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

前端 未结 2 725
清酒与你
清酒与你 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

提交回复
热议问题