IMZRH的日志

努力成为一个有用的人

导航

如何在Excel中通过VBA快速查找多列重复的值

Posted on 2016-07-20 16:32  张荣华  阅读(7270)  评论(0编辑  收藏  举报

今天项目组的一个同事问我如何快速的找到一个Excel中第3列和第5列的值完全重复的值,我想了想虽然Excel中自带查找重复值的功能,但是好像只能对同一列进行比较,所以就写了一个VBA进行处理,VBA非常简单,但效果不错。

Sub FindDuplicatesInColumn()

    Dim lastRow As Long
    Dim matchFoundIndex As Long
    Dim iCntr As Long
    lastRow = 500
    
    ' 初始化临时列, 第7列用来存放结果,第8列将3 5两列的值拼接起来,方便判断
    For iCntr = 2 To lastRow
        Cells(iCntr, 7) = ""
        Cells(iCntr, 8) = Cells(iCntr, 3) & Cells(iCntr, 5)
    Next iCntr
    
    For iCntr = 2 To lastRow
        If Cells(iCntr, 5) <> "" Then
            ' 判断是否存在相等的拼接后的列,如果存在,则记录到结果中
            matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 8), Range("H1:H" & lastRow), 0)
            If iCntr <> matchFoundIndex Then
                Cells(iCntr, 7) = "Duplicate with " & matchFoundIndex
            End If
        End If
    Next iCntr
End Sub