2012-03-13 73 views
1

上柱A的空行我有下面的代碼段,在空行需要從列A,然後刪除該整行。我無法使用2010年的Special - > Blanks - > Delete Sheet Rows功能,因爲2007的上界約有80​​00個非連續行。這些代碼在一些較舊的機器上速度非常慢,大約需要40分鐘才能完成(但完成這項工作)。有沒有更快的選擇呢?刪除在Excel 2007

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 

回答

1

此代碼需要在第二個10萬行(如果需要記錄更爲全面的代碼的動作):

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 
+0

這將在Excel 2007上工作嗎?我問,因爲2007年有約8000非連續行的限制。 – rvphx 2012-03-14 14:16:34

+0

是的,這個代碼應該適用於所有版本。它只是對錶單進行排序,以便可以在一個塊中刪除所有行。 – 2012-03-14 14:29:02

+0

哇。這就像一個魅力!我將在電子表格中調整此代碼,因爲在此處存在一些自定義標記(不需要的文本),在我放入此代碼之前需要刪除這些標記。 – rvphx 2012-03-14 14:48:01

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

希德

+0

我沒有得到一個機會以完全測試,但從運行時間來看,它看起來像第一塊大致相同。我一定會盡快嘗試,並報告我發現的內容。雖然謝謝! – rvphx 2012-03-13 22:21:17

+0

實際上,在大量的行中,我發現代碼在問題中發佈的速度明顯快於第一個建議。我認爲AutoFilter方法可以更好地擴展,但Excel 2007及更早版本的這個範圍也會受到〜8000區域限制。 – 2012-03-14 11:14:49