Variable Declaration and Scope

When you declare a variable within a Visual Basic 2005 class, the variable is available only within that instance of the class and cannot be accessed by another instance. If you declare the variable as Shared, it is available to all instances of the class. In VBA, variables declared within a code block, such as a loop, are available locally to the entire procedure, but variables in Visual Basic 2005 are available only within the code block itself. If you declare a variable within a looping structure, the variable is not available outside the loop.

As in VBA, you declare a variable in Visual Basic 2005 using the Dim statement and specify a data type for the variable. If you do not specify a data type in VBA, the variable is automatically created as the type Variant. The Variant data type is no longer supported in Visual Basic 2005. Instead, an unspecified variable is created as an Object.

As a best practice, you should always explicitly type any variables that you declare. This is to avoid late binding to variables. Although late binding is supported in Visual Basic 2005, early-bound variables aid in code readability, and enable IntelliSense on the object. Figure 4.5 shows the differences in IntelliSense capabilities when a variable's data type is not specified versus when it is specified.

In VBA, if you declare more than one variable within a statement, you must specify the type for each variable or else it defaults to the Variant type. In Visual Basic 2005, you can declare multiple variables as the same type. Table 4.4 shows the difference in multiple variable declarations between VBA and Visual Basic 2005.

Array variables should not be declared using the New keyword (As New). In VBA, you can automatically initialize array members by declaring the array with the New keyword. This keyword is not supported for arrays in Visual Basic 2005. Instead, you must explicitly initialize the members of an array, as shown in Listing 4.12.

Dim myString = "Hello World" myString.|

Dim myString = "Hello World" myString.|

Dim myString As String = "Hello World" myString.|

■a/ EndsWith iiy IndexOf iiy Insert ¡'■s LastlndexOf

Length ^'y Remove ^'y Replace iiy Split iiy StartsWith

Common | All

Figure 4.5. Late binding to variables (top) versus early binding

Table 4.4. Variable Declaration in VBA and Visual Basic 2005

Declaration

VBA

Visual Basic 2005

Dim iCount, iTotal As Integer

iCount is Variant,

Both iCount and

iTotal is Integer.

iTotal are Integers.

Dim iCount

iCount is a Variant

iCount is an Object

data type.

data type.

Listing 4.12. Initializing an array

Dim Fruit() As String = {"apples", "oranges", "bananas", "pears"} MsgBox(Fruit(0))

0 0

Post a comment