在条件将VBA与For和IF应用时删除所有行
Excel VBA
我想删除基于cond的所有行查看if语句,但代码不会删除所有具有ws.Cells(i, 6).Value = 0
Sub Clean() For Each ws In Worksheets ' find Last Row LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row ' loop over all rows For i = 2 To LastRow ' start of the for loop If ws.Cells(i, 6).Value = 0 Then Rows(i).Delete End If Next i Next ws End Sub
更换
For i = 2 To LastRow
同
For i = LastRow to 2 step -1
应该工作得更好。
我发现你在代码中丢失了一些重要的东西。 当你删除一行时,你的i
variables会自动跳过1行,行删除后的当前行不被validation。
Sub Clean() For Each ws In Worksheets ' find Last Row LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row ' loop over all rows For i = 2 To LastRow ' start of the for loop If ws.Cells(i, 6).Value = 0 Then Rows(i).Delete i = i - 1 ' force your code to review the same line again End If Next i Next ws End Sub
希望能帮助到你。