我有一个包含许多重复项的大型工作表。重复项在E列中,我必须删除列L中编号最小的那些。我正在使用此代码:
Sub Duplicados()
Dim i, lr
Application.ScreenUpdating = False
Application.EnableEvents = False
ActiveSheet.UsedRange.Sort Key1:=Range("E2"), Order1:=xlAscending, Key2:=Range("L2") _
, Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1
lr = Cells(Rows.Count, "L").End(xlUp).Row
For i = lr - 1 To 1 Step -1
If Cells(i, "E").Value = Cells(i + 1, "E") Then
Rows(i).EntireRow.Delete
End If
Next i
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
然而,它太慢了,我想知道是否有更好的方法来做到这一点。
答案 0 :(得分:1)
您的代码耗时太长的一个原因是它一次删除一行。您可以做的一件事是加快当前结构的进程,首先要识别需要删除的所有行,然后一次删除它们。有关使用Union
方法执行此操作的方法,请参阅以下示例:
Dim rr As Range
Dim i As Long
Dim lr As Long
ActiveSheet.UsedRange.Sort Key1:=Range("E2"), Order1:=xlAscending, Key2:=Range("L2") _
, Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1
lr = Cells(Rows.Count, "L").End(xlUp).Row
For i = lr - 1 To 1 Step -1
If Cells(i, "E") = Cells(i + 1, "E") Then
If rr Is Nothing Then
Set rr = Cells(i, 1)
Else: Set rr = Union(rr, Cells(i, 1))
End If
End If
Next i
rr.EntireRow.Delete