简体   繁体   English

如何根据条件删除表格的行Excel vba

[英]how to delete rows of a table depending on condition Excel vba

The problem is really simple but I could not find any efficient solution. 这个问题确实很简单,但是我找不到任何有效的解决方案。 I have a table. 我有桌子 I want to loop through and delete the entire row when some condition are met. 我想遍历并在满足某些条件时删除整行。 The code I use is the following: 我使用的代码如下:

Range("H3").Select
Range(Selection, Selection.End(xlDown)).Select
Dim cellule As Range
For Each cellule In Selection.Cells    
If cellule.Value = "--" And ...(More condition) Then
        cellule.EntireRow.Delete
    End If
Next cellule

It actually works but when two consecutive rows met those condition then the 2nd one is not deleted because it has gone up when the 1st had been deleted. 它实际上可以工作,但是当连续两行满足这些条件时,则不会删除第二行,因为第二行在删除第一行时就上升了。 Basically the 2nd has been skipped. 基本上第二个已被跳过。

you can do this without a loop if you want: 您可以根据需要执行以下操作:

first, add a formula in an empty column that will show the #NA error if your condition is true: 首先,在空列中添加一个公式,如果您的条件为true,则会显示#NA错误:

sFormula = "=IF(H:H=""- -"",NA(),"""")" ' could combine conditions using AND Excel worksheet functionn

' put the formula in column K for all rows, if the condition in col H is met, 
' this row will show an #NA error in column K   
Range("K2:K" & Range("H" & rows.count).End(xlUp).Row).Formula = sFormula

' now match all the rows using SpecialCells in one step, and delete!
Range("K5:H" & Range("H" & rows.count).End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).entirerow.delete shift:=xlup

this is similar to striking the F5 key in Excel and clicking 'SpecialCells', then choosing 'Errors' 这类似于在Excel中敲击F5键并单击“ SpecialCells”,然后选择“ Errors”

let us know how you get on 让我们知道您的身体情况如何

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM