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

前端 未结 2 700
清酒与你
清酒与你 2021-01-11 23:38

Below is a piece of code where I need to store some info about a warning message by going through messages passed. The parameter passed itself is a variant which is set by a

相关标签:
2条回答
  • 2021-01-12 00:05

    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

    0 讨论(0)
  • 2021-01-12 00:14

    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

    0 讨论(0)
提交回复
热议问题