VBA - 删除 - ActiveSheet.UsedRange.Rows.Count

时间:2015-07-24 09:10:34

标签: excel vba excel-vba

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

NewLastRow = ActiveSheet.UsedRange.Rows.Count

NewLastRow提出了第65行,尽管行中没有任何内容 所以我合并了一段代码来选择活动范围,并删除没有内容的行。

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

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

2 个答案:

答案 0 :(得分:4)

您可以在代码中改进两件事:

1)您正在遍历所有行。它在Excel 2007+中超过100万次迭代。通常只有几千个非空行。因此,如果您首先找到最后一个非空行的索引,然后将此索引用作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

注意即可。为了使此代码正常运行,您需要在代码中加入function to find the last non-empty row in Excel worksheet

答案 1 :(得分:0)

You can remove it by following code :

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