优化此vba代码以在很短的时间内运行

时间:2014-04-18 11:24:33

标签: vba for-loop

我有一个代码

For rptlop = 3 To ThisWorkbook.Worksheets("Raw").UsedRange.Rows.Count
    For sulop = 4 To ThisWorkbook.Worksheets("Calculated").UsedRange.Rows.Count
        If InStr(LCase(Worksheets("Calculated").Cells(sulop, 2)), LCase(Worksheets("Raw").Cells(rptlop, 1))) >= 1 _
        And InStr(LCase(Worksheets("Calculated").Cells(sulop, 1)), LCase(Worksheets("Raw").Cells(rptlop, 2))) >= 1 _
        And InStr(LCase(Worksheets("Calculated").Cells(sulop, 1)), LCase(Worksheets("Raw").Cells(rptlop, 3))) >= 1 Then
            ThisWorkbook.Worksheets("Raw").Cells(rptlop, 5) = ThisWorkbook.Worksheets("Calculated").Cells(sulop, clmqtr(Worksheets("Raw").Cells(rptlop, 4)))
            Exit For
        End If
    Next sulop
Next rptlop

我也有一个功能

Function clmqtr(myqtr) As Long
    Dim suclm As Long
    For suclm = 4 To ThisWorkbook.Worksheets("Calculated").UsedRange.Columns.Count
        If ThisWorkbook.Worksheets("Calculated").Cells(3, suclm) = myqtr Then
            clmqtr = suclm
            Exit For
        End If
    Next suclm
End Function
rptlop中的

我在sulop中有2900行我有70000多行。如何优化此代码以在很短的时间内运行?

1 个答案:

答案 0 :(得分:0)

在执行代码之前,有两个直接想法disable screen updating以及set calculation to manual。这可以防止excel在您的代码完成之前引用屏幕并执行计算。

'before your loop
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

'
'   your code here
'

'after your code executes, be sure to turn calculation and screen updating back on
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic