Learn Access 2003 VBA with The Smart Method
Lesson 4-4: Understand
What are variables.
A variable is a container that is able to store data of any type in memory.
Every variable has a data type. For example a variable may be a number,
text or a date.
Suppose we have two variables called strFirstName and strLastName.
Look at the following VBA code:
strFirstName = “Freddie"
strLastName = “Mercury"
strFullName = strFirstName & “ " & strLastName
The strFullName variable now contains the text Freddie Mercury. Note the
concatenation operator (&) used to append a space (
“ "
) onto the text
Freddie and the text Mercury after the space.
If it is not already open, open the VBACode.mdb database.
Open the frmTest form in Design View.
Open the VBA Editor.
When the form is in Design View you will notice a Code Button
on the top toolbar. Clicking this button will take you straight
to the Code Editor and is quicker than right-clicking the command
button and selecting Build Event from the shortcut menu.
Add the following code to the ThankYouMessage sub
strMessage = “Thank you for pressing me."
Replace the message text in the MsgBox function call with
your new variable.
Because the variable strMessage contains the message text we can
now use the variable in place of the text originally entered:
Call MsgBox( “Thank you for pressing me" )
Call MsgBox( strMessage)
Your code should now look like this:
Private Sub cmdPressMe_Click()
Call ThankYouMessage
End Sub
Sub ThankYouMessage()
strMessage = "Thank you for pressing me"
Call MsgBox(strMessage)
End Sub
Why the strange
variable name.
You may have thought that we
would call a variable that will
store a First Name simply
FirstName rather than
While VBA wouldn’t complain
about a variable named
FirstName we use the prefix str
in order to show that the
variable contains string (text)
information rather than, for
example, a date or a number.
You’ll learn more about the
reason why this is a good idea
when we cover data types more
thoroughly in a later lesson.
Variable naming conventions
are all documented in Appendix
A: The Rules.
Session Four: An Introduction To VBA
© 2007 The Smart Method Ltd
Test the command button.
Switch to Form view. When you click the command button you
should still hear a beep and see the message displayed in a dialog
box proving that your new variable is working properly.