HandsOn Using Variables

This chapter's hands-on exercises are provided in the Acc2003_Chap03.mdb file included in the book's downloadable files.

1. Open Acc2003_Chap03.mdb from the downloadable files or, if you'd like to start from scratch, create a new Microsoft Office Access 2003 database.

2. Click the Modules button in the Database window and then click the New button to create a new module. When the Visual Basic Editor window appears you will notice Module1 under the Modules folder in the Project Explorer window.

3. In the [Module1 (Code)] window that appears in the center of the screen, enter the code of the AgeCalc procedure shown below.

4. If the Immediate window is not open, press Ctrl+G or choose View | Immediate Window. Since the example procedure writes the results to the Immediate window, you should ensure that this window is open prior to executing step 5 below.

5. To run the procedure, click any line between the Sub and End Sub keywords and press F5.

Sub AgeCalc()

' variable declaration Dim FullName As String Dim DateOfBirth As Date Dim age As Integer

' assign values to variables FullName = "John Smith" DateOfBirth = #l/3/1967#

' calculate age age = Year(Now()) - Year(DateOfBirth)

' print results to the Immediate window Debug.Print FullName & " is " & age & " years old." End Sub

Notice that in the AgeCalc procedure the variables are declared on separate lines at the beginning of the procedure. If you want, you can declare several

Introduction to Access 2003 VBA Programming variables on the same line, separating each variable name with a comma, as shown in the example below:

Dim FullName As String, DateOfBirth As Date, age As Integer

When you list all your variables on one line, the Dim keyword appears only once at the beginning of the variable declaration line.

0 0

Post a comment