使用VBA删除Excel中的空行

我想通过使用下面的代码删除空行:

worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete 

上面的代码工作正常,但run time error '1004': No Cells were found.

 On Error Resume Next worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete On Error GoTo 0 

error handling有助于在没有空白单元格的情况下。 如果没有像这样的单元格, SpecialCells(xlCellTypeBlanks)将总是返回一个错误,所以如果你想使用SpecialCells(xlCellTypeBlanks) ,error handling是唯一的方法(我知道)来处理它。

你需要testing有没有空白。

 If WorksheetFunction.CountBlank(Worksheet.Columns("A:A")) > 0 Then Worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete End If 

如果没有空格,您可以使用On Error Resume Next跳过该行,但通常最好testing一个特定的条件,而不是假设您知道错误是什么。

就我所见,如果列A中的每个单元格都有一个值,则只会显示“找不到单元格”消息。

编辑:基于@ brettdj的评论,这是一个替代仍然使用CountBlank:

 If WorksheetFunction.CountBlank(Intersect(worksheet.UsedRange, ws.Columns("A:A"))) > 0 Then worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete End If 

当然UsedRange是臭名昭着的,可能会比看起来更大。 我认为最好先确定要删除的行的实际范围,然后检查该范围内的SpecialCells,例如:

 Sub DeleteRows() Dim ws As Excel.Worksheet Dim LastRow As Long Set ws = ActiveSheet LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row With ws.Range("A2:A" & LastRow) If WorksheetFunction.CountBlank(.Cells) > 0 Then .SpecialCells(xlCellTypeBlanks).EntireRow.Delete End If End With End Sub 

最后一个注意事项 – 我把variables从“worksheet”改为“ws”,因为“worksheet”是一个Excel保留字。

和我一起工作很好。 这些声明不会给我带来任何的错误

  Sheet1.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete 'perfect 

我发现你的问题的这种types的解决scheme

  On Error Resume Next Sheet1.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete On Error GoTo 0 

看看这些链接

http://www.excelforum.com/excel-programming/390329-microsoft-visual-basic-run-time-error-1004-no-cells-were-found.html

http://www.mrexcel.com/forum/showthread.php?t=343744

是的,你是否设置了你的对象? 工作表在这里没有任何意义

 dim wsheet as worksheets set wsheet = worksheets("worksheetname") or worksheets("sheet1") wsheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete 

其他方式:

 If Range("Table2").Rows.Count > 1 Then Range("Table2").EntireRow.Delete End If