我相信唯一的方法是使用On Error
並處理Subscript Out of Range
錯誤,如果數組(或您感興趣的數組維度)未初始化,將會引發該錯誤。
E.g.
Public Function IsInitialized(arr() As String) As Boolean
On Error GoTo ErrHandler
Dim nUbound As Long
nUbound = UBound(arr)
IsInitialized = True
Exit Function
ErrHandler:
Exit Function
End Function
Dim a() As String
Dim b(0 To 10) As String
IsInitialized(a) ' returns False
IsInitialized(b) ' returns True
您可以將其推廣到測試數組中有多少維,例如,
Public Function HasAtLeastNDimensions(arr() As String, NoDimensions As Long) As Boolean
On Error GoTo ErrHandler
Dim nUbound As Long
nUbound = UBound(arr, NoDimensions)
HasAtLeastNDimensions = True
Exit Function
ErrHandler:
Exit Function
End Function
Dim a() As String
Dim b(0 To 10) As String
Dim c(0 To 10, 0 To 5) As String
HasAtLeastNDimensions(a, 1) ' False: a is not initialized
HasAtLeastNDimensions(b, 1) ' True: b has 1 dimension
HasAtLeastNDimensions(b, 2) ' False: b has only 1 dimension
HasAtLeastNDimensions(c, 2) ' True: c has 2 dimensions
UPDATE
在迴應評論:
我是正確的思維,該功能不能很容易地推廣到任何數組類型操作
它可以很容易地通過將參數設置爲Variant來泛化,並檢查它是f體內的數組使用IsArray
功能:
Public Function HasAtLeastNDimensions(arr As Variant, NoDimensions As Long) As Boolean
On Error GoTo ErrHandler
Dim nUbound As Long
If Not IsArray(arr) Then Exit Function
nUbound = UBound(arr, NoDimensions)
HasAtLeastNDimensions = True
Exit Function
ErrHandler:
Exit Function
End Function
來源
2013-05-08 11:29:48
Joe
你想要做什麼?你需要一個數組來源 - 它來自哪裏 – 2013-05-08 11:28:57
請參閱http://stackoverflow.com/questions/4097021/vba-handle-empty-array-error或http://stackoverflow.com/questions/206324/how -to-check-for-empty-array-in-vba-macro – 2013-05-08 11:29:04
所有你需要處理的事情就是說如果ubound(arr)> 1那麼...',初始化時使用'redim arr(MAX) – 2013-05-08 11:35:19