Excel VBA如何通过二维数组进行search

基本上我试图循环通过数组中的所有值,并计数大于用户通过使用Inputbox指定的值的数量,也试图使用IF语句,以确保input1和100之间的数字。 之后,我只是想简单地显示在一个消息框后的结果。

这是我到目前为止:

Dim arr As Variant arr = Range("A1:J10") Range("A1").Resize(UBound(arr, 1), UBound(arr, 2)) = arr Dim val As String val = InputBox("Enter an integer value") If val < 1 Or val > 100 Then ' tells the user to try again MsgBox "You did not enter a value from 1 to 100 , try again" val = Inputbox("Enter an integer value") Else End If 

基本上用if语句来validation用户input的内容并循环访问数组。

 Dim val As String val = InputBox("Enter an integer value") Do While val < 1 Or val > 100 ' tells the user to try again MsgBox "You did not enter a value from 1 to 100 , try again" val = InputBox("Enter an integer value") Loop 'checks array if the number is greater then input number Dim MyRange As Range Dim cell As Range Dim counter as integer counter = 0 Set MyRange = Range("A1:J10") For Each cell In MyRange If cell.Value > CInt(val) Then counter = counter + 1 cell.Interior.Color = RGB(255, 0, 0) 'or cell.Interior.ColorIndex = 3 End If Next msgbox "Total number greater then input number is: " & counter 

我build议下面的内容,通过使用内置的CountIF函数来摆脱循环和数组。

 Do Dim val As Variant val = InputBox("Enter an integer value") If IsNumeric(val) And val > 1 And val < 100 Then Dim bPass As Boolean bPass = True End If If Not bPass Then MsgBox "You did not enter a value from 1 to 100 , try again" Loop Until bPass Dim lCountIf As Long lCountIf = WorksheetFunction.CountIf(Range("A1:J10"), ">" & val) MsgBox lCountIf & " values greater than " & val & "in Range." 

ID

  • 使用Application.InputBox(),它可以让你强制数字input

  • 避免数组并使用WorksheetFunction.CountIf()

如下:

 Dim val As Integer Do val = CInt(Application.InputBox(prompt:="Enter an integer value between 1 and 100", Type:=1)) Loop while val <1 And val > 100 MsgBox WorksheetFunction.CountIf(Range("A1:J10"), ">" & val)