Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA array length (not ubound or onerror!)

Tags:

vba

ms-access

Sorry to ask such a basic question but this is driving me mad...

What function in VBA returns the number of elements in an array... i.e when the array is empty it will return 0?

I cant do this with UBound because it throws an error when called on an empty array and i cant believe the way to do this by using OnError to first determine if its empty or not... as is suggested on forums! array.Length complains about a bad qualifier or something.

I really need to do this:

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 any good links to a concise set of VBA language and function reference would be most useful... MSDN seems really obscure!!!

like image 451
user2361340 Avatar asked May 08 '13 10:05

user2361340


1 Answers

I believe the only way to do this is to use On Error and handle the Subscript Out of Range error that will be raised if the array (or the dimension of the array you're interested in) isn't initialized.

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

You can generalized this to test how many dimensions there are in an array, e.g.

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

In response to comment:

am i right in thinking that the function cannot be easily generalised to operate on any array type

It can be easily generalized by making the parameter a Variant, and checking it is an array in the body of the function using the IsArray function:

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
like image 50
Joe Avatar answered Oct 04 '22 23:10

Joe