突出显示两张2张工作簿之间的重复项

时间:2017-03-08 11:36:32

标签: excel-vba vba excel

我正在创建一个宏来比较两个工作簿的工作表。如果在另一个工作簿的工作表中发现重复,我需要突出显示该行。到目前为止,我一直在搜索,我找到了代码,但我不知道如果它在另一张工作簿的另一张表中找到重复,我怎么能突出显示单元格/整行。以下是我的代码:

Sub CompareWorkbooks()

Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long



strRangeToCheck = "B2:D49"

Set wbkA = ActiveWorkbook 
Set varSheetA = wbkA.Worksheets("SAP").Range(strRangeToCheck)
Set wbkB = Workbooks.Open(FileName:="C:\Request Distribution\Reminder 20170302.xls")
Set varSheetB = wbkB.Worksheets("SAP").Range(strRangeToCheck)

For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
    If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then

       'What to put to hightlight the cell / entire row

    Else

    'Some msgbox to display that there are no duplicates between sheets of 2 workbooks

    End If
Next
Next

End Sub

1 个答案:

答案 0 :(得分:1)

Sub CompareWorkbooks()

Dim varSheetA As Range
Dim varSheetB As Range
Dim r As Range
Dim wbkA As Workbook
Dim rFind As Range

Set wbkA = ActiveWorkbook
With wbkA.Worksheets("SAP")
    .UsedRange.Interior.ColorIndex = xlNone
    Set varSheetA = .Range("B2", .Range("B" & Rows.Count).End(xlUp))
End With
Set wbkB = Workbooks.Open(Filename:="C:\Request Distribution\Reminder 20170302.xls")
Set varSheetB = wbkB.Worksheets("SAP").Range(varSheetA.Address)

For Each r In varSheetA
    Set rFind = varSheetB.Find(What:=r, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        r.Interior.Color = RGB(127, 187, 199)
    End If
Next r

End Sub