Microsoft Access 2010 Bible

(Rick Simeone) #1

Part II: Programming Microsoft Access


422


l (^) You provide a meaningful name for the variable as part of the Dim statement. In Figure
11.5, the variable names are strDocName and strLinkCriteria, indicating how the
variables are used by the procedure.
l The Dim statement includes the data type of the new variable. In Figure 11.5, both vari-
ables are declared as the string data type.
l Different techniques can be used to assign a value to a variable. Figure 11.5 uses the =
operator to assign a literal value — frmContactLog — to strDocName. Notice that
frmContactLog is surrounded by quotation marks, making it a “literal” value. A value
pulled from the txtContactID text box on the form’s surface is combined with a literal
string — “[ContactID]=“ — and assigned to the strCriteria variable. The data
assigned to variables should always be appropriate for the variable’s data type.
l Variables are manipulated with a variety of operators. Figure 11.5 uses the VBA concate-
nation operator (&) to combine [ContactID]= and the value in txtContactID.
There are a number of ways to perform each of the tasks you see in Figure 11.5. For example, as
you’ll read in the “Declaring variables” section, later in this chapter, the Dim statement is not the
only way to establish a variable. And, as you’ll see throughout this book, the = operator is not the
only way to assign a value to a variable. Also, you don’t need to use a variable like strCriteria
to temporarily hold the value generated by combining two values. The two values could just as
easily be combined on the fly within the DoCmd.OpenForm statement:
DoCmd.OpenForm “frmContactLog”, _
“[ContactID] = “ & Me![txtContactID]
There are very few rules governing how you declare and use your variables. You should always
strive for readability in your VBA code. In the small example shown in Figure 11.5, you can easily
see that strFormName holds the name of a form, especially because it’s used as part of the
DoCmd.OpenForm statement.
Naming variables
Every programming language has its own rules for naming variables. In VBA, a variable name must
meet the following conditions:
l It must begin with an alphabetical character.
l (^) It must not contain an embedded period.
l It must have a unique name. The variable’s name cannot be used elsewhere in the proce-
dure or in modules that use the variables.
l It must not contain spaces or punctuation characters.
l (^) It must not be a reserved word, such as Sub, Module, or Form.
l It must be no longer than 64 characters.

Free download pdf