问题
I'm using this code:
Dim r As Integer
For r = 1 To Sheet1.UsedRange.Rows.Count
If Cells(r, "Q") = "0" Then
Sheet1.Rows(r).EntireRow.Delete
End If
Next
The problem is it doesn't delete everything, it just deletes some of the rows and i have to press the button that uses this code multiple times to delete all instances of "0" in "Q"
Answers from similar questions
How to reverse a For loop
Delete Row based on Search Key VBA
回答1:
I appreciate this has been addressed in the comments, but for completeness, you need to reverse the order of the for/next loop as shown below:
Dim r As Integer
For r = Sheet1.UsedRange.Rows.Count to 1 step -1
If Cells(r, "Q") = "0" Then
Sheet1.Rows(r).EntireRow.Delete
End If
Next
The way you had it previously, by deleting an entire row at the start of the list, you were moving all the content up one row. By starting form the bottom up, deleting an entire row doesn't impact the rows numbers for the items you haven't processed yet.
Glad you got it sorted.
来源:https://stackoverflow.com/questions/21515073/excel-vba-deleting-a-row-if-a-cell-contains-a-text