I want to take the average value of only a few items in an array in Microsoft Excel-VBA. For Example, take the average, for every pair of numbers in the vector: 45 21 63 12 19. The major problem here is, that I want to be able to make the quantity of numbers dynamic so that it can also always take the average of every 3 numbers.
I tried using the Index
function, or the Offset
function, but both did not work.
Dim arrMarks(1 To 5) As Long
arrMarks(1) = 45
arrMarks(2) = 21
arrMarks(3) = 63
arrMarks(4) = 12
arrMarks(5) = 19
length = UBound(arrMarks, 1) - LBound(arrMarks, 1) + 1
' take the average of m numbers
m = 3
m_length = length - (m-1)
Dim arravg(1 To m_length)
For i = 1 To m_length
If (i + m) <= length Then
arravg(i) = Application.WorksheetFunction.Average(arrMarks.Offset(m, 0))
End If
Next i
This example just returns an error.
Desired outcome:
Values of arravg being:
Average(45, 21, 63)
Average(21, 63, 12)
Average(63, 12, 19)
I hope to make the code in a way that m
can be filled with any number (as long as m < length) and make it work. Do you have any idea?