ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Average (https://www.excelbanter.com/excel-programming/382973-average.html)

RobcPettit[_2_]

Average
 
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


Bernie Deitrick

Average
 
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


"RobcPettit" wrote in message
oups.com...
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




OssieMac

Average
 
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

"RobcPettit" wrote:

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



RobcPettit[_2_]

Average
 
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



All times are GMT +1. The time now is 01:54 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com