VBA check if array is one dimensional

后端 未结 5 1690
我寻月下人不归
我寻月下人不归 2020-12-08 12:01

I have an array (that comes from SQL) and can potentially have one or more rows.

I want to be able to figure out if the array has just one row.

UBound doesn\

5条回答
  •  萌比男神i
    2020-12-08 12:43

    I know you want to avoid using the error handler, but if it's good enough for Chip Pearson, it's good enough for me. This code (as well as a number of other very helpful array functions) can be found on his site:

    http://www.cpearson.com/excel/vbaarrays.htm

    Create a custom function:

    Function IsArrayOneDimensional(arr as Variant) As Boolean
        IsArrayOneDimensional = (NumberOfArrayDimensions(arr) = 1)
    End Function
    

    Which calls Chip's function:

    Public Function NumberOfArrayDimensions(arr As Variant) As Integer
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' NumberOfArrayDimensions
    ' This function returns the number of dimensions of an array. An unallocated dynamic array
    ' has 0 dimensions. This condition can also be tested with IsArrayEmpty.
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    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
    
    Err.Clear
    
    NumberOfArrayDimensions = Ndx - 1
    
    End Function
    

提交回复
热议问题