【问题标题】:Excel VBA how to search through 2d arrayExcel VBA如何搜索二维数组
【发布时间】:2017-02-07 05:44:19
【问题描述】:

基本上,我试图循环遍历数组中的所有值,并计算大于用户指定值的值的数量,方法是使用 Inputbox 并尝试使用 IF 语句来确保介于 1 和输入 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 语句来验证用户输入的内容并循环遍历数组。

【问题讨论】:

  • 我假设您希望在 if 语句中使用 or,因为 val 不能同时小于 1 和大于 100。
  • 啊对的好点!

标签: excel vba


【解决方案1】:

我建议以下方法,通过使用内置的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."

【讨论】:

    【解决方案2】:

    我会

    • 使用 Application.InputBox() 可以强制输入数字

    • 避免使用数组并使用 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)
    

    【讨论】:

    • 我正在寻找那个 (Application.InputBox)。我的记忆让我不知道正确的语法是什么......所以我认为我的记忆只是让我在 InputBox 能够强制一个整数上失败:(
    • @ScottHoltzman,是的,它很有用。我什至更喜欢IsNumeric(),因为后者不可靠(例如:?IsNumeric("1..2") 返回True...)
    【解决方案3】:
    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
    

    【讨论】:

    • 是否有办法仅使用 If/Else 语句来验证 val?
    • 在我看来循环更好的情况下,你为什么坚持使用 if 语句。
    • 因为我打算使用另一个循环来计算数组中的值大于在 val 中输入的值。在这种情况下试图避免在循环中出现循环
    • 试试我发布的答案,看看它是否满足您的需求。
    • 我应该将单元格调暗为范围以避免弹出另一个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2017-09-06
    • 2015-06-27
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    相关资源
    最近更新 更多