很抱歉提出这样一个基本问题,但这让我很生气...
VBA中的哪个函数返回数组中的元素数...即当数组为空时它将返回0?
我无法使用UBound执行此操作,因为它在空数组上调用时会抛出错误,并且我无法通过使用OnError首先确定它是否为空而无法相信这样做...就像在论坛上建议的那样! array.Length抱怨一个糟糕的限定符或其他东西。
我真的需要这样做:
dim termAry() as String
populate termAry
...
private sub populate(terms() as String)
redim preserve terms(terms.Length) ' Redim takes ubound for array size
terms(ubound(terms)) = "something really annoying"
end sub
P.S任何与VBA语言和函数参考的简洁集合的良好链接都是最有用的... MSDN似乎真的很模糊!!!
答案 0 :(得分:11)
我认为唯一的方法是使用On Error
并处理Subscript Out of Range
错误,如果数组(或您感兴趣的数组的维度)不是' t初始化。
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
<强>更新强>
回应评论:
我认为该功能不能轻易推广到任何阵列类型
可以通过将参数设置为Variant来轻松推广,并使用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