Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 10 Creating Modules and Procedures 263


Sub BirthdayGreeting (ByVal Person As String)
Dim Msg As String
If Person <> "" Then
Msg = "Happy birthday " & Person & "!"
Else
Msg = "Name not specified."
End If
MsgBox(Msg, , "Best Wishes")
End Sub

The BirthdayGreeting procedure receives the name to be greeted by using the Person
argument, a string variable received by value during the procedure call. If the value of
Person isn’t empty, or null, the specified name is used to build a message string that will
be displayed with a MsgBox function. If the argument is null, the procedure displays the
message “Name not specified .”

Calling a Sub Procedure


To call a Sub procedure in a program, you specify the name of the procedure, and then list
the arguments required by the Sub procedure. For example, to call the BirthdayGreeting
procedure, you could type the following statement:

BirthdayGreeting("Robert")

In this example, the BirthdayGreeting procedure would insert the name “Robert” into
a message string, and the routine would display the following message box:

The space-saving advantages of a procedure become clear when you call the procedure
many times using a variable, as shown in the example below:

Dim NewName As String
Do
NewName = InputBox("Enter a name for greeting.", "Birthday List")
BirthdayGreeting(NewName)
Loop Until NewName = ""

Here the user can enter as many names for birthday greetings as he or she likes. The next
exercise gives you a chance to practice using a Sub procedure to handle another type of
input in a program.
Free download pdf