Excel vba Deleting a row if a cell contains a text [duplicate]

回眸只為那壹抹淺笑 提交于 2021-01-29 04:04:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!