简体   繁体   English

Excel 宏/VBA - 如果一列中的单元格为空,如何删除整行?

[英]Excel Macro / VBA - How do I delete an entire row if a cell in one column is blank?

I want a macro code that (1) starts at Row 3, (2) and deletes any row where its cell in Column B is blank.我想要一个宏代码,它 (1) 从第 3 行开始,(2) 并删除其在 B 列中的单元格为空白的任何行。 I've tried...我试过了...

Sub DelBlankRows()  
    Columns("B:B").Select  
    Selection.SpecialCells(xlCellTypeBlanks).Select  
    Selection.EntireRow.Delete  
End Sub

And

Sub delrows()  
     Range("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete  
End Sub

Better would be to define the worksheet as well:更好的是定义工作表:

Sub test()
    Worksheets("sheet1").Range("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete shift:=xlUp
End Sub

Will delete every row where column B is empty.将删除 B 列为空的每一行。

If you need to start at row 3 until the last row:如果您需要从第 3 行开始直到最后一行:

Sub test()
    Dim lr As Double
    lr = Worksheets("Sheet1").Range("B65536").End(xlUp).Row
    Worksheets("Sheet1").Range("B3:B" & lr).SpecialCells(xlCellTypeBlanks).EntireRow.Delete shift:=xlUp
End Sub

Chances are, you are going to be looping this in something... The concise answers given to you will not "update" the row index of your loop.有可能,您将在某些东西中循环这个......给您的简洁答案不会“更新”您的循环的行索引。 I present a cleaner looking option that will likely fit into whatever you are doing:我提供了一个看起来更干净的选项,它可能适合你正在做的任何事情:

pseudo CODE伪代码

For row = start To rowcount
    If cells(row,column).Value = "" Then
        Cells(row,column).EntireRow.Delete shift:=xlUp
        row = row-1  'this is because the xlUp shift changes index for all rows BELOW your loop
    End If
Next row

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

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