Excel 修改VBA代码以删除除前两行之外的所有重复项
我发现下面的代码在提取我需要的数据方面做得很好,但是我现在需要修改它。当前,它基于活动列删除所有重复行,并保留第一行 我需要在另一列上运行它,并删除除前两行之外的所有重复项 我不知道如何改变它 非常感谢Excel 修改VBA代码以删除除前两行之外的所有重复项,excel,vba,Excel,Vba,我发现下面的代码在提取我需要的数据方面做得很好,但是我现在需要修改它。当前,它基于活动列删除所有重复行,并保留第一行 我需要在另一列上运行它,并删除除前两行之外的所有重复项 我不知道如何改变它 非常感谢 Public Sub DeleteDuplicateRows() ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' DeleteDuplicateRows ' This will del
Public Sub DeleteDuplicateRows()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' DeleteDuplicateRows
' This will delete duplicate records, based on the Active Column. That is,
' if the same value is found more than once in the Active Column, all but
' the first (lowest row number) will be deleted.
'
' To run the macro, select the entire column you wish to scan for
' duplicates, and run this procedure.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim R As Long
Dim N As Long
Dim V As Variant
Dim Rng As Range
On Error GoTo EndMacro
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set Rng = Application.Intersect(ActiveSheet.UsedRange, _
ActiveSheet.Columns(ActiveCell.Column))
Application.StatusBar = "Processing Row: " & Format(Rng.Row, "#,##0")
N = 0
For R = Rng.Rows.Count To 2 Step -1
If R Mod 500 = 0 Then
Application.StatusBar = "Processing Row: " & Format(R, "#,##0")
End If
V = Rng.Cells(R, 1).Value
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Note that COUNTIF works oddly with a Variant that is equal to vbNullString.
' Rather than pass in the variant, you need to pass in vbNullString explicitly.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If V = vbNullString Then
If Application.WorksheetFunction.CountIf(Rng.Columns(1), vbNullString) > 1 Then
Rng.Rows(R).EntireRow.Delete
N = N + 1
End If
Else
If Application.WorksheetFunction.CountIf(Rng.Columns(1), V) > 1 Then
Rng.Rows(R).EntireRow.Delete
N = N + 1
End If
End If
Next R
EndMacro:
Application.StatusBar = False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Duplicate Rows Deleted: " & CStr(N)
End Sub
要保留前两行,请将For循环更改为
For R = Rng.Rows.Count To 2 Step -1
致:
要处理其他列,请更改此行
Set Rng = Application.Intersect(ActiveSheet.UsedRange, _
ActiveSheet.Columns(ActiveCell.Column))
例如:
Set Rng = Application.Intersect(ActiveSheet.UsedRange, _
ActiveSheet.Range("A1").EntireColumn))
其中A列是要使用的列
Set Rng = Application.Intersect(ActiveSheet.UsedRange, _
ActiveSheet.Range("A1").EntireColumn))