宏基于两个单元格删除工作表中的重复项

时间:2016-02-26 18:49:13

标签: excel vba excel-vba macros

我尝试删除工作表中的所有重复项,条件是在任何其他行的A和B列中重复一行A和B列中的值。列数无关紧要。有人能说明我出错的地方吗?

我当前的代码:

Sub RemoveDuplicate()
    Dim rCell As Range
    Dim rRange As Range
    Dim lCount As Long
    Dim sh As Worksheet

    Set sh = ThisWorkbook.Sheets("Data")
    lCount = sh.Range("A2", sh.Range("A2").End(xlDown)).Rows.Count + 1
    Set rRange = sh.Range("A2:B" & lCount)

    For lCount = lCount To 1 Step -1
        With rRange("A" & lCount & ",B" & lCount)
            If WorksheetFunction.CountIf(rRange, .Value) > 1 Then
                .EntireRow.Delete
            End If
        End With
    Next lCount

End Sub

示例:

|  A  |  B  |
|00001|12345| - KEEP
|00002|12345| - KEEP
|00003|12345| - KEEP
|00001|12346| - KEEP
|00001|12346| - REMOVE
|00001|12347| - KEEP
|00004|12345| - KEEP
|00002|12345| - REMOVE

固定代码:

Sub RemoveDuplicate()
    Dim lCount As Long
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Data")
    lCount = sh.Range("A2", sh.Range("A2").End(xlDown)).Rows.Count + 1
    sh.Range("A1:B" & lCount).RemoveDuplicates Columns:=Array(1,2), Header:=xlYes
End Sub

2 个答案:

答案 0 :(得分:1)

只需使用内置重复删除的excel,例如

  

ActiveSheet.Range(“A1:B100”)。RemoveDuplicates Columns:= Array(1,2),   头:= xlYes

答案 1 :(得分:0)

我的意思是:

此块

With rRange("A" & lCount & ",B" & lCount)
    If WorksheetFunction.CountIf(rRange, .Value) > 1 Then
        .EntireRow.Delete
    End If
End With

应该是

If worksheetfunction.countifs( _
    sh.range("A2:A" & lcount), sh.range("A" & lcount), _
    sh.range("B2:B" & lcount), sh.range("B" & lcount)) > 0 Then 

    sh.range("A" & lcount).Entirerow.delete
end if