【发布时间】:2016-07-12 20:16:29
【问题描述】:
我想根据列中的重复值删除 Excel 中的行。比方说
Column A Column B
ABC 1
DEF 2
DEF 3
ABC 1
在B 列中,我们有一个重复值。仅使用删除重复功能没有帮助。
【问题讨论】:
我想根据列中的重复值删除 Excel 中的行。比方说
Column A Column B
ABC 1
DEF 2
DEF 3
ABC 1
在B 列中,我们有一个重复值。仅使用删除重复功能没有帮助。
【问题讨论】:
嗯,这段代码完美运行
ActiveSheet.Range("$A$1:$B$4").RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo
【讨论】:
ActiveSheet.Range([data_range]).RemoveDuplicates Columns:=[column_number], Header:=xlNo
也许不是最优化的解决方案,但它确实有效
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
【讨论】: