tags:

views:

616

answers:

3

What is the "best" way to determine the number of elements in an array in VBScript?

UBound() tells you how many slots have been allocated for the array, but not how many are filled--depending on the situation, those may or may not be the same numbers.

+2  A: 

There's nothing built in to tell you what elements are filled. The best way is to keep track of this yourself using a count variable as you add/remove elements from the array.

Spencer Ruport
+3  A: 

I'm not aware of a non-iterative method to do this, so here's the iterative method:

Function countEmptySlots(arr)
    Dim x, c
    c = 0
    For x = 0 To ubound(arr)
     If arr(x) = vbUndefined Then c = c + 1
    Next
    countEmptySlots = c
End Function

As Spencer Ruport says, it's probably better to keep track yourself to begin with.

Chris Nielsen
This actually gets the opposite of what I wanted, but the technique works just as well the other way around (looking for filled slots, comparing arr(x) <> vbUndefined).
TSomKes
See the answer provided by AnthonyWJones for a more comprehensive solution.
Chris Nielsen
+3  A: 

First off there is no predefined identifier called vbUndefined as the currently accepted answer appears to imply. That code only works when there is not an Option Explicit at the top of the script. If you are not yet using Option Explicit then start doing so, it will save you all manner of grief.

The value you could use in place of vbUndefined is Empty, e.g.,:-

If arr(x) = Empty Then ...

Empty is a predefined identify and is the default value of a variable or array element that has not yet had a value assigned to it.

However there is Gotcha to watch out for. The following statements all display true:-

MsgBox 0 = Empty
MsgBox "" = Empty
MsgBox CDate("30 Dec 1899") = True

Hence if you expect any of these values to be a valid defined value of an array element then comparing to Empty doesn't cut it.

If you really want to be sure that the element is truely "undefined" that is "empty" use the IsEmpty function:-

If IsEmpty(arr(x)) Then

IsEmpty will only return true if the parameter it actually properly Empty.

There is also another issue, Null is a possible value that can be held in an array or variable. However:-

MsgBox Null = Empty

Is a runtime error, "invalid use of null" and :-

MsgBox IsEmpty(Null)

is false. So you need to decide if Null means undefined or is a valid value. If Null also means undefined you need your If statement to look like:-

 If IsEmpty(arr(x)) Or IsNull(arr(x)) Then ....

You might be able to waive this if you know a Null will never be assigned into the array.

AnthonyWJones