2017-04-12 32 views
0

我有一個Excel工作簿2片(產品列表和CurrentProducts)搜索和刪除VBA代碼需要優化

我有以下代碼:

Sub Macro1() 

Dim Lastrow As Integer 
Dim x As Integer 
Dim BinNo As String 
Dim MyCell As Range 

Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 
Application.EnableEvents = False 

Lastrow = Sheets("ProductsList").Range("A65536").End(xlUp).Row 

For x = Lastrow To 2 Step -1 

BinNo = Sheets("ProductsList").Range("A" & x).Value 

With Sheets("CurrentProducts").Range("A:A") 
    Set MyCell = .Find(What:=BinNo, _ 
        After:=.Cells(.Cells.Count), _ 
        LookIn:=xlValues, _ 
        LookAt:=xlWhole, _ 
        SearchOrder:=xlByRows, _ 
        SearchDirection:=xlNext, _ 
        MatchCase:=False) 

    If Not MyCell Is Nothing Then 
     Sheets("CurrentProducts").Range(MyCell.Address).EntireRow.Delete 
    End If 
End With 

Next 

Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 
Application.EnableEvents = True 

End Sub 

這樣做什麼是採取從柱A中的每個值在ProductList中,在CurrentProducts中搜索它,如果它找到該值,則從CurrentProducts中刪除整行,這樣我就會在CurrentProducts表中留下任何新產品。

此代碼有效,但速度非常慢,需要大約5分鐘才能運行。

每頁有大約30,000行。

有沒有辦法加快速度,還是僅僅因爲有這麼多行?

+2

如果代碼工作,你需要優化/審查,那麼你應該將它張貼在**代碼審查**部分,點擊:http:/ /codereview.stackexchange.com/ –

+3

我將此問題標記爲偏離主題,因爲它應該按照此處的規定遷移到CodeReview:http://meta.stackoverflow.com/questions/266749/migration-of-code-questions從堆棧溢出到代碼複審原因:代碼正在工作,並且OP本身要求改進工作代碼的性能。沒有錯誤或錯誤需要克服。 – Ralph

回答

1

我建議這可以通過使用公式更快地完成。例如,你可以做一個vlookup。然後,您可以對工作表進行排序並刪除任何返回值的行。

這是一種可能的解決方案。

我可以想到很多類似的東西。但使用公式將是最簡單的。

0

你可以試試這樣的事情...

Sub DeleteRows() 
Dim ws1 As Worksheet, ws2 As Worksheet 
Dim lr As Long 
Application.ScreenUpdating = False 
Set ws1 = Sheets("ProductsList") 
Set ws2 = Sheets("CurrentProducts") 

With ws2 
    lr = .Cells(Rows.Count, 1).End(xlUp).Row 
    .Columns(1).Insert 
    .Range("A2:A" & lr).Formula = "=IF(COUNTIF(" & ws1.Name & "!A:A,B2),NA(),"""")" 
    On Error Resume Next 
    .Range("A2:A" & lr).SpecialCells(xlCellTypeFormulas, 16).EntireRow.Delete 
    .Columns(1).Delete 
End With 
Application.ScreenUpdating = True 
End Sub