Microsoft Access 2010 Bible

(Rick Simeone) #1

Part II: Programming Microsoft Access


394


Each VBA code module includes two or more sections:

l A declarations section at the top of the module

l (^) A section for each procedure
The declarations section
You can use the declarations section at the top of a VBA module to declare (define) variables used
in the module’s procedures. A variable is a way to temporarily store values as your code runs.
Examples of variables include
l (^) intCounter (an integer)
l curMySalary (a currency)
l (^) dtmDate (a date/time)
The three-character prefixes (int, cur, dtm) in these variable names constitute a simple naming
convention and are entirely optional. Naming conventions are routinely used by most Access
developers to help document a variable’s data type (integer, currency, and datetime, respectively,
in this case). Anything you can do to document your application helps reduce maintenance costs
and make your code easier to modify later on.
The name you give a variable doesn’t determine the type of data contained within the variable.
Caution
You might have noticed the Option Explicit line at the top of the VBA modules in this chapter’s figures
and example database. Option Explicit is a directive that instructs the VBA compiler to require every vari-
able to be “explicitly” declared within the module. This means that every variable must be declared as a spe-
cific data type (integer, string, and so on).
Explicit variable declaration is always a good idea because it prevents stray variables from creeping into an
application and causing bugs. Without the Option Explicit directive at the top of the module, every time
you type in an identifier that the VBA compiler doesn’t recognize, it automatically creates a new variable by
that name. This means that, when using “implicit” variable declarations, if you’ve been using a variable named
strLastName and type it in incorrectly (for example, strLstName), the VBA compiler creates a new vari-
able named strLstName and begins using it. Bugs caused by simple misspellings can be very difficult to
detect, because the application doesn’t raise any errors, and the only way to detect the cause of the bug is to
go through the code one line at a time until you find the misspelling.
You aren’t required to declare every variable used in a module within the declarations section,
because variables are also declared within procedures. But be aware that all the variables defined in
the declarations section are shared by all the procedures within the module.
Cross Reference
Variable scope (the term that describes where a variable can be used in an application) is described in Chapter 11.

Free download pdf