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.