API reference · Finance
Mean
Returns the arithmetic mean of numeric values in a vector or the first column of a 2D array.
Signature#
Function Mean(ByVal vArr As Variant) As DoubleParameters#
| Parameter | VBA type | Default | Description |
|---|---|---|---|
vArr | VariantByVal | Required | Input 1D array or 2D array. For 2D input, only the column at its second-dimension lower bound is used. |
Returns#
Double. Sum(vArr) divided by Count(vArr, True), or 0 if there are no qualifying numeric values or the input shape is rejected.
Example#
Before
values2D · 3 × 2
Rows 1..3 · Columns 1..2
| row / col | 1 | 2 |
|---|---|---|
| 1 | 100 | 9000 |
| 2 | “200” | 9000 |
| 3 | Empty | 9000 |
After
Return valueValues / state
No array dimensions
| Item | Value |
|---|---|
| Mean | 150 |
(100 + 200) ÷ 2 = 150. The second column is ignored; Empty does not add to the count.
Shaded headers are array indices, not data. Quoted cells are text. Values shown are derived from the source, not an Excel execution.
Option Explicit
Public Sub ExampleFinanceMean()
Dim f As New Finance
Dim values As Variant
ReDim values(1 To 3, 1 To 2)
values(1, 1) = 100
values(2, 1) = "200"
values(3, 1) = Empty
values(1, 2) = 9000
values(2, 2) = 9000
values(3, 2) = 9000
Debug.Print f.Mean(values) '150; second column is ignored
End SubBehavior and edge cases#
- Accepts an allocated 1D array or a 2D array. A 1D array is expanded through the global Arr instance declared in a standard module. For 2D input, only the column at LBound(vArr, 2) is read; additional columns are ignored.
- Loops over the actual first-dimension lower and upper bounds. A horizontal 2D vector therefore contributes only its first cell; reduce it to 1D first if every cell should be included.
- The input is passed ByVal and is not deliberately modified. Non-array input or a detected rank other than 1 or 2 returns the default numeric value 0.
- Error values, Null and Empty are skipped before IsNumeric is evaluated. Numeric text is accepted and converted with CDbl using VBA locale rules; text that is not numeric is skipped. VBA Boolean and Date values are not numeric for IsNumeric.
- There is no overflow recovery. Values that pass IsNumeric but cannot be converted or accumulated within Double limits can raise a runtime error.
- Calls Me.Count(vArr, True) and then Me.Sum(vArr), producing two linear scans after shape normalization. A zero numeric count exits without dividing.
- A return value of 0 does not distinguish an actual zero mean from the absence of numeric observations.
Performance#
View implementation
Function Mean(ByVal vArr As Variant) As Double
'Returns the mean of numeric values in a column vector
Dim n As Long
If Not IsArray(vArr) Then Exit Function
If Arr.DimCounter(vArr) = 1 Then vArr = Arr.DimExpand(vArr)
If Arr.DimCounter(vArr) <> 2 Then Exit Function
n = Me.Count(vArr, True)
If n = 0 Then Exit Function
Mean = Me.Sum(vArr) / n
End Function