如何匹配/搜索excel VBA中Sheet2.Range(“A1:A10”)中的Sheet1.Range(“A1”)的值

时间:2017-02-15 14:39:21

标签: vba excel-vba excel

假设我在Sheet1.Range("A1")

中有这个值“ABC123”

我想在Sheet2.Range(“A1:A10”)//或列

中搜索/匹配此值
If the value is found
      //msgbox "Found"
else
     //msgbox "Not found"
end if

4 个答案:

答案 0 :(得分:1)

试试这个:

Sub foo()
    Dim t As Long
        On Error Resume Next
        t = Application.WorksheetFunction.Match(Worksheets("Sheet1").Range("A1"), Worksheets("Sheet2").Range("A:A"), 0)
        On Error GoTo 0
        If t > 0 Then
            MsgBox "Found"
        Else
            MsgBox "Not found"
        End If
End Sub

答案 1 :(得分:1)

尝试使用下面的Match功能(您将获得行号):

Option Explicit

Sub MatchTest()

Dim MatchRes As Variant

MatchRes = Application.Match(Worksheets("Sheet1").Range("A1").Value, Worksheets("Sheet2").Range("A1:A10"), 0)
If IsError(MatchRes) Then
    MsgBox "Not found"
Else
    MsgBox "Found at row " & MatchRes
End If

End Sub

答案 2 :(得分:1)

考虑:

Sub dural()
    Dim s As String, r1 As Range, r2 As Range, r3 As Range

    Set r1 = Sheet1.Range("A1")
    Set r2 = Sheet2.Range("A1:A10")
    s = r1.Value

    Set r3 = r2.Find(what:=s, after:=r2(1))
    If r3 Is Nothing Then
        MsgBox "not found"
    Else
        MsgBox "Found"
    End If
End Sub

答案 3 :(得分:0)

只是在斯科特的解决方案中玩一下:

Sub foo2()
    Dim t As Long
    On Error GoTo NotFound
    t = Application.WorksheetFunction.Match(Worksheets("Sheet1").Range("A1"), Worksheets("Sheet2").Range("A:A"), 0)
    MsgBox "Found
    Exit Sub      
NotFound:
    MsgBox "Not found"
End Sub