我完全是VBA的新手,但到目前为止,我在Google中找不到任何解决方案。我找到了2个单独的代码,但是当组合解决方案时却没有找到
我有一个删除有条件的重复行的问题
column b column z
1 22/1/2019
2 22/1/2019
1 23/1/201
2 23/1/2019
结果
column b column z
1 23/1/2019
2 23/1/2019
我的代码(使用for进行嵌套时出现问题)
Sub Macro1()
Dim RowsToDelete As Range, innerRow As Long
Set TheRng = Intersect(ActiveSheet.UsedRange, ActiveSheet.Range("B:Z"))
xx = TheRng.Value
innerRow = 1
For i = UBound(xx) To 2 Step -1
Do While ActiveSheet.Range("b" & Row) <> ""
If ActiveSheet.Range("b" & Row) = ActiveSheet.Range("b" & innerRow) Then
For j = i - 1 To 1 Step -1
If ActiveSheet.Range("Z" & Row) < ActiveSheet.Range("Z" & innerRow) Then
Set RowsToDelete = Union(IIf(RowsToDelete Is Nothing, TheRng.Cells(i, 1), RowsToDelete), TheRng.Cells(i, 1))
Exit For
End If
Next j
Loop
RowsToDelete.EntireRow.Select 'Delete
End Sub
答案 0 :(得分:2)
您似乎想从B列中删除重复项,但将行的最新日期保留在Z列中。
RemoveDuplicates通常会删除具有最大行号(最靠近数据底部)的重复项,因此对数据进行降序排序,使日期降序,以最新日期位于顶部,并删除重复项。
Sub Macro1()
With Worksheets("sheet1")
'With .Range(.Cells(1, "B"), .Cells(.Rows.Count, "Z").End(xlUp))
With Intersect(.UsedRange, .Range("B:Z"))
.Sort key1:=.Columns(1), order1:=xlAscending, _
key2:=.Columns(.Columns.Count), order2:=xlDescending, _
Header:=xlNo
.RemoveDuplicates Columns:=1, Header:=xlNo
End With
End With
End Sub