Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

262 Part II Programming Fundamentals


Writing Sub Procedures


A Sub procedure is similar to a Function procedure, except that a Sub procedure doesn’t
return a value associated with its name. Sub procedures are typically used to get input
from the user, display or print information, or manipulate several properties associated with
a condition. Sub procedures can also be used to process and update variables received in
an argument list during a procedure call and pass back one or more of these values to the
calling program.

Sub Procedure Syntax


The basic syntax for a Sub procedure is:

Sub ProcedureName([arguments])
procedure statements
End Sub

The following syntax items are important:

n ProcedureName is the name of the Sub procedure you’re creating.
n arguments is a list of optional arguments (separated by commas if there’s more than
one) to be used in the Sub procedure. Each argument should also be declared as
a specific type. (Visual Studio adds the ByVal keyword by default to each argument,
indicating that a copy of the data is passed to the function through this argument but
that any changes to the arguments won’t be returned to the calling routine .)
n procedure statements is a block of statements that accomplishes the work of the
procedure.
In the Sub procedure call, the number and type of arguments sent to the procedure must
match the number and type of arguments in the Sub procedure declaration, and the entire
group must be enclosed in parentheses. If variables passed to a Sub procedure are modified
during the procedure, the updated variables aren’t passed back to the program unless the
procedure defined the arguments by using the ByRef keyword. Sub procedures declared in
a module are public by default, so they can be called by any event procedure in a project.

Important All calls to a Sub procedure must include parentheses after the procedure
name. A set of empty parentheses is required even if no arguments are being passed to the
procedure.

For example, the following Sub procedure receives a string argument representing a person’s
name and uses a text box to wish that person happy birthday. If this Sub procedure is
declared in a module, it can be called from any event procedure in the program.
Free download pdf