我一直在嘗試使用VBA幾個月,但我不確定我在編寫速度方面非常高效。如何提高VBA代碼的速度
以下代碼是計算股票排名模型中使用的zscores。計算非常簡單,只需計算zscore=zscore1*weight1+zscore2*weight2....zscoreN*zscoreN
,其中zscores
位於不同的工作表中,並且權重包含在一個數組中。該代碼有效,但有500個股票和103個週期,大約需要30秒才能完成。我一直在尋求建議,以加速我的代碼/使其更好地「正確」,就好的編程實踐而言。
我知道我的代碼是混亂的,但因爲它的工作原理,我只是希望我可以在使用循環,if-sentenses和數組的方式上得到一些一般性建議。
Public factor() As Single
Sub zscores()
Dim StartTime As Double, EndTime As Double
Dim sheetNames() As String
Dim r As Integer, i As Integer
Dim antalAktier As Integer, perioder As Integer
Dim zscore As Single
StartTime = Timer
Worksheets("ZScores").Range("B2:AAA1000").ClearContents
'perioder and antalAktier is just variables to determine number of stocks and periods
perioder = Application.WorksheetFunction.CountA(Worksheets("returns").Range("A2:A1500"))
antalAktier = Application.WorksheetFunction.CountA(Worksheets("returns").Range("B1:AAA1"))
'Makes an array of sheetnames
r = 1
i = 0
ReDim sheetNames(0)
Do Until Worksheets("BloomdataFLDS").Cells(r, 1).Value = ""
sheetNames(i) = Worksheets("BloomdataFLDS").Cells(r, 1).Value
i = i + 1
ReDim Preserve sheetNames(i)
r = r + 1
Loop
'factor() is an array of values from textboxes in a userform
'Code uses the sheetnames array to jump between sheets and making a weighted average of the cell values and factor array values
k = 2
For k = 2 To antalAktier + 1
r = 2
For r = 2 To perioder + 1
zscore = 0
For i = 0 To (UBound(factor) - 18)
zscore = zscore + (factor(i) * Worksheets(sheetNames(i)).Cells(r, k).Value)
Next i
'truncates the value to be max/min +/- 3
If Worksheets("binær").Cells(k, r).Value = 1 And Worksheets("returns").Cells(r, k).Value <> "#N/A N/A" Then
If zscore < 3 And zscore > -3 Then
Worksheets("ZScores").Cells(r, k).Value = zscore
ElseIf zscore < -3 Then
Worksheets("ZScores").Cells(r, k).Value = -3
ElseIf zscore > 3 Then
Worksheets("ZScores").Cells(r, k).Value = 3
End If
Else:
Worksheets("ZScores").Cells(r, k).Value = ""
End If
Next r
Next k
EndTime = Timer
MsgBox "Execution time in seconds: " + Format$(EndTime - StartTime)
End Sub
可能重複[如何提高VBA宏代碼的速度?](http://stackoverflow.com/questions/13016249/how-to-improve-the-speed-of-vba-macro-code) –