Chapter 11: Mastering VBA Data Types and Procedures
427
Tip
You can declare public variables in the code module attached to a form or report. Referencing these public
variables from another module is a little bit different than referencing public variables declared in standard
modules. To reference the value of a public variable declared behind a form or report from another module,
you must qualify the variable reference, using the name of the form or report object. frmMainForm.
MyVariable, for example, accesses a form named frmMainForm and obtains the value of the public vari-
able MyVariable declared in the form’s code module. Public variables declared within a form or report’s
module cannot be referenced unless the form or report is open.
The Private keyword
The declarations section in Figure 11.6 shows the use of the Dim and Private statements to
declare variables. Technically, there is no difference between Private and Dim, but using
Private at the module level to declare variables that are available to only that module’s proce-
dures is a good idea. Declaring private variables contrasts with
l (^) Dim, which must be used at the procedure level, distinguishing where the variable is
declared and its scope (Module versus Procedure)
l (^) Public, the other method of declaring variables in modules, making understanding your
code easier
Tip
You can quickly go to the declarations section of a module while you’re working on code in a form’s module
by selecting (Declarations) from the Procedure drop-down list in the code editor. Another way to move
to the declarations section is to select (General) in the Object drop-down list in the code editor. (Refer to
the Module window combo boxes in Figure 11.6.) The Declarations item is not available when a control, or the
form, is selected in the Object drop-down list.
When you declare a variable, you use the AS clause to specify a data type for the new variable.
Because Access is a database development system, it’s not surprising that variable data types are
similar to field data types in an Access database table.
Working with Data Types
When you declare a variable, you also specify the data type for the variable. Each variable has a
data type. The data type of a variable determines what kind of information can be stored in the
variable.
A string variable — a variable with a data type of string — can hold character values ranging
from A to Z, a to z, and 0 to 1 , as well as formatting characters (#, -, !, and so on). Once created,
a string variable can be used in many ways: comparing its contents with another string, pulling
parts of information out of the string, and so on. If you have a variable defined as a string, how-
ever, you cannot use it to do mathematical calculations.