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

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

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 

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

 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 

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

请给这个尝试…

 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 

您可以使用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