简体   繁体   English

使用VBA删除“ B”列为空的所有行

[英]Deleting All Rows That Have an Empty “B” Column Using VBA

I'm looking to create a macro that deletes all rows that don't contain any data in Column B. Any help would be appreciated. 我正在寻找创建一个宏,该宏将删除B列中不包含任何数据的所有行。任何帮助将不胜感激。 This is all I got for now. 这就是我现在所拥有的。

Sub DeleteAllEmptyBRows()
Dim lr As Long
lr = Cells(Rows.Count, "B").End(xlUp).Row
    For Each cell In Range("B1:B" & lr)
        If cell.Value = "" Then
            cell.Row.Delete
            Exit Sub
        End If
   Next cell
End Sub

You can use SpecialCells to do this in one quick line: 您可以使用SpecialCells快速完成此操作:

Range("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

I'd use the above, but also for your own knowledge, here's how you could do it following your code: 我将使用以上内容,但也请您自行了解,以下是按照代码执行的方法:

Sub DeleteAllEmptyBRows()
Dim lr As Long, i&

lr = Cells(Rows.Count, "B").End(xlUp).Row

For i = lr To 1 Step -1 'Since you're deleting rows, start at the end, and work upwards
    If Cells(i, 2).Value = "" Then
        Cells(i, 2).EntireRow.Delete
    End If
Next i

End Sub

Note that you have an Exit Sub in yours, after the first time a row is deleted. 请注意,第一次删除行后,您就有一个Exit Sub I removed that, since you want to loop through all cells in the range. 我删除了它,因为您想遍历范围内的所有单元格。 Again, this is a loop so will take longer, and has more room for errors, than the simple one liner above. 同样,这是一个循环,因此比上面的简单衬纸需要更长的时间,并且有更多的出错空间。

You are missing some parameters: 您缺少一些参数:

Cells(cell.Row, 2).Delete Shift:=xlUp

If you need the entire row, just change to: 如果需要整行,只需更改为:

cell.Row.EntireRow.Delete

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

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