Microsoft Access 2010 Bible

(Rick Simeone) #1

Part II: Programming Microsoft Access


426


Notice that the variable name follows the Dim statement. In addition to naming the variable, use
As Data Type to specify a data type for the variable. The data type is the kind of information that
will be stored in the variable — string, integer, currency, and so on. The default data type
is variant; it can hold any type of data.

When you use the Dim statement to declare a variable in a procedure, you can refer to that variable
only within that procedure. Other procedures, even if they’re stored in the same module, don’t
know anything about the variable declared within a procedure. Such a variable is often described
as local because it’s declared locally within a procedure and is known only by the procedure that
owns it. (You can read more about variable scope in the “Understanding variable scope and life-
time” section, later in this chapter.)

Variables also can be declared in the declarations section of a module. Then all the procedures in
the module can access the variable. Procedures outside the module in which you declared the vari-
able, however, can’t read or use the variable.

The Public keyword
To make a variable available to all modules in the application, use the Public keyword when you
declare the variable. Figure 11.6 illustrates declaring a public variable.

FIGURE 11.6

Declaring a public variable


Caution
You can’t declare a variable public within a procedure. It must be declared in the declarations section of a
module. If you try to declare a variable public within a procedure, you get an error message.


Although you can declare a public variable in any module, it seems logical to declare public vari-
ables only within the module that will use them the most. The exceptions to this rule are true
global variables that you want to make available to all procedures across modules and that are not
specifically related to a single module. Some programmers declare global variables in a single stan-
dard module so that you can find them easily.
Free download pdf