Excel vba 如果单元格包含文本,则删除一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21515073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:41:10  来源:igfitidea点击:

Excel vba Deleting a row if a cell contains a text

excelvbaexcel-vba

提问by user3249749

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"

问题是它不会删除所有内容,它只会删除一些行,我必须多次按下使用此代码的按钮才能删除“Q”中所有“0”的实例

Answers from similar questions

类似问题的答案

How to reverse a For loop
Delete Row based on Search Key VBA

如何根据搜索键 VBA反转 For 循环
删除行

回答by Andrew - Eversight Ltd

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:

我很感激评论中已经解决了这个问题,但为了完整起见,您需要颠倒 for/next 循环的顺序,如下所示:

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.

很高兴你把事情解决了。