VBA using ubound on a multidimensional array

后端 未结 5 1668
刺人心
刺人心 2020-11-30 02:18

Ubound can return the max index value of an array, but in a multidimensional array, how would I specify WHICH dimension I want the max index of?

For example

5条回答
  •  余生分开走
    2020-11-30 03:02

    In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:

    Function sizeOfArray(arr As Variant) As String
        Dim str As String
        Dim numDim As Integer
    
        numDim = NumberOfArrayDimensions(arr)
        str = "Array"
    
        For i = 1 To numDim
            str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
            If Not i = numDim Then
                str = str & ", "
            Else
                str = str & ")"
            End If
        Next i
    
        sizeOfArray = str
    End Function
    
    
    Private Function NumberOfArrayDimensions(arr As Variant) As Integer
    ' By Chip Pearson
    ' http://www.cpearson.com/excel/vbaarrays.htm
    Dim Ndx As Integer
    Dim Res As Integer
    On Error Resume Next
    ' Loop, increasing the dimension index Ndx, until an error occurs.
    ' An error will occur when Ndx exceeds the number of dimension
    ' in the array. Return Ndx - 1.
        Do
            Ndx = Ndx + 1
            Res = UBound(arr, Ndx)
        Loop Until Err.Number <> 0
    NumberOfArrayDimensions = Ndx - 1
    End Function
    

    Example usage:

    Sub arrSizeTester()
        Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
        Debug.Print sizeOfArray(arr())
    End Sub
    

    And its output:

    Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)
    

提交回复
热议问题