First, since you're using Excel VBA, you don't need to use any special code to calculate the average of an array. You can use WorksheetFunction.Average
Option Explicit
Sub Question1()
Dim a() As Variant ' has to be a variant array, since that's what the `Array` function returns.
Dim i As Integer
Dim summ As Integer
Dim avg As Double
a = Array(12, 9, 8, 12, 16, 19, 3, 2, 5, 20)
avg = Excel.WorksheetFunction.Average(a)
MsgBox "Average is: " & avg
End Sub
If you want your code to be more portable (i.e. not have to depend on Excel's worksheet functions), then I would recommend splitting your average-calculation into a separate function you can call with any array and any base. To calculate the length of an array, you want to use both the LBound
and UBound
, as documented here:
n = UBound(a) - LBound(a) + 1
Assuming, of course, that a
is an array, this will always work, regardless of whether your array is 0-based, 1-based, or something completely different.
Since you're looping over the array to get the sum anyways, you can also use that loop to get the length anyways. Something like this:
Option Explicit
' assuming that arr is an array containing things we can sum, to get an average.
Public Function ArrayAverage(arr As Variant) As Double
Dim n As Long, sum As Double
Dim i As Long
n = 0: sum = 0
For i = LBound(arr) To UBound(arr)
n = n + 1
sum = sum + arr(i)
Next i
ArrayAverage = sum / n
End Function
Public Sub Question1()
Dim a() As Variant, avg As Double
a = Array(12, 9, 8, 12, 16, 19, 3, 2, 5, 20)
avg = ArrayAverage(a)
MsgBox "Average is: " & avg
End Sub