Visual Basic 6's Variant data type is able to hold any other data type, including numbers, strings, dates, and object references. This data type can be very useful in a wide variety of situations. I'll show you a couple of useful tricks with Variants.
When a Variant has been declared but not assigned a value, it contains the special value Empty. You can test for this with the IsEmpty function. For example, suppose you want to determine whether a Variant has been assigned a value. If it has been assigned a value, you do nothing; if it hasn't been assigned a value, then assign the value 0. Here's how (assume that V is a type Variant variable):
If IsEmpty(V) Then V = 0
If an empty Variant is used in an expression, it will evaluate as either the value 0 or an empty string depending on the expression.
Another useful special value is Null, which is traditionally used to indicate that a variable does not contain valid data. You can assign this value to a Variant with the Null keyword:
V = Null
You can test for it with the IsNull function. For example, if Name is a type Variant:
If IsNull(Name) Then
MsgBox "The name is not valid"
MsgBox "The name is " & Name
You cannot use Null with any variable type other than Variant.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!