Visual Basic

Overview of Variants

In Visual Basic 6, UDTs have been added to the list, effectively completing the set. Now a Variant can be assigned any variable or constant, whatever the type.

A variety of functions convert to these subtypes and test for these subtypes. Table 4-1 shows the development of the Variant data type through the versions of Visual Basic, along with the matching functions.

Table 4-1 The Evolution of Variants

Type Visual Basic Name Visual Basic Version Convert Function Test Function
0 Empty 2 = Empty IsEmpty
1 Null 2 = Null IsNull
2 Integer 2 CInt IsNumeric*
3 Long 2 CLng IsNumeric
4 Single 2 CSng IsNumeric
5 Double 2 CDbl IsNumeric
6 Currency 2 CCur IsNumeric
7 Date 2 CVDate/CDate IsDate
8 String 2 CStr
9 Object 4 IsObject
10 Error 4 CVErr IsError
11 Boolean 4 CBool
12 Variant 4 CVar
13 Data Object 4
14 Decimal 5 CDec IsNumeric
17 Byte 4 CByte
36 UDT 6
8192 Array 4 Array IsArray
16384 ByRef Never?

*Strictly speaking, IsNumeric tests to see if a variable can be converted to a numeric value, and is not simply reporting on a Variant's subtype.

Internal Structure

A Variant always takes up at least 16 bytes of memory and is structured as shown in Figure 4-1.

Figure 4-1 The structure of a Variant

The first two bytes correspond to the value returned by the VarType function. (The VarType return values are defined as constants in the VbVarType enumeration.) For example, if the VarType is 2 (the value of the constant vbInteger), the Variant has a subtype of Integer. You cannot change this value directly, but the conversion functions (such as CInt) will do this for you.

The Reserved bytes have no documented function yet; their principal purpose is to pad the structure out to 16 bytes. The Data area holds the value of the variable, if the value fits into 8 bytes; otherwise, the Data area holds a pointer to the data (as with strings and so on). The type indicates how the Data portion of the Variant is to be understood or interpreted.

In this way, Variants are self-describing, meaning they contain within them all the information necessary to use them.