Declaring Variables

You declare a variable with the Dim keyword. Dim stands for "dimension." The Dim keyword is followed by the variable's name and type.

Suppose you want the procedure to display the age of an employee. Before you can calculate the age, you must feed the procedure the employee's date of birth. To do this, you declare a variable called DateOfBirth, as follows:

Dim DateOfBirth As Date

Notice that the Dim keyword is followed by the name of the variable (DateOfBirth). If you don't like this name, you are free to replace it with another word, as long as the word you are planning to use is not one of the VBA keywords. You specify the data type the variable will hold by including the As keyword followed by one of the data types from Table 3-1. The Date data type tells Visual Basic that the variable DateOfBirth will store a date. To store the employee's age, you will declare the age variable, as follows:

Dim age As Integer

The age variable will store the number of years between today's date and the employee's date of birth. Since age is displayed as a whole number, the age variable has been assigned the Integer data type.

You may also want your procedure to keep track of the employee's name, so you declare another variable to hold the employee's first and last name:

Dim FullName As String

Since the word Name is on the VBA list of reserved words, using it in your VBA procedure would guarantee an error. To hold the employee's full name, we used the variable FullName and declared it as the String data type because the data it will hold is text. Declaring variables is regarded as good programming practice because it makes programs easier to read and helps prevent certain types of errors.

Part I

0 0

Post a comment