2017-09-26 112 views
1

當G,H,I列中的單元格中的所有3個數值都相等時,我想要刪除整行。我寫了一個vba代碼,它不會刪除任何內容。可以有人建議?Excel 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 

回答

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

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