Variables have the values your program assigns to them. Before ally value is assigned ‘ to them, numeric variables are zero, and string variables are zero length (“”). There are, however, four special values: Empty, Null, Nothing, and Error,
The Empty Value
If a variant variable has been declared, but has not yet ( been assigned a value, its value is Empty. The Empty value is different from a zero length string. To find out if a variable has been initialized with the Is Empty function use:
If IsEmpty(var) then MsgBox “Variable has not been initialized’
As soon as you assign a value to the variable, it’s no longer Empty, and the IsEmpty() function returns False. You can also set a variable to Empty with the following statement:
var = Empty
The Empty value is used with numeric, string, and date variables. You can use the Empty value to reset variables before calling a procedure.
The Null Value
Null is commonly used in database applications to indicate that a field doesn’t contain data or that an object variable hasn’t been assigned a value, The Null value is different from the Empty value. Available of the types we have examined so far is never Null, unless you assign the value Null to it with the following statement:
var = Null
Uninitialized variables that refer to database fields are Null, not Empty, as in the following:
If Not IsNull(varField) Then
{process variable varField}
End If
If your code calls a function to create a new object, it must always check the value of the new object variable with the IsNulI() statement to verify that the object has been created.
The Nothing Value
The Nothing value is used with objects and indicates that an object variable has not been initialized. If you want to disassociate an object variable from an object, set it to Nothing with the Set statement. The following statements create an object variable that references Excel and then releases it:
The first Print statement will display the string “Microsoft Excel” on the Immediate window. The second Print statement will raise a runtime error; because the myVar variable does not point to any object (it is disassociated from Excel when it is set to Nothing). Visual Basic doesn’t know where to look for the Name property and generates a runtime error. Of course, if Excel is not installed on your computer, the very first line will generate an error message.
The Error Value
This is a peculiar value that allows you to write functions that return Variant types or errors. If the function carries out its operations successfully, the result is returned as usual (it must be a Variant). If an error occurs, then the function can return an Error value. The calling program must examine the function’s return value and act accordingly:
For more information on using the Error type, see the section “Errors as Function Return Values” later in this chapter.