Microsoft Access 2010 Bible

(Rick Simeone) #1

Part II: Programming Microsoft Access


424


Private Sub Combine_Implicit()
strFirstName = txtFirstName
strLastName = txtLastName
txtFullName = strFirstName & “ “ & strLastName
End Sub

The second approach is to explicitly declare them with one of the following keywords: Dim,
Static, Private, or Public (or Global). The choice of keyword has a profound effect on the
variable’s scope within the application and determines where the variable can be used in the pro-
gram. (Variable scope is discussed in the “Understanding variable scope and lifetime” section, later
in this chapter.)

The syntax for explicitly declaring a variable is quite simple:

Dim VariableName As DataType

Static VariableName As DataType

Private VariableName As DataType

Public VariableName As DataType

In each case, the name of the variable and its data type are provided as part of the declaration. VBA
reserves the amount of memory required to hold the variable as soon as the declaration statement
is executed. Once a variable is declared, you can’t change its data type, although you can easily
convert the value of a variable and assign the converted value to another variable.

The following example shows the Combine_Implicit sub rewritten to use explicitly declared
variables:

Private Sub Combine_Explicit()
Dim strFirstName As String
Dim strLastName As String
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
txtFullName = strFirstName & “ “ & strLastName
End Sub

So, if there’s often very little difference between using implicit and explicit variables, why bother
declaring variables at all? The following code demonstrates the importance of using explicitly
declared variables in your applications:

Private Sub Form_Load()
Department = “Manufacturing”
Supervisor = “Joe Jones”
Title = “Senior Engineer”
‘Dozens of lines of code go here
txtDepartment = Department
txtSupervisor = Superviser
txtTitle = Title
End Sub
Free download pdf