API reference · Arrays

DimCounter

Probe array dimensions with UBound, up to the implementation's fixed limit of ten.

FunctionArrays→IntegerSource L59

Signature#

VBA
Function DimCounter(ByVal vArr As Variant) As Integer

Parameters#

ParameterVBA typeDefaultDescription
vArrVariantByValRequiredVariant to inspect. Scalars and arrays whose first dimension cannot be queried return zero.

Returns#

Integer. Returns 1 through 9 when the next UBound dimension probe fails. Returns 0 for non-arrays, unallocated dynamic arrays, and arrays for which all ten dimension probes succeed.

Example#

SEE THE TRANSFORMATIONCount dimensions, not elements
Before
transactions2D · 3 × 2

Rows 1..3 · Columns 1..2

row / col12
1EmptyEmpty
2EmptyEmpty
3EmptyEmpty
Additional input
vector1D · (3,)

Indices 0..2 · one dimension

012
10025080
After
Dimension countsValues / state

No array dimensions

ItemValue
transactions2
vector1
scalar 1000

The matrix contains six Empty cells. The vector has three elements; the scalar is not an array.

Shaded headers are array indices, not data. Quoted cells are text. Values shown are derived from the source, not an Excel execution.

VBA
Sub ExampleDimCounter()
    Dim a As New Arrays
    Dim transactions As Variant
    Dim vector As Variant

    ReDim transactions(1 To 3, 1 To 2)
    vector = VBA.Array(100, 250, 80)
    Debug.Print a.DimCounter(transactions) ' Expected: 2
    Debug.Print a.DimCounter(vector)       ' Expected: 1
    Debug.Print a.DimCounter(100)          ' Expected: 0
End Sub

Behavior and edge cases#

Performance#

At most ten UBound probes: O(1) time under the fixed limit and O(1) auxiliary storage.

View implementation
VBA
Function DimCounter(ByVal vArr As Variant) As Integer
    'Returns the number of dimensions in an array

    Dim lDim            As Long
    Dim lDim_checker    As Long
    Dim iDim            As Long

    If Not IsArray(vArr) Then
        DimCounter = 0
        Exit Function
    End If

    For iDim = 1 To LTOTALDIMCHECK
        On Error Resume Next
        lDim_checker = UBound(vArr, iDim)
        If Err <> 0 Then
            Err.Clear
            On Error GoTo 0
            DimCounter = iDim - 1
            Exit Function
        End If
    Next iDim
End Function