如果重复则删除行,然后在另一列上过滤

时间:2016-02-07 10:09:30

标签: excel-vba vba excel

我正在过滤一个包含大量赛马信息的表格。我已经完成了8个过滤器中的7个,但我正在努力完成最后一个过滤器。基本上所有我需要的是查看比赛时间(col B)的列,如果有2次相同则显然在​​比赛中有2个选项。我只想要一个选择,所以接下来我要删除/过滤基于C列的行,即C,即Trainer win%。无论哪个是我需要保持的更大%。如果他们是相同的可能会把msgbox这样说,或者我可能必须使用第3个字段进行过滤。我找到了一段接近的代码。

Sub text()      
Dim j As Integer, k As Integer, r As Range      
j = Range("E2").End(xlDown).Row      
For k = j To 2 Step -1      
    MsgBox k      
    Set r = Range(Cells(k, "E"), Cells(k, "E").End(xlUp))      
    If WorksheetFunction.CountIf(r, Cells(k, "E")) > 1 Then      
        Cells(k, "E").EntireRow. Delete      
    End If      
Next k      
End Sub 

1 个答案:

答案 0 :(得分:1)

按训练者胜率百分比(降序)对数据进行排序,然后在时间上使用Range.RemoveDuplicates method

Sub tract()
    With Worksheets("Sheet6")    '<~~ you should know which worksheet you are on
        With .Cells(1, 1).CurrentRegion
            'sort on the trainer win percentage (descending)
            .Cells.Sort Key1:=.Columns(3), Order1:=xlDescending, _
                        Orientation:=xlTopToBottom, Header:=xlYes
            'remove duplicate times - the lower rows will be deleted
            .RemoveDuplicates Columns:=2, Header:=xlYes
        End With
    End With
End Sub

删除重复项始终删除较低的条目;使条目更接近顶部。这就是为什么首先对训练员胜率进行排序很重要。这并不考虑胜率百分比也是重复的情况。在这种情况下,必须添加另一个排序键。如果列Z是决定因素,并且您希望保留较低的值,那么它将类似于以下内容。

Sub tract()
    With Worksheets("Sheet6")    '<~~ you should know which worksheet you are on
        With .Cells(1, 1).CurrentRegion
            'sort on the trainer win percentage (descending) and columns Z (ascending)
            .Cells.Sort Key1:=.Columns(3), Order1:=xlDescending, _
                        Key2:=.Columns(26), Order2:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes
            'remove duplicate times - the lower rows will be deleted
            .RemoveDuplicates Columns:=2, Header:=xlYes
        End With
    End With
End Sub