删除excel 2007中A列上的空行

时间:2012-03-13 21:01:19

标签: excel-vba excel-2007 vba excel

我有以下代码片段从列A中获取空行,然后删除整行。我无法使用Special - >空白 - > 2010年删除工作表行功能,因为2007年的上限约为8000个非连续行。这些代码在某些旧机器上速度非常慢,大约需要40分钟才能完成(但是可以完成工作)。有更快的替代方案吗?

 Private Sub Del_rows()
    Dim r1 As Range, xlCalc As Long
    Dim i As Long, j As Long, arrShts As Variant
    With Application
        xlCalc = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
    End With
    arrShts = VBA.Array("Sheet1")  'add additional sheets as required
    For i = 0 To UBound(arrShts)
        With Sheets(arrShts(i))
            For j = .UsedRange.Rows.Count To 2 Step -8000
                If j - 7999 < 2 Then
                    .Range("A2:A" & j).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
                Else
                    .Range("A" & j, "A" & j - 7999).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
                End If
            Next j
        End With
    Next i
    Application.Calculation = xlCalc

2 个答案:

答案 0 :(得分:4)

拉吉夫,试试吧。这应该很快。

Option Explicit

Sub Sample()
    Dim delrange As Range
    Dim LastRow As Long, i As Long

    With Sheets("Sheet1") '<~~ Change this to the relevant sheetname
        '~~> Get the last Row in Col A
        LastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To LastRow
            If Len(Trim(.Range("A" & i).Value)) = 0 Then
                If delrange Is Nothing Then
                    Set delrange = .Rows(i)
                Else
                    Set delrange = Union(delrange, .Rows(i))
                End If
            End If
        Next i

        If Not delrange Is Nothing Then delrange.Delete
    End With
End Sub

修改

您还可以使用自动过滤删除行。这很快。我没有测试这些巨大行的示例:)如果您有任何错误,请告诉我。

Option Explicit

Sub Sample()
    Dim lastrow As Long
    Dim Rng As Range

    With Sheets("Sheet1")
        lastrow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Remove any filters
        .AutoFilterMode = False

        With .Range("A1:A" & lastrow)
          .AutoFilter Field:=1, Criteria1:=""
          .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With

        '~~> Remove any filters
        ActiveSheet.AutoFilterMode = False
    End With
End Sub

HTH

西特

答案 1 :(得分:1)

此代码在100,000行内不到一秒(如果需要,记录更全面代码的操作):

Sub DeleteRows()

Application.ScreenUpdating = False
Columns(1).Insert xlToRight
Columns(1).FillLeft
Columns(1).Replace "*", 1
Cells.Sort Cells(1, 1)
Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Columns(1).Delete

End Sub