How to find the number of dimensions that an array has?

An array has 2 bounds: Upper and Lower.

I think you're asking where the lower bound begins.

By default, the lower bound is zero. For example:

Sub test()
    Dim arr
    arr = Array("a", "b", "c")
    Debug.Print "Lower: " & LBound(arr), "Upper: " & UBound(arr)
End Sub

returns: Lower: 0 Upper: 2 because the 3 elements have indices of 0, 1, and 2.


Some functionality may begin at 1 by default but it's rare. One example is filling an array with a range:

Sub test()
    Dim arr
    arr = Range("A2:A4")
    Debug.Print "Lower: " & LBound(arr), "Upper: " & UBound(arr)
End Sub

...returns: Lower: 1 Upper: 3


If you fully declare the array, you can make the upper and lower bound whatever you want:

Sub test()
    Dim arr(99 To 101) As String
    arr(100) = "blah"
    Debug.Print "Lower: " & LBound(arr), "Upper: " & UBound(arr)
End Sub

...returns: Lower: 99 Upper: 101, but an array with declared bounds won't work with many functions (like the previous examples.


You can also set the default lower bound with an statement at the very top of each module:

Option Base 1

...but there are so many places it doens't apply it's kind of useless. (More here.)


See also:

  • MSDN : Declaring Arrays (Fixed & Dynamic)

  • MSDN : LBound Function

  • MSDN : UBound Function


Is it possible to find the number of dimensions of an array in VBA?

This approach increments the possible dimensions count, 60 being the built in maximum (c.f. comment):

Private Function nDim(ByVal vArray As Variant) As Long
' Purpose: get array dimension (MS)
Dim dimnum     As Long
Dim ErrorCheck As Long    ' OP: As Variant
On Error GoTo FinalDimension

For dimnum = 1 To 60        ' 60 being the absolute dimensions limitation 
    ErrorCheck = LBound(vArray, dimnum)
Next
' It's good use to formally exit a procedure before error handling
' (though theoretically this wouldn't needed in this special case - see comment) 
Exit Function

FinalDimension:
nDim = dimnum - 1

End Function

Further links (thx @ChrisNeilson)

MS Using arrays

Big Array

Tags:

Excel

Vba