HandsOn Using a One Dimensional Array

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

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

2. Switch to the Visual Basic Editor window and insert a new module.

3. Enter the following FavoriteCities procedure in the Code window to start indexing array elements at 1:

Option Base 1

Part I

Sub FavoriteCities() ' declare the array Dim cities(6) As String

' assign the values to array elements cities(1) = "Baltimore"

cities(2) = "Atlanta"

cities(3) = "Boston"

cities(4) = "Washington"

cities(6) = "Trenton"

' display the list of cities

MsgBox cities(1) & Chr(13) & cities(2) & Chr(13) _ & cities(3) & Chr(13) & cities(4) & Chr(13) _ & cities(5) & Chr(13) & cities(6)

End Sub

4. Choose Run | Run Sub/UserForm to execute the FavoriteCities procedure.

5. Modify the FavoriteCities procedure so that it displays the names of the cities in reverse order (from 6 to 1).

Before the FavoriteCities procedure begins, the default indexing for an array is changed. Notice that the position of the Option Base 1 statement is at the top of the module window before the Sub statement. This statement tells Visual Basic to assign the number 1 instead of the default 0 to the first element of the array. The array cities is declared with six elements of the String data type. Each element of the array is then assigned a value. The last statement in this procedure uses the MsgBox function to display the list of cities in a message box. When you run this procedure, each city name will appear on a separate line (see Figure 7-1). You can change the order of the displayed data by switching the index values.

Initial Value of an Array Element

Until a value is assigned to an element of an array, the element retains its default value. Numeric variables have a default value of zero (0), and string variables have a default value of empty string ("").

Introduction to Access 2003 VBA Programming

0 0

Post a comment