根据Column中的重复项删除Excel中的行

时间:2016-07-12 10:57:09

标签: excel excel-vba vba

我想根据列中的重复值删除Excel中的行。让我们说

Column A      Column B
ABC             1
DEF             2
DEF             3
ABC             1

B列中,我们有一个重复的值。仅使用删除重复功能并没有帮助。

2 个答案:

答案 0 :(得分:0)

嗯,这段代码完美无缺

ActiveSheet.Range("$A$1:$B$4").RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo

答案 1 :(得分:0)

可能不是最优化的解决方案,但它可以完成工作

Public Sub DeleteDuplicates()
    Dim rng As Range, cell As Range, find As Range, previous As Range
    Set rng = Worksheets("Test").Range("A:A")

    ' For each cell of the column
    For Each cell In rng
        ' Check duplicates only if the cell is not empty
        If Trim(cell) <> "" Then
            ' Search for the same value in column A
            Set find = rng.find(What:=cell, After:=cell, LookAt:=xlWhole, MatchCase:=True)
            ' if a result is found
            If Not find Is Nothing Then
                Do
                    Set previous = Nothing
                    ' If the column B is the same, save the row as "to be deleted"
                    ' The delete is not now otherwise the FindNext won't work
                    If find.Offset(, 1) = cell.Offset(, 1) Then
                        Set previous = find
                    End If

                    Set find = rng.FindNext(find)

                    ' If a duplicate was found, delete the raw
                    If Not previous Is Nothing Then
                        previous.EntireRow.Delete
                    End If

                    ' if no more duplicate, exit the do loop
                    If find Is Nothing Then
                        Exit Do
                    End If

                    ' if address of the result is the same as the clel, exit the do loop
                    If cell.Address = find.Address Then
                        Exit Do
                    End If
                Loop While True
            End If
        End If
    Next
End Sub