VBA:search子string和删除整行

我试图删除P列中包含“H”的string的所有行。 macros的工作,但是,它只能删除每一次必要的行的一半。 这是因为代码中的For循环 – 当一行被删除时,下一行将具有与删除行相同的i值,并被Next i跳过。

 Dim LastRow As Long 'Finds last row With ActiveSheet LastRow = .Cells(.Rows.count, "P").End(xlUp).Row End With 'Iterates through rows in column B, and deletes the row if string contains "H" For i = 4 To LastRow If InStr(1, Range("P" & i), "H") <> 0 Then Rows(i).EntireRow.Delete Next i 'Message Box when tasks are completed MsgBox "Complete" 

有没有办法让For循环重复相同的i值,如果一行被删除,以获得所有的行?

执行此操作的标准方法是以相反的顺序进行迭代。

 Dim LastRow As Long 'Finds last row With ActiveSheet LastRow = .Cells(.Rows.count, "P").End(xlUp).Row End With 'Iterates in reverse through rows in column B, and deletes the row if string contains "H" For i = LastRow To 4 Step -1 If InStr(1, Range("P" & i), "H") <> 0 Then Rows(i).EntireRow.Delete Next i 'Message Box when tasks are completed MsgBox "Complete" 

尝试筛选通配符*H*并删除可见的行。

 Option Explicit Sub qweqrwtqrweq() if autofiltermode then .autofiltermode = false With ActiveSheet '<~~much better to use thge ACTUAL WORKSHEET NAME!! eg with worksheets("sheet1") With .Range(.Cells(4, "P"), .Cells(.Rows, Count, "P").End(xlUp)) .AutoFilter fiedl:=1, Criteria1:="*h*" If CBool(Application.subtotla(103, .Cells)) Then .Cells.etirerow.Delete End If End With End With if autofiltermode then .autofiltermode = false MsgBox "Complete" End Sub 

批量操作几乎总是比逐行检查更高效。