Learn Access 2003 VBA with The Smart Method
94
www.LearnAccessVBA.com
Lesson 5-3: Understand
arguments
An argument is a value that may be passed to a sub or function.
Arguments usually modify the behavior of the sub or function in some
way.
In this lesson we’ll refine our ThankYouMessage sub even further by
adding two arguments to it.
1
Open the VBACode.mdb database (if not already open) and
open frmTest in Design View.
2
Open the VBA Editor.
Right click on the Command Button and select Build Event from
the shortcut menu. The code for the Command Button’s Click
event is displayed in the code editor.
3
Add an argument to the ThankYouMessage sub.
Edit the code so that it is the same as the following:
Private Sub cmdPressMe_Click()
Dim strMessage As String
strMessage = "Thank you for pressing me"
Call ThankYouMessage(strMessage)
End Sub
Sub ThankYouMessage(strMessage As String)
Beep
Call MsgBox(strMessage)
End Sub
Consider what is now happening. The strMessage variable is being
passed as an argument from the cmdPressMe_Click() event
handler to the ThankYouMessage sub.
4
Add a second argument to the ThankYouMessage sub to
allow a title to be specified.
Edit the code so that it is the same as the following:
Private Sub cmdPressMe_Click()
Dim strMessage As String
Dim strTitle As String
strMessage = "Thank you for pressing me"
strTitle = "Thank You"
Call ThankYouMessage(strMessage, strTitle)
End Sub
Sub ThankYouMessage(strMessage As String, _
strTitle As String)
Beep
Call MsgBox(strMessage,,strTitle)
Session5a
note
Some programmers prefer the
term Parameter instead of
Argument. Both are correct.
pg_0002
Session Five: Professional Grade VBA
© 2007 The Smart Method Ltd
95
End Sub
Passing the arguments is quite straightforward. There are simply
two arguments now instead of one.
Note that the MsgBox function has two commas between the
strMessage and strTitle arguments rather than one. This is because
the MsgBox function accepts the Title as its third argument, the
second argument is optional.
Note also the continuation character (an underscore) after the first
argument declaration for the ThankYouMessage sub.
Use continuation characters to break up long lines of code so that
they can be viewed within the code editor window without having
to use the scrollbars.
5
Test the command button.
Switch to Form View. When you click the command button you
should still hear a beep and see the message and title displayed in
a dialog box.
This proves that both your arguments are being passed correctly.