2013-03-22 82 views
-2

我想提高後續VBA代碼的效率。我能想到的是在代碼中使用「With」和「End With」。還有什麼我可以做的優化代碼?如何優化後續VBA代碼的運行速度?

謝謝!

Sub ONLY_CORP_Lives_Premiums() 
Dim row_phil, row_phl, row_eveeb, row_evenb As Integer 
Dim row_indiv, row_sme, row_corp As Integer 
Dim row As Variant 
Dim row_start, row_end As Integer 
Dim i, k As Integer 
Dim start_time, end_time 

start_time = Now() 
Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 
Sheets("SETUP").Range("J32") = Sheets("SETUP").Range("J28") 

Sheets("LIVES PROJECTION").Activate 
row_phil = Application.CountIf(Range("B1237:B1048576"), "PHIL" & "*") 
row_phl = Application.CountIf(Range("B1237:B1048576"), "PHL" & "*") + row_phil 
row_eveeb = Application.CountIf(Range("B1237:B1048576"), "EVEEB" & "*") + row_phl 
row_evenb = Application.CountIf(Range("B1237:B1048576"), "EVENB" & "*") + row_eveeb 
row = Array(0, row_phil, row_phl, row_eveeb, row_evenb) 

For i = LBound(row) To (UBound(row) - 1) 

    row_start = row(i) + 34 
    row_end = row(i + 1) - 1 + 34 
    row_indiv = Application.CountIf(Range("d" & row_start & ":d" & row_end), "INDIV") 
    row_sme = Application.CountIf(Range("d" & row_start & ":d" & row_end), "SME") 
    row_corp = Application.CountIf(Range("d" & row_start & ":d" & row_end), "CORP") 
     For k = row_start + row_indiv + row_sme - 34 To row_start + row_indiv + row_sme + row_corp - 1 - 34 
     With Sheets("LIVES PROJECTION") 
     .Range("B12:G12").Value = .Range("B34:G34").Offset(k, 0).Value 
     .Range("B12:FM26").Calculate 
     End With 
     Sheets("PREMIUMS PROJECTION").Range("B12:FM26").Calculate 
     Sheets("LIVES PROJECTION").Range("H34:FM34").Offset(k, 0).Value = Sheets("LIVES PROJECTION").Range("H12:FM12").Value 
     Sheets("PREMIUMS PROJECTION").Range("H34:FM34").Offset(k, 0).Value = Sheets("PREMIUMS PROJECTION").Range("H12:FM12").Value 
     Next k 
Next i 
'' 
Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 
Sheets("SETUP").Range("J33") = Sheets("SETUP").Range("J28") 
Calculate! 
end_time = Now() 
Sheets("SETUP").Range("j50") = DateDiff("s", start_time, end_time) 

End Sub 
+0

將變量聲明爲特定類型有幫助,但是您的當前聲明僅將特定類型賦予每行上的最後一個變量:在VBA中,每個變量都需要一個類型,或者默認情況下它們將是Variant。使用Long代替Integer也是一個好主意(最高可達32,767,對於Excel 2007+中的範圍具有風險)使用變量可以保存對每張工作表的引用,也可以用於多次使用的任何範圍。 – 2013-03-22 16:30:54

回答

1

你真的需要在For .. Next循環內計算這麼多嗎?如果您不這樣做,請在開始時切換到Application.Calculation = xlCalculationManual,並在最後計算一次。如果您確實需要在執行代碼時進行計算,請嘗試對其進行修改,以便儘可能少地進行計算。 使用With .. End With真的沒有太大的幫助。如果有的話。

相關問題