Specifying the Data Type of a Variable

If you don't specify the variable's data type in the Dim statement, you end up with the untyped variable. Untyped variables in VBA are always assigned the Variant data type. Variant data types can hold all the other data types (except for user-defined data types). This feature makes Variant a very flexible and popular data type. Despite this flexibility, it's highly recommended that you create typed variables. When you declare a variable of a certain data type, your

Part I

VBA procedure runs faster because Visual Basic does not have to stop to analyze the variable to determine its type.

Visual Basic can work with many types of numeric variables. Integer variables can only hold whole numbers from -32,768 to 32,767. Other types of numeric variables are Long, Single, Double, and Currency. The Long variables can hold whole numbers in the range -2,147,483,648 to 2,147,483,647. As opposed to Integer and Long variables, Single and Double variables can hold decimals.

String variables are used to refer to text. When you declare a variable of the String data type, you can tell Visual Basic how long the string should be. For instance, Dim extension As String * 3 declares the fixed-length String variable named extension that is three characters long. If you don't assign a specific length, the String variable will be dynamic. This means that Visual Basic will make enough space in computer memory to handle whatever amount of text is assigned to it.

After you declare a variable, you can only store in it the type of information that you stated in the declaration statement. Assigning string values to numeric variables or numeric values to string variables results in the error message "Type Mismatch" or causes Visual Basic to modify the value. For example, if your variable was declared to hold whole numbers and your data uses decimals, Visual Basic will disregard the decimals and use only the whole part of the number.

Let's use the MyNumber procedure in Hands-On 3-2 below as an example of how Visual Basic modifies the data according to the assigned data types.

0 0

Post a comment