Hi,
I am trying to perform a Weighted Moving Average Calculation in VBA. The code below seems simple enough but generates an error. Input data are in column B starting at row 2. WMA output is in column G starting at row 2.
Is there someone in the Forum who can determine what is causing the error? Here's the code:
Any help would be greatly appreciated.
Thanks,
Art
I am trying to perform a Weighted Moving Average Calculation in VBA. The code below seems simple enough but generates an error. Input data are in column B starting at row 2. WMA output is in column G starting at row 2.
Is there someone in the Forum who can determine what is causing the error? Here's the code:
Code:
Sub wma()
Dim i As Long
Dim n As Long
Dim wma As Double
Dim weight As Double
Dim sumWeight As Double
Dim colData As Long
Dim colWMA As Long
colData = 2 ' Column containing the data
colWMA = 7 ' Column to output the WMA
n = 5 ' Length of the WMA
For i = 2 To Cells(Rows.Count, colData).End(xlUp).Row
wma = 0
weight = 0
sumWeight = 0
For j = i - n + 1 To i
weight = weight + 1
wma = wma + Cells(j, colData) * weight
sumWeight = sumWeight + weight
sumWeight = 1
Next j
Cells(i, colWMA).Value = wma / sumWeight
Next i
End Sub
Any help would be greatly appreciated.
Thanks,
Art