Average

R

RobcPettit

Hi Im trying to figure out why:
Dim j As Variant, x As Variant, k as variant
Dim arr(15) As Single

For x = 1 To 15
arr(j) = 5
j = j + 1
Next x

j = Application.WorksheetFunction.Average(arr)
k = Application.WorksheetFunction.StDev(arr),
does not return the expected results of 5 and 0. I get 4.68 and 1.25.
Any Ideas. Regards Robert
 
B

Bernie Deitrick

Rob,

By default, arrays are 0-based, and your variable j is initially zero, so
you are actually working with 15 5's and 1 zero.

Either use

Dim arr(1 to 15) As Single

or put

Option Base 1

at the top of your module.

Below is a fixed version...

HTH,
Bernie
MS Excel MVP

Sub NewSub()
Dim j As Integer
Dim x As Variant
Dim k As Variant

Dim arr(1 To 15) As Single

For x = 1 To 15
arr(x) = 5
Next x

j = Application.WorksheetFunction.Average(arr)
k = Application.WorksheetFunction.StDev(arr)
MsgBox j & " " & k

End Sub
 
G

Guest

Because the array has 16 elements not 15.
For x = 0 To 15 works.

An array starts on zero unless you have set it to 1 in an Option Base
Statement. See help for more info on this.

Regards,

Ossiemac
 
R

RobcPettit

Thankyou both for your replys. Once I added the option base that
solved my problem. Thankyou for the explanation, this is something I
can be aware of in the future.
Regards Robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top