删除表格中的空白行

问题描述 投票:0回答:1

我有一个表,我想在其中删除任何没有数据的行。

该代码是一个更大的子代码的一部分。

我明白了

错误 1004 对象“范围”的“删除”方法失败。

Dim row As Range
With ws_IAD
    lastrow = tbl_IAD.Range.Rows(tbl_IAD.Range.Rows.count).row
    With tbl_IAD.DataBodyRange
        .SpecialCells(xlCellTypeBlanks).Rows.Delete
    End With
End With
excel vba
1个回答
0
投票

.SpecialCells(xlCellTypeBlanks)
不会返回连续范围 - 因此您无法通过这种方式删除它们。

有两种选择。

  • 第一个:如果列表对象/表格的左侧或右侧没有数据,则可以删除整个工作表行
  • 第二个:逐行检查表是否为空 - 然后删除表的行(如果表很大,这会降低性能)。

您可以像这样调用其中一个或这些潜艇:

deleteEmptyRowsOfListobject tbl_IAD

选项 1 过滤所有空行,然后删除可见行。

Public Sub deleteEmptyRows(lo As ListObject)

Dim i As Long
For i = 1 To lo.ListColumns.Count
    lo.Range.AutoFilter i, "="
Next

Application.DisplayAlerts = False
With lo.DataBodyRange
    On Error Resume Next 'in case there are no empty rows
        'this will delete the whole sheet row!!! -->
        'if there is content to the left or to the right of the listobject it will get deleted too!
        .SpecialCells(xlCellTypeVisible).Delete
    On Error GoTo 0
End With
Application.DisplayAlerts = True

lo.AutoFilter.ShowAllData

End Sub

选项 2 使用工作表函数 CountA 返回范围内非空单元格的数量。

Public Sub deleteEmptyRowsOfListobject(lo As ListObject)

Dim i As Long, lr As ListRow

Application.DisplayAlerts = False

With lo.ListRows
    For i = .Count To 1 Step -1
        Set lr = .Item(i)
        If WorksheetFunction.CountA(lr.Range) = 0 Then
            lr.Delete
        End If
    Next
End With

Application.DisplayAlerts = True

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.