突出显示不同工作表上两个范围之间的重复项

时间:2015-08-17 20:01:06

标签: excel vba duplicates highlight

我正在尝试找到一种更有效的方法来突出显示不同工作表上两个范围之间的重复单元格。下面的代码非常缓慢:

    Sub HighlightDuplicates()
Application.DisplayAlerts = False

lrU = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
lrPT = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row

Dim rng1, rng2, cell1, cell2 As Range

Set rng1 = Worksheets("Sheet1").Range("DL4:DL" & lrU)
Set rng2 = Worksheets("Sheet2").Range("E3:M" & lrPT)

    For Each cell1 In rng1

        For Each cell2 In rng2

            If cell1.Value = cell2.Value Then

            cell1.Font.Bold = True
            cell1.Font.ColorIndex = 2
            cell1.Interior.ColorIndex = 3
            cell1.Interior.Pattern = xlSolid
            cell2.Font.Bold = True
            cell2.Font.ColorIndex = 2
            cell2.Interior.ColorIndex = 3
            cell2.Interior.Pattern = xlSolid

            End If

        Next cell2
     Next cell1
Application.DisplayAlerts = True
End Sub

有关更有效方法的任何建议吗?

感谢您的帮助。

此致

1 个答案:

答案 0 :(得分:1)

将我的评论放在一起,你可以修改你的代码看起来像这样(未经测试)

Sub HighlightDuplicates()
Application.DisplayAlerts = False
application.calculation=xlcalculationmanual
application.screenupdating=false

lrU = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
lrPT = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row

Dim rng1, rng2, cell1, cell2 As Range

Set rng1 = Worksheets("Sheet1").Range("DL4:DL" & lrU)
Set rng2 = Worksheets("Sheet2").Range("E3:M" & lrPT)

For Each cell2 In rng2
    Set cell1 = rng1.Find(cell2, lookin:=xlValues)
    if not cell1 is nothing then
        firstAddress = cell1.address
        Do
            cell1.Font.Bold = True
            cell1.Font.ColorIndex = 2
            cell1.Interior.ColorIndex = 3
            cell1.Interior.Pattern = xlSolid
            cell2.Font.Bold = True
            cell2.Font.ColorIndex = 2
            cell2.Interior.ColorIndex = 3
            cell2.Interior.Pattern = xlSolid
            Set cell1 = rng1.FindNext(cell2)
        Loop While Not cell1 Is Nothing And cell1.Address <> firstAddress 
    end if
next cell1

application.displayalerts=true
application.calculation=xlcalculationmanual
application.screenupdating=true
end sub