I have a column which averages another column, to form a moving average series for a graph. For a moving average using a sample length of 4, it looks something like this:
B1 = A1
B2 = AVERAGE(A1:A2)
B3 = AVERAGE(A1:A3)
B4 = AVERAGE(A1:A4)
B5 = AVERAGE(A2:A5)
B6 = AVERAGE(A3:A6)
...
...
Simple enough. Now let's say I have a named range that contains the number of samples (we'll call it "SampleSize"). Right now I'm writing those hardcoded formulas in a VBA loop, and adjusting the first cell in the average based on the sample size. In the above example, I locked the first cell to A1 until I got to the 5th row, at which point it becomes a true moving average. This works fine, but the problem is I have to re-run the loop to create new hard-coded formulas in each cell any time the sample size changes...and that isn't very efficient due to other stuff that is going on in the loop.
How could I write a permanent dynamic formula for each cell, that would account for the variable sample size? Pseudo code would be something like:
B1 = A1
...
...
B4 = if SampleSize >= thisRow then AVERAGE(A1:AthisRow) else AVERAGE(AthisRow -SampleSize + 1:AthisRow)
B5 = if SampleSize >= thisRow then AVERAGE(A1:AthisRow) else AVERAGE(AthisRow-SampleSize + 1:AthisRow)
B6 = if SampleSize >= thisRow then AVERAGE(A1:AthisRow) else AVERAGE(AthisRow-SampleSize + 1:AthisRow)
...
...
The idea seems simple, but I'm drawing a blank. Any help appreciated!
- craig
(colored text seemed to work better than code tags )
Bookmarks