Excel VBA脚本删除最新的重复记录

时间:2010-08-17 16:50:32

标签: excel excel-vba vba

工作表首先根据A列(帐号)排序,然后按C列(日期)排序。

我有以下脚本删除重复记录并保留最新记录。

Sub DeleteTheOldies()  
Dim RowNdx As Long  
For RowNdx = Range("a1").End(xlDown).Row To 2 Step -1  
Do While Cells(RowNdx, "a").Value = Cells(RowNdx - 1, "a").Value  
If Cells(RowNdx, "c").Value <= Cells(RowNdx - 1, "c").Value Then  
Rows(RowNdx).Delete  
Else  
Rows(RowNdx - 1).Delete  
End If  
RowNdx = RowNdx - 1  
If RowNdx = 1 Then Exit Sub  
Loop  
Next RowNdx  
End Sub  

示例数据:

Column A     Column B   Column C  
751063031 1605621498 03-JUL-10  
751063031 5600003138 18-JUL-10  
751063031 5600084443 17-AUG-10  
754199715 1605621498 27-FEB-10  
754199715 5600084438 17-AUG-10  
757129104 5600084892 12-NOV-09  
757129104 5600084438 17-AUG-10  
757307416 1605621498 27-FEB-10  
757307416 5600084438 17-AUG-10  

当前脚本的输出:

751063031 5600084443 17-AUG-10  
754199715 5600084438 17-AUG-10  
757129104 5600084438 17-AUG-10  
757307416 5600084438 17-AUG-10  

我需要修改版本的脚本来提供以下输出(删除最新的并保留其余部分)

751063031 1605621498 03-JUL-10  
751063031 5600003138 18-JUL-10  
754199715 1605621498 27-FEB-10  
757129104 5600084892 12-NOV-09  
757307416 1605621498 27-FEB-10    

1 个答案:

答案 0 :(得分:0)

尝试以下方法。这将适用于您上面的示例。如果您有其他约束/要求,可能需要进行调整。

Sub NewStuff()

    Dim RowNdx As Long
    Dim CurVal As String

    For RowNdx = 1 To Range("a1").End(xlDown)

        If Cells(RowNdx, "a").Value = Empty Then

            Exit For

        End If

        If Cells(RowNdx, "a").Value <> Cells(RowNdx + 1, "a").Value Then

            Rows(RowNdx).Delete
            RowNdx = RowNdx - 1

        End If

    Next RowNdx

End Sub