Microsoft VBA比较两列并显示错误消息

时间:2017-07-17 17:48:33

标签: vba excel-vba excel

我有两张“Sheet A”和“Sheet B”,“Sheet A”包含一些数据,“Sheet B”包含所有数据。因此,如果我“工作表A”没有任何数据,而这些数据在工作表B中不存在,我想显示信息。

VBA代码

Private Sub CommandButton1_Click()
Dim myRng As Range
    Dim lastCell As Long

    'Get the last row
    Dim lastRow As Integer
    lastRow = ActiveSheet.UsedRange.Rows.Count

    'Debug.Print "Last Row is " & lastRow

    Dim c As Range
    Dim d As Range

    Application.ScreenUpdating = False

    For Each c In Worksheets("Sheet1").Range("A2:A" & lastRow).Cells
        For Each d In Worksheets("Sheet2").Range("A2:A" & lastRow).Cells
            c.Interior.Color = vbRed
            If (InStr(1, d, c, 1) > 0) Then
                c.Interior.Color = vbWhite
                Exit For
            End If
        Next
    Next

    For Each c In Worksheets("Sheet2").Range("A2:A" & lastRow).Cells
        For Each d In Worksheets("Sheet1").Range("A2:A" & lastRow).Cells
            c.Interior.Color = vbRed
            If (InStr(1, d, c, 1) > 0) Then
                c.Interior.Color = vbWhite
                Exit For
            End If
        Next
    Next

Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

如果您有基于列的数据,可以尝试此公式。这将在您的数据旁边的工作表A上(A1是您的数据,B1是公式)和查找工作表A列A与工作表B(matchRange =工作表B,列x)。

=IF(ISNUMBER(MATCH(LookupValue,MatchRange,0)),"Yes","No")