我有一个表,我想在其中删除任何没有数据的行。
该代码是一个更大的子代码的一部分。
我明白了
错误 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
.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