如何优化后续VBA代码的运行速度?

时间:2013-03-22 10:37:15

标签: vba optimization

我想提高遵循VBA代码的效率。我能想到的是使用" With" "结束"在代码中。我还能做些什么来优化代码吗?

谢谢!

 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

1 个答案:

答案 0 :(得分:1)

你真的需要在For .. Next循环中计算这么多吗?如果不这样做,请在开头切换到Application.Calculation = xlCalculationManual,并在结束时计算一次。如果您确实需要在执行代码期间进行计算,请尝试对其进行修改,以便尽可能少地计算。 使用With .. End With并没有太大帮助。如果有的话。