Variable Initialization

When a procedure begins execution, all of its local variables are automatically initialized, that is, given initial values. In general, however, it is not good programming practice to rely on this initialization, since it makes the program less readable and somewhat more prone to logical errors. Thus, it is a good idea to initialize all local variables explicitly, as in the following example:

Sub Example()

Dim x As Integer Dim s As String x = 0 ' Initialize x to 0

s = "" ' Initialize s to empty string

Note, however, that static variables cannot be initialized, since that defeats their purpose! Thus, it is important to know the following rules that VBA uses for variable initialization (note also that they are intuitive):

• Numeric variables (Integer, Long, Single, Double, Currency) are initialized to zero.

• A variable-length string is initialized to a zero-length (empty) string.

• A fixed-length string is filled with the character represented by the ASCII character code 0, or Chr(0).

• Variant variables are initialized to Empty.

• Object variables are initialized to Nothing.

The Nothing keyword actually has several related uses in Excel VBA. As we will see in Chapter 8, it is used to release an object variable. Also, it is used as a return value for some functions, generally to indicate that some operation has failed. Finally, it is used to initialize object variables.

0 0

Post a comment