I have a column of data (B), and I would like to use VBA to calculate the averages of several ranges specified within the column. I made this UDF:
Function Avg(StartRow As Long, EndRow As Long) As Long
' Calculates average of range beginning at row "StartRow" and ending at row "EndRow".
Dim i As Long
Dim Sum As Long
Dim Num As Long
Sum = 0
Num = 0
For i = StartRow To EndRow
Sum = Sum + Cells(i, 2) ' <-- Always comes out as 0.
Next i
Num = Range(Cells(StartRow, 2), Cells(EndRow, 2)).Count
Avg = Sum / Num
Then I call on this function in a subroutine as follows:
For i = 1 To NumSteps
Cells(11, i + 6) = Avg(StartRow(i), EndRow(i))
Next i
Where StartRow() and EndRow() hold a varying number of values depending on NumSteps.
NumSteps is the number of ranges I need to take the average of and is defined earlier in the subroutine.
The problem seems to be in the Avg function, specifically the part that finds the sum. I'm not sure why, but this value always comes out as zero.
Bookmarks