The array VBA code below calculates 9 periods exponential moving average of the values in Column U (from row 31 to last row ~row 6983). The output will be in Column V (from row 39 to last row). he problem now the second output value is 39 rows below i.e. cell V78, this should be located in cell V40, appreciate any VBA expert help, thanks
VBA Code:
Option Explicit
Sub EMA9()
Dim valArray As Variant
Dim runSum, EMA9() As Double
Dim i, lastRow, lRow, firstRow, x1, x2, iPeriod, iCol As Long
'Step1 - set last row and reference range to calculate
With Worksheets("Sheet1")
lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
valArray = .Range(.Cells(1, 21), .Cells(lastRow, 21)).Value2
End With
'Step2 - set lower and upper limit
iPeriod = 9
x1 = 2 / (iPeriod + 1)
x2 = 1 - (2 / (iPeriod + 1))
ReDim EMA9(LBound(valArray, 1) - 38 To UBound(valArray, 1), 1 To 1)
'Step3 - calculate first row value, [sum (row 31 to row 39)]
firstRow = 31
runSum = 0
For i = firstRow To (iPeriod + 30)
runSum = runSum + valArray(i, 1)
Next
'Step4 - calculate first row average value, [average (row 31 to row 39)]
EMA9(1, 1) = runSum / iPeriod
'Step5 - calculate the 2nd row (row 32) value onwards, [current value of valArray * x1 + previous value of EMA9 * x2]
For i = (iPeriod + firstRow) To UBound(valArray, 1)
EMA9(i, 1) = valArray(i, 1) * x1 + EMA9(i - 1, 1) * x2
Next
'Step6 - write the values to worksheet
iCol = 22
With Worksheets("Sheet1")
.Range(.Cells((iPeriod - 8), iCol), .Cells(lastRow, iCol)).Value2 = EMA9
End With
'Step7 - clear memory
Erase valArray: Erase EMA9
End Sub
Last edited by a moderator: