excel vba搜索匹配项

时间:2019-04-07 17:43:31

标签: excel vba

我在Sheet1 A1中有一个日期,在Sheet2的A列中填充了日期

我正在寻找某种东西,将其分配给按钮并按下时将向下查看Sheet2列A,如果任何日期与Sheet1 A1相匹配,它将显示一个消息框,指出已找到匹配项,如果未找到匹配项,则会弹出一个消息框,提示找不到匹配项

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用此代码。但是,如果需要,请不要忘记更改第二个工作表的名称。

Private Sub CommandButton1_Click()

    Dim cell As Variant
    Dim rangeSheet As Worksheet
    Set rangeSheet = Worksheets("Sheet2")
    Dim checker As Boolean
        checker = False

    Dim lastRow As Variant
        lastRow = rangeSheet.Cells(Rows.Count, "A").End(xlUp).Row

    For Each cell In rangeSheet.Range("A1:A" & lastRow)
        If cell.Value = ActiveCell.Value Then
            checker = True
            Exit For
        End If
    Next cell

    If checker = True Then
        MsgBox ("Found")
    Else
        MsgBox ("Not found")
    End If

End Sub

答案 1 :(得分:0)

尝试一下并告诉我

Option Explicit

Private Sub CommandButton1_Click()

    Dim Sheet1 As Worksheet, Sheet2 As Worksheet
    Dim TheDate As String
    Dim c As Range
    Dim Last As Integer

    'Put your own name for your Worksheets
    Set Sheet1 = Worksheets("Feuil1")
    Set Sheet2 = Worksheets("Feuil2")

    'I put the value that you are looking for in the first Worksheets in cells B1
    TheDate = Sheet1.Range("B1").Value

    Last = Sheet2.Range("a65000").End(xlUp).Row

    'All your date are only in the columns A
    Set c = Sheet2.Range("A1:A" & Last).Find(TheDate, LookIn:=xlValues)


    If Not c Is Nothing Then
        MsgBox ("Found ! : " & c.Address)
        Set c = Nothing
    Else
        MsgBox "No match for : " & TheDate
    End If
End Sub