简体   繁体   English

VBA Excel-当列中的单元格值等于零时删除行

[英]VBA Excel - Deleting rows when cell value in column equals zero

I have some code in my VBA script that is supposed to delete entire rows when the value of the respective B column of the row equals zero. 我的VBA脚本中有一些代码,当该行的各个B列的值等于零时,该代码应删除整个行。 Unfortunately, the lines of code I have been using are not doing exactly what I want as it deletes the entire row if ANY of the cells in the respective row equals zero. 不幸的是,如果相应行中的任何单元格等于零,那么它将删除整行,因此我一直在使用的代码行并没有完全满足我的要求。 Here is the code so far: 这是到目前为止的代码:

With Worksheets("Sheet2")
For myloop = .Range("B10000").End(xlUp).Row To 1 Step -1
    If .Cells(myloop, 4).Value = 0 Then .Rows(myloop).EntireRow.Delete
Next myloop
End With

For instance I had a row in which the cell in column D was equal to zero and this code deleted the entire row even though the value of the cell in column B was not zero. 例如,我有一行,其中D列中的单元格等于零,即使B列中单元格的值不为零,此代码也删除了整行。 How can I change the code so it actually only scans for the entries in column B? 如何更改代码,使其实际上仅扫描B列中的条目?

Any help is appreciated and thanks in advance. 任何帮助表示赞赏,并在此先感谢。

The user gizlmo provided the answer: 用户gizlmo提供了答案:

Change .Cells(myloop, 4).Value to .Cells(myloop, 2).Value .Cells(myloop, 4).Value更改为.Cells(myloop, 2).Value

an AutoFilter() approach is the following: AutoFilter()方法如下:

With Worksheets("Sheet2") '<--| reference your shet
    With .Range("B1", .Cells(Rows.Count, "B").End(xlUp)) '<--| reference its column B range from row 1 (header) down to last not empty row
        If WorksheetFunction.CountBlank(.Cells) + WorksheetFunction.CountIf(.Cells, 0) = 0 Then Exit Sub '<--| exit of no empty or "zero" cells
        .AutoFilter Field:=1, Criteria1:=0, Operator:=xlOr, Criteria2:=""  '<--| filter column B cells with "0" content
         .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete '<--| if any filtered cell other than headers then delete their entire rows
    End With
    .AutoFilterMode = False
End With

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

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