Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Speed up an Excel Macro?

Right now I have a macro PopulateYearlyValues But it seems to me it's taking way too long

Sub PopulateYearlyValues(ByVal Month As Range)
    Dim c As Double
    Dim s As Double
    c = Application.WorksheetFunction.Match(UCase(Month.Value), ActiveSheet.Range("AA5:AX5"), 0)
    s = (ActiveSheet.Range("AA5").Column - 1)
    With ActiveSheet
        Dim i As Integer
        Dim j As Integer
        For i = 7 To 44
            .Range("G" & i).Value = 0
            .Range("H" & i).Value = 0
            For j = 1 To c
                .Range("G" & i).Value = (.Range("G" & i).Value + .Cells(i, s).Offset(0, j))
                .Range("H" & i).Value = (.Range("H" & i).Value + .Cells(i, s).Offset(0, (j + 1)))
                j = j + 1
            Next j
        Next i
    End With
End Sub

I have a range G7:H44 that needs to be populated with the SUM of range AA7:AX44 but.. it's only every other column:

If Month.Value = "January"
    G7  = SUM(AA7)
    H7  = SUM(AB7)
    ...
    G44 = SUM(AA44)
    H44 = SUM(AB44)
End If

If Month.Value = "April"
    G7  = SUM(AA7, AC7, AE7, AG7)
    H7  = SUM(AB7, AD7, AF7, AH7)
    ...
    G44 = SUM(AA44, AC44, AE44, AG44)
    H44 = SUM(AB44, AD44, AF44, AH44)
End If

But the macro I have is taking way too long.. Is there any other way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try the usual vba optimization methods of setting calculation to manual and disabling ScreenUpdating .

Dim calc As XlCalculation
calc = Application.Calculation
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Application.ScreenUpdating = True
Application.Calculation = calc

Put your code or function call between Application.Calculation = xlCalculationManual and Application.ScreenUpdating = True

This is from my previous Post


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...