找到ZEROth Dimension Array

时间:2014-08-05 19:40:35

标签: arrays excel vba excel-vba

通常情况下,在寻找赎回量或其范围时,您可以使用UBound和LBound。

我现在被卡住,因为我有一个动态数组,我想检查它是否有第一个ReDim(或者它是否至少有一个维度)。

没有单维UBound(数组,1)超出范围。

那么如何检查它是否有零维度?

结果看起来或多或少像这样:

Dim array()
If NO_DIMENSIONS Then
    ...something...
End if

1 个答案:

答案 0 :(得分:2)

您可以使用错误捕获来完成此操作。

Function NumberOfDimensions(arr As Variant)

    'Sets up the error handler.
    On Error GoTo FinalDimension

    'Visual Basic for Applications arrays can have up to 60000
    'dimensions; this allows for that.
    For DimNum = 1 To 60000

        'It is necessary to do something with the LBound to force it
        'to generate an error.
        ErrorCheck = LBound(arr, DimNum)

    Next DimNum

FinalDimension:
        NumberOfDimensions = DimNum - 1

End Function

此代码已从Microsoft support的代码修改为函数。

所以你会这样使用:

Dim testArr()

If NumberOfDimensions(testArr) = 0 Then
    'Do Something
End If

在此方法中,您将该下标超出范围错误并使用它来计算有多少维度。