【问题标题】:VBA array length (not ubound or onerror!)VBA 数组长度(不是 ubound 或 onerror!)
【发布时间】:2013-05-02 13:53:28
【问题描述】:

很抱歉问了这么一个基本问题,但这让我发疯了......

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 似乎真的很晦涩!!!

【问题讨论】:

标签: vba ms-access


【解决方案1】:

我相信这样做的唯一方法是使用On Error 并处理Subscript Out of Range 错误,如果数组(或您感兴趣的数组的维度)未初始化,则会引发该错误。

例如

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

【讨论】:

  • 这适用于字符串数组,我是否认为该函数不能轻易泛化以对任何数组类型进行操作......似乎元素明智的类型转换需要深层复制?
猜你喜欢
  • 2014-04-08
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多