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.
First off there is no predefined identifier called
vbUndefinedas the currently accepted answer appears to imply. That code only works when there is not anOption Explicitat the top of the script. If you are not yet usingOption Explicitthen start doing so, it will save you all manner of grief.The value you could use in place of
vbUndefinedisEmpty, e.g.,:-Emptyis 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:-
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
IsEmptyfunction:-IsEmptywill only return true if the parameter it actually properlyEmpty.There is also another issue,
Nullis a possible value that can be held in an array or variable. However:-Is a runtime error, “invalid use of null” and :-
is false. So you need to decide if
Nullmeans undefined or is a valid value. IfNullalso means undefined you need yourIfstatement to look like:-You might be able to waive this if you know a
Nullwill never be assigned into the array.