我看到几篇关于删除范围内空白行的帖子以及其他关于删除基于单个空白列的表行的帖子,但没有关于删除完整空白表行的内容。
最快的方法是什么?
我在下面发布了我的解决方案以帮助其他人,但我有兴趣看看是否有人有更快的方法。
答案 0 :(得分:3)
这是我用来删除空白表行的过程。我有时使用大型(Excel)数据集,这种方法更快。它将表行加载到数组中,检查数组是否有空行,并在最后执行一次range.delete
操作。
您可以使用以下程序:
Sub Test()
DeleteBlankTableRows ActiveSheet.ListObjects(1)
End Sub
ActiveSheet.ListObjects(1)(通常)是活动工作表上的第一个表格表。
这是实际程序:
Sub DeleteBlankTableRows(ByVal tbl As ListObject)
Dim rng As Range
Set rng = tbl.DataBodyRange ' Get table data rows range.
Dim DirArray As Variant
DirArray = rng.Value2 ' Save table values to array.
' LOOP THROUGH ARRAY OF TABLE VALUES
Dim rowTMP As Long
Dim colTMP As Long
Dim combinedTMP As String
Dim rangeToDelete As Range
' Loop through rows.
For rowTMP = LBound(DirArray) To UBound(DirArray)
combinedTMP = vbNullString ' Clear temp variable.
' Loop through each cell in the row and get all values combined.
For colTMP = 1 To tbl.DataBodyRange.Columns.Count
combinedTMP = combinedTMP & DirArray(rowTMP, colTMP)
Next colTMP
' Check if row is blank.
If combinedTMP = vbNullString Then
' Row is blank. Add this blank row to the range-to-delete.
If rangeToDelete Is Nothing Then
Set rangeToDelete = tbl.ListRows(rowTMP).Range
Else
Set rangeToDelete = Union(rangeToDelete, tbl.ListRows(rowTMP).Range)
End If
End If
Next rowTMP
' DELETE BLANK TABLE ROWS (if any)
If Not rangeToDelete Is Nothing Then rangeToDelete.Delete
End Sub
这比其他方法有一些优势:
SpecialCells(xlCellTypeBlanks)
方法的34秒的一半。答案 1 :(得分:1)
这应该有效。不确定它是否更快,但它是另一种方法:
Sub delete_blank_table_rows()
Dim Rng As Range, tempRng As Range
Set Rng = Range("Table1") ' Change as necessary
Set Rng = Range(Cells(Rng.Rows(1).Row, Rng.Columns(1).Column), Cells(Rng.Rows(Rng.Rows.Count).Row, Rng.Columns(Rng.Columns.Count).Column))
Dim i As Long
For i = Rng.Rows.Count To 1 Step -1
Cells(Rng.Rows(i).Row, Rng.Columns(1).Column).Select
Set tempRng = Range(Cells(Rng.Rows(i).Row, Rng.Columns(1).Column), Cells(Rng.Rows(i).Row, Rng.Columns(Rng.Columns.Count).Column))
If WorksheetFunction.CountA(tempRng) = 0 Then
tempRng.Delete shift:=xlUp
End If
Next i
End Sub
编辑:当然要加快速度,你应该在运行时关闭屏幕更新,计算。
答案 2 :(得分:0)
我认为这可能会更快(您可以修改lastrow和lastcol以满足您的表格尺寸):
Sub delete_rows_blank2()
t = 1
lastrow = ActiveSheet.UsedRange.Rows.Count
lastcol = ActiveSheet.UsedRange.Columns.Count
Do Until t = lastrow
For j = 1 To lastcol
If Cells(t, j) = "" Then
j = j + 1
If j = lastcol Then
Rows(t).Delete
t = t + 1
End If
Else
t = t + 1
End If
Next
Loop
End Sub