VBA – 删除ActiveSheet.UsedRange.Rows.Count中的空行

我的工作表上有大约50行,我正在使用VBAmacros编辑它们。
当我用以下格式存储最后使用的行时

NewLastRow = ActiveSheet.UsedRange.Rows.Count 

尽pipe行中没有任何东西,NewLastRow出现在第65行。
所以我join了一段代码来select活动范围,并删除没有内容的行。

 ActiveSheet.UsedRange.Select 'Deletes the row within the selection if the row has no data. Dim i As Long 'Turn off aspects which could slow down process. With Application .Calculation = xlCalculationManual .ScreenUpdating = False 'Delete backwards. For i = Selection.Rows.Count To 1 Step -1 If WorksheetFunction.CountA(Selection.Rows(i)) = 0 Then Selection.Rows(i).EntireRow.Delete End If Next i .Calculation = xlCalculationAutomatic .ScreenUpdating = True End With 

这工作,但需要很长的时间。 我怎样才能加快速度?

你可以在你的代码中改进两件事情:

1)你遍历所有的行。 Excel 2007+中的迭代次数超过100万次。 通常不会有数以千计的非空行。 因此,如果您首先find最后一个非空行的索引,然后在For ... Next循环中将此索引用作限制,则代码将工作得更快。

2)删除行是非常耗时的操作,所以如果可能的话应该合并成一个单独的操作。 您可以使用Union函数将要删除的所有行集中到一个范围内,然后使用单个命令将其全部删除。

以下是完成您的任务的完整代码:

 Public Sub deleteRows() Dim wks As Excel.Worksheet Dim rng As Excel.Range Dim row As Long Dim lastRow As Long '------------------------------------------------------------------------- Set wks = Excel.ActiveSheet lastRow = lastNonEmptyRow(wks) With wks For row = 1 To lastRow If Application.WorksheetFunction.CountA(.Rows(row)) = 0 Then If rng Is Nothing Then Set rng = .Rows(row) Else Set rng = Excel.Union(rng, .Rows(row)) End If End If Next row End With 'In order to avoid Run-time error check if [rng] range is not empty, before removing it. If Not rng Is Nothing Then Call rng.EntireRow.Delete End If End Sub 

注意 。 为了使此代码正常工作,您需要包含函数来查找Excel工作表中的最后一个非空行到代码中。

您可以通过以下代码将其删除:

在错误恢复下一步
 worksheet.Columns( “A:A”)。SpecialCells(xlCellTypeBlanks).EntireRow.Delete
在错误转到0