使用VBA查找重复行

时间:2016-02-13 19:11:59

标签: vba excel-vba filter find duplicates

我需要在VBA中识别重复的行(注意:重复的行意味着所考虑的所有列上的原始行的值相等)。我发现有几个程序可以基于某个列来执行此操作,并且我知道可以使用Range.RemoveDuplicates Method (Excel)快速找到并删除重复的行,但是这对我的识别没有帮助。假设给出以下行:

EE  10  12  13
jk  56  AA  00
BB  32  af  12
21  CC  CC  fg
as  DD  89  fg
AA  67  45  vb
fh  56  df  kl
cv  fh  CC  34
af  xv  DD  67
EE  10  12  13

在此示例中,将标识第一行和最后一行(在函数中返回或以某种类型的颜色标记)。请注意,我不想删除它们,而是将它们保存在新工作表上,但这不是问题。问题只是识别。

根据我的实际数据,我有大约30,000行,因此性能也非常重要。

2 个答案:

答案 0 :(得分:1)

也许是这样的:

Sub highlight()

    firstRow = 2
    lastrow = 30

    For j = firstRow To lastrow
        If Range(Cells(j, 1), Cells(j, 4)).Interior.Color = 255 Then
            'already highlighted, found to be duplicate.  Skip.
        For i = firstRow + 1 To lastrow
            If Range(Cells(i, 1), Cells(i, 4)).Interior.Color = 255 Then
                'already highlighted, found to be duplicate.  Skip.
            ElseIf Cells(i, 1) & Cells(i, 2) & Cells(i, 3) & Cells(i, 4) _
                = Cells(j, 1) & Cells(j, 2) & Cells(j, 3) & Cells(j, 4) Then
                'Dupe found, highlight as red
                Range(Cells(i, 1), Cells(i, 4)).Interior.Color = 255
            End If
        Next
    Next

End Sub

此解决方案需要嵌套循环。重要的是跳过已经发现为欺骗的项目,我使用突出显示。

未经测试,但应该接近。

答案 1 :(得分:0)

Sub szukanie()

    firstRow = 1
    lastrow = 13

    For j = firstRow To lastrow
        If Range(Cells(j, 1), Cells(j, 4)).Interior.Color = 255 Then
                For i = firstRow + 1 To lastrow
                    If Range(Cells(i, 1), Cells(i, 4)).Interior.Color = 255 Then
                        ElseIf Cells(i, 1) & Cells(i, 2) & Cells(i, 3) & Cells(i, 4) = Cells(j, 1) & Cells(j, 2) & Cells(j, 3) & Cells(j, 4) Then

                            Range(Cells(i, 1), Cells(i, 4)).Interior.Color = 255

                    End If
                Next
        End If
    Next

End Sub

但是您必须突出显示第一行