使用VLOOKUP搜索不同的工作表

时间:2014-10-04 13:48:44

标签: excel vba excel-vba

我正在尝试搜索我工作簿中的32张表中是否存在某个数字。 我试图使用下面提到的代码,但它不起作用,因为VLOOKUP没有解密变量(n)。请帮助:

Private Sub SearchAll_Click()
Dim SearchCriteria As Double, s As Integer
SearchCriteria = Me.SearchBox.Value
s = 0
For s = 0 To ThisWorkbook.Sheets.Count
s = s + 1
    If Application.WorksheetFunction.VLookup(SearchCriteria, Sheets(s).Range("A:A").Value, 1, False) = SearchCriteria Then
MsgBox ("The Number " & SearchCriteria & " is available in list " & Sheets(s).Name)
Exit For
Else
MsgBox ("The Number is Unavailable")
End If
Next s
End Sub

图例:

  • SearchAll是用于启动搜索的按钮。
  • SearchCriteria是用于输入您要搜索的值的文本框。

1 个答案:

答案 0 :(得分:1)

使用Application.WorksheetFunction.VLookup确定工作簿中是否存在特定值的方式存在一些问题。我已将您的代码修改为以下内容:

Private Sub SearchAll_Click()
    Dim SearchCriteria As Double, s As Integer
    Dim Lookup As Variant
    Dim Match As Boolean

    SearchCriteria = Me.SearchBox.Value

    For s = 1 To ThisWorkbook.Sheets.Count
        Lookup = Application.VLookup(SearchCriteria, Sheets(s).Range("A:A"), 1, False)
        If Not IsError(Lookup) Then
            MsgBox ("The Number " & SearchCriteria & " is available in list " & Sheets(s).Name)
            Match = True
            Exit For
        End If
    Next s

    If Match = False Then MsgBox ("The Number is Unavailable")
End Sub

相反,我在这里使用了Application.VLookup,如果在特定工作表中找不到搜索值,它会向变量变量Lookup返回错误。然后,通过查看Lookup的错误状态,可以确定是否找到了搜索值。另外,我已将消息The Number is Unavailable移到循环外部,以避免每次在特定工作表中找不到值时触发它。

相关问题