2017-05-19 25 views
1

我試圖刪除P列中包含「H」字符串的所有行。但是,宏只能刪除每次需要的行的一半。這是因爲代碼中的For循環 - 當一行被刪除時,下一行將具有與刪除行相同的i值,並被Next i跳過。VBA:搜索子字符串和刪除整行

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值,如果行,以獲得所有的行刪除?

回答

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" 
+0

謝謝!這讓它工作。 – MTJ

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 

批量操作幾乎總是一行一行地考試更有效。