我试图删除所有包含" H"的字符串的行。在P
列中。然而,宏工作,它每次只删除一半必要的行。这是因为代码中的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
值?
答案 0 :(得分:2)
执行此操作的标准方法是以相反的顺序迭代。
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"
答案 1 :(得分:0)
尝试过滤通配符*H*
并删除可见行。
Option Explicit
Sub qweqrwtqrweq()
if autofiltermode then .autofiltermode = false
With ActiveSheet '<~~much better to use thge ACTUAL WORKSHEET NAME!! e.g. 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
批量操作几乎始终比逐行检查更有效。