2013-05-01 187 views
1

嗨夥伴們,VBA宏崩潰Excel

我正在運行一個宏來刪除包含特定值的整個行。該代碼在小數據集上工作正常,但在當前版本(約22,000條記錄)上,它一直崩潰Excel(2010)。代碼如下。在將數據拆分成更小的塊並一次又一次地運行宏之後,我不知道該怎麼做。

讚賞任何幫助和下面的代碼:

Sub CleanOcc() 

'Row counting 
Dim Firstrow As Long 
Dim Lastrow As Long 
Dim Lrow As Long 
Dim Lrow2 As Long 

With Sheets("Occ_Prep") 

    'Cleans the occ_prep sheet ready for upload (Column and value can be changed) 
    Sheets("Occ_Prep").Activate 

    'Set the first and last row to loop through 
    Firstrow = .UsedRange.Cells(1).Row 
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row 

    'We loop from Lastrow to Firstrow (bottom to top) 
    For Lrow2 = Lastrow To Firstrow Step -1 

     'We check the values in the A column in this example 
     With .Cells(Lrow2, "K") 


      If Not IsError(.Value) Then 

       If .Value = "0" Then .EntireRow.Delete 
       'This will delete each row with the Value "ron" 
       'in Column A, case sensitive. 

      End If 

     End With 

    Next Lrow2 

End With 



End Sub 
+0

Excel和真正大量的數據不會混合,它不是真的意味着數據庫:\ – 2013-05-01 21:21:12

+1

這是找到最後一個單元格的一種非常錯誤的方法。請參見[THIS](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba)另請參閱[THIS](http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/da7d1600-43bc-4e04-b2cc-8c4871349964)這裏我使用'delrange'對象來刪除相關的行。只需修改它以適應您的需求。 – 2013-05-01 21:41:00

+0

另一種方式。使用自動過濾器在'0'上過濾Col K,然後刪除相關的行。參見[THIS](http://stackoverflow.com/questions/11631363/how-to-copy-a-line-in-excel-using-a-specific-word-and-pasting-to-another-excel-s )這顯示瞭如何使用過濾的範圍。只需修改它即可刪除您的範圍 – 2013-05-01 21:43:41

回答

1

同意亞洲時報Siddharth評論自動篩選的路要走。這應該快很多。

Option Explicit 
Sub delrows() 
    Dim ws As Worksheet 
    Dim LR As Long 
    Dim rng As Range, frng As Range 

    Application.ScreenUpdating = False 

    Set ws = Sheets("dataset") '<-- Change this to name of your worksheet 
    With ws 
     LR = .Range("A" & Rows.Count).End(xlUp).Row 
     .AutoFilterMode = False 
     Set rng = .Range("A1:C" & LR) '<-- Assuming K is the last column 
     rng.AutoFilter 3, "0" '<-- 11 referes to Column K 
     Set frng = rng.Offset(1, 0).SpecialCells(xlCellTypeVisible) '<-- Don't delete the header 
     frng.EntireRow.Delete 
     .AutoFilterMode = False 
    End With 

    Application.ScreenUpdating = True 
End Sub 

編輯:我剛在〜5秒鐘內清理了20000行(3列)的數據。顯然這取決於有多少比賽。