2016-02-19 84 views
0

我在尋找幫助使代碼片段運行得更快。我已經嘗試了一些技巧,比如保存數組中的值,然後評估它們並關閉屏幕更新&代碼運行時的計算,但仍需要非常多的時間。在Excel中緩慢運行vba腳本時遇到困難

我認識到有一噸的記錄可以貫穿,但我希望有更多的資深程序員能夠給我提供一些明智的建議。

Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 

Dim w As Long 
Dim x As Long 
Dim y As Long 
Dim z As Long 
Dim srch() As Variant 
Dim ent() As Variant 
Dim rng1 As Range 
Dim rng As Range 
Set rng = ActiveSheet.Range("C2:C134743") 
ReDim srch(1 To 134742) 
Set rng1 = Sheets("ExampleSheet").Range("F2:F63078") 
ReDim ent(1 To 63077) 

For x = 1 To 134742 
    srch(x) = rng.Cells(x, 1).Value 
Next x 

For w = 1 To 63077 
    ent(w) = rng1.Cells(w, 1).Value 
Next w 

For z = 1 To 134742 

    For y = 1 To 63077 

     If CStr(srch(z)) = ent(y) Then 
      ActiveSheet.Range("AA2:AA134743").Cells(z, 1) = "Example_True" 
      GoTo jmp 
     Else 
      ActiveSheet.Range("AA2:AA134743").Cells(z, 1) = "Example_False" 
     End If 

    Next y 

jmp: 

Next z 

Application.Calculation = xlCalculationAutomatic 
Application.ScreenUpdating = True 

在此先感謝

+0

使用查找命令來查找細胞符合所需的數據。 –

+0

@ Grade'Eh'Bacon是正確的。如果您仍然需要使用陣列,則可以直接從範圍加載它們。 'ent = rng1'(注意那是n,1個數組)。 –

+0

這應該被移植到[代碼評論](http://codereview.stackexchange.com/) - 我已經標記它,所以希望它會被移動。 –

回答

0

應該會更快:

Sub TT() 

    Dim z As Long, y As Long 
    Dim srch As Variant, ent As Variant, v 
    Dim rng1 As Range, rng As Range, c As Range 

    Application.ScreenUpdating = False 
    Application.Calculation = xlCalculationManual 

    Set rng = ActiveSheet.Range("C2:C134743") 
    srch = rng.Value 

    Set rng1 = Sheets("ExampleSheet").Range("F2:F63078") 
    ent = rng1.Value 

    For z = 1 To UBound(srch, 1) 
     Set c = rng.Cells(z).EntireRow.Cells(1, "AA") 
     v = CStr(srch(z, 1)) 
     For y = 1 To UBound(ent, 1) 
      If v = ent(y, 1) Then 
       c.Value = "Example_True" 
       GoTo jmp 
      End If 
     Next y 
     c.Value = "Example_False" 'only do this once! 
jmp: 

    Next z 

    Application.Calculation = xlCalculationAutomatic 
    Application.ScreenUpdating = True 

End Sub 
0

嘗試關閉自動計算

你也不需要activesheet這麼多。搭配:

Set rng = ActiveSheet.Range("C2:C134743") 

你可以只告訴它這是什麼片即sheetx.range等

而且你似乎通過一組變量周圍不必要。它看起來很像你可以重新設計這個以更簡單的方式做到這一點。你只是使用index/match來過濾true/false?