2017-05-19 19 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 

一括操作が行単位検査のほぼ常により効率的です。

関連する問題