Excel VBA在一行循环中删除三重复

时间:2017-09-26 11:37:10

标签: excel vba excel-vba

当列G,H,I中单元格中的所有3个数值相等时,我想删除整行。我写了一个vba代码,它不会删除任何内容。有人可以建议吗?

Sub remove_dup()

Dim rng As Range
Dim NumRows As Long
Dim i As Long


Set rng = Range("G2", Range("G2").End(xlDown))
NumRows = Range("G2", Range("G2").End(xlDown)).Rows.Count

For i = 2 To NumRows

Cells(i, 7).Select
If Cells(i, 7).Value = Cells(i, 8).Value = Cells(i, 9).Value Then
EntireRow.Delete
Else
Selection.Offset(1, 0).Select
End If

Next i

End Sub

3 个答案:

答案 0 :(得分:1)

试试这段代码。删除行时,始终从最后一行开始,然后朝第一行开始。这样你肯定不会跳过任何一行。

Sub remove_dup()
Dim rng As Range
Dim NumRows As Long
Dim i As Long

NumRows = Range("G2", Range("G2").End(xlDown)).Rows.Count
For i = NumRows + 1 To 2 Step -1
        If Cells(i, 7).Value = Cells(i, 8).Value And Cells(i, 7).Value = Cells(i, 9).Value Then
                    Cells(i, 7).EntireRow.Delete
        Else
        End If
Next i
End Sub

答案 1 :(得分:1)

您可以使用UNION一起删除所有行。试试这个

Sub remove_dup()
    Dim ws As Worksheet
    Dim lastRow As Long, i As Long
    Dim cel As Range, rng As Range

    Set ws = ThisWorkbook.Sheets("Sheet4")  'change Sheet3 to your data range
    With ws
        lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row    'last row with data in Column G
        For i = lastRow To 2 Step -1    'loop from bottom to top
            If .Range("G" & i).Value = .Range("H" & i).Value And .Range("G" & i).Value = .Range("I" & i).Value Then
                If rng Is Nothing Then          'put cell in a range
                    Set rng = .Range("G" & i)
                Else
                    Set rng = Union(rng, .Range("G" & i))
                End If
            End If
        Next i
    End With
    rng.EntireRow.Delete    'delete all rows together
End Sub

答案 2 :(得分:1)

请记住,当您删除行时,您需要以相反的顺序循环。

请试一试......

Sub remove_dup()
Dim NumRows As Long
Dim i As Long

NumRows = Cells(Rows.Count, "G").End(xlUp).Row

For i = NumRows To 2 Step -1
    If Application.CountIf(Range(Cells(i, 7), Cells(i, 9)), Cells(i, 7)) = 3 Then
        Rows(i).Delete
    End If
Next i

End Sub