Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 11: Mastering VBA Data Types and Procedures


431


Forcing explicit declaration
Access provides a simple compiler directive that forces you to always declare the variables in your
applications. The Option Explicit statement, when inserted at the top of a module, instructs
VBA to require explicit declaration of all variables in the module. If, for example, you’re working
with an application containing a number of implicitly declared variables, inserting Option
Explicit at the top of each module results in a check of all variable declarations the next time
the application is compiled.

Because explicit declaration is such a good idea, it may not come as a surprise that Access provides
a way to automatically ensure that every module in your application uses explicit declaration. The
Editor tab of the Options dialog box (shown in Figure 11.7) includes a Require Variable
Declaration check box. This option automatically inserts the Option Explicit directive at
the top of every module created from this point in time onward.

FIGURE 11.7

Requiring variable declaration is a good idea in most Access applications.


The Require Variable Declaration option doesn’t affect modules already written. This
option applies only to modules created after this option is selected, so you’ll have to insert the
Option Explicit statement in existing modules. Require Variable Declaration is not
set by default in current versions of Access. You must set this option yourself to take advantage of
having Access add Option Explicit to all your modules.

Using a naming convention
Like most programming languages, applications written in VBA tend to be quite long and complex,
often occupying many thousands of lines of code. Even simple VBA programs may require hundreds
of different variables. VBA forms often have dozens of different controls on them, including text
boxes, command buttons, option groups, and other controls. Keeping track of the variables, proce-
dures, forms, and controls in even a moderately complicated VBA application is a daunting task.
Free download pdf