我試圖刪除工作表中的所有重複項,條件是一列中的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
錯誤應該在這行'如果WorksheetFunction.CountIf(rRange,.Value)> 1 Then'。當你根據你的'With'語句調用'.Value'時,excel會返回一個數組,而不是一個條件。嘗試爲您的場景使用'CountIfs'函數 – Rosetta
儘量不要使用'lCount'來計算行數和迭代次數。您可以聲明一個單獨的變量,例如爲了達到迭代的目的。這使得你的代碼不會對自己產生困惑 – Rosetta