|
Introduction to Sub-Procedures
|
|
A sub procedure is an assignment that is carried
but does not give back a result. To create a sub procedure, start by typing the Sub
keyword followed by a name (like everything else, a procedure must
have a name). The name of a procedure is always followed by parentheses. At
the end of the sub procedure, you must type End Sub. Therefore, the
primary syntax of a sub procedure is:
Sub ProcedureName()
End Sub
The name of a procedure should follow the same rules
we learned to name the variables. In addition:
- If the procedure performs an action that can be represented with a
verb, you can use that verb to name it. Here are examples: show,
display
- To make the name of a procedure stand, you should start it in
uppercase. Examples are Show, Play, Dispose, Close
- You should use explicit names that identify the purpose of the
procedure. If a procedure would be used as a result of another
procedure or a control's event, reflect it on the name of the sub
procedure. Examples would be: afterupdate, longbefore.
- If the name of a procedure is a combination of words, you should
start each word in uppercase. Examples are: AfterUpdate, SayItLoud
The section between the Sub and the End Sub
lines is referred to as the body of the procedure. Here is an example:
Sub Assign()
End Sub
The body of the
procedure is used to define what, and how, the assignment should be carried.
For example, if you need to use a variable, you can declare it and specify
the kind of variable you need. There is no restriction on the type of
variables that can be declared in a procedure. Here is an example in which
a string variable is declared in the body of a sub routine:
Sub Assign()
Dim strFullName As String
End Sub
In the same way, you can declare as many variables as
you need inside of a procedure. The actions you perform inside of a
procedure depend on what you are trying to accomplish. For example, a
procedure can simply be used to create a string. The above procedure can
be changed as follows:
Sub Assign()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
|
Practical
Learning: Introducing Procedures
|
|
- Start Microsoft Visual Basic
- To create a new application, on the main menu, click File -> New ->
Project or File -> New Project
- In the Templates list, click Console Application
- In the Name text box, type Squared
- In the Solution Name text box, type Geometry1
- Click OK
- In the Solution Explorer, under the Square node, right-click Module1.vb and click Rename
- Type Square.vb and press Enter
- To create a procedure, change the document as follows:
Public Module Square
Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
MsgBox("=-= Square Characteristics=-=" & vbCrLf & _
"Side: " & dblSide & vbCrLf & _
"Perimeter: " & dblPerimeter)
End Sub
Sub Main()
End Sub
End Module
|
- Save the document
Once you have a procedure, whether you created it or
it is part of the Visual Basic language, you can use it. Using a procedure is also referred
to as calling it. Before calling a procedure, you should first locate the
section of code in which you want to use it. To call a simple procedure,
type its name followed by parentheses in the section where you want to use
it.
Here is an example:
Module Exercise
Sub Assign()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
MsgBox(strFullName)
End Sub
Friend Sub Main()
Assign()
End Sub
End Module
Besides using the name of a
procedure to call it, you can also precede it with the Call
keyword. Here is an example:
Module Exercise
Sub Assign()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
MsgBox(strFullName)
End Sub
Friend Sub Main()
Call Assign()
End Sub
End Module
|
Practical Learning: Calling a Sub Procedure
|
|
- To call the procedure, type its name in the Main() procedure
as follows:
Module Central
Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
MsgBox("=-= Square Characteristics=-=" & vbCrLf & _
"Side: " & dblSide & vbCrLf & _
"Perimeter: " & dblPerimeter)
End Sub
Sub Main()
ProcessSquare()
End Sub
End Module
|
- Execute the application and enter the side of the square as 48.14
- Close the DOS window and return to your programming environment
|
Procedures and Access Modifiers
|
|
Like a variable, a procedure can use access
modifiers. A procedure can be made a private procedure, a friendly
procedure, or a public procedure, using the Private, the Friend,
or the Public keywords respectively:
- Private: A procedure marked as private can be called only by
members of the same module
- Friend: A friendly procedure can be called by members of the
modules of the same application
- Public: A public procedure can be called from its program and other
programs
|
Practical Learning:
Access Modifying a Procedure
|
|
- To control the access to a procedure, change the file
as follows:
Public Module Square
Private Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
MsgBox("=-= Square Characteristics =-=" & vbCrLf & _
"Side: " & dblSide & vbCrLf & _
"Perimeter: " & dblPerimeter)
End Sub
Public Sub Main()
ProcessSquare()
End Sub
End Module
|
- Execute the application and enter the side of the square as 105.15
- Close the DOS window and return to your programming environment
|
Introduction to Functions |
|
Like a sub procedure, a
function is used to perform an assignment. The main difference between a sub
procedure and
a function is that, after carrying its assignment, a function gives back a
result. We also say that a function "returns a value". To
distinguish both, there is a different syntax you use for a function.
To create a function, you use the Function keyword
followed by a name and parentheses. Unlike a sub procedure, because a
function returns a value, you must specify the type of value the
function will produce. To give this information, on the right side of the
closing parentheses, you can type the As keyword, followed by a data type. To
indicate where a function stops, type End Function. Based on this, the
minimum syntax used to create a function is:
AccessModifier(s) Function FunctionName() As DataType
End Function
As seen for a sub procedure, a function can have an
access modifier. The rules are the same as we described for a sub
procedure.
The Function keyword is required.
The name of a function follows the same rules and
suggestions we reviewed for sub procedures.
The As keyword may be required (in the next
sections, we will review the alternatives to the As DataType
expression).
The DataType factor
indicates the type of value that the function will return. If the function
will produce a word or a group of words, you can create it as String. The other data types are
also valid in the contexts we reviewed them. Here is an example:
Function GetFullName() As String
End Function
As done with the variables, you can also use a type
character as the return type of a function and omit the As DataType
expression. The type character is typed on the right side of the function
name and before the opening parenthesis. An example would be GetFullname$().
As with the variables, you must use the appropriate type character for the
function:
| Character |
The function must return |
| $ |
a String type |
| % |
a Byte, Short, Int16, or In32 |
| & |
an Int64 or a Long |
| ! |
a Single type |
| # |
a Double |
| @ |
a Long integer |
Here is an example:
Function GetFullName$()
End Function
As mentioned already, the section between the Function
and the End Function lines is the body of the function. It is used to
describe what the function does. As done on a sub procedure, one of the
actions you can perform in a function is to declare a (local) variable and
use it as you see fit. Here is an example:
Function CallMe() As String
Dim Salute As String
Salute = "You can call me Al"
End Function
|
Returning a Value From a Function
|
|
After performing an assignment in a function, to
indicate the value it returns, somewhere after the assignment and before
the End Function line, you can type the name of the function, followed by the =
sign, followed by the value the function returns. Here is an example in
which a function returns a name:
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
GetFullName = LastName & ", " & FirstName
End Function
Alternatively, instead of using
the name of the function to indicate the value it returns, you can type Return,
followed by the value or the expression that the function returns. Based
on this, the above function could also be created as follows:
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
Return LastName & ", " & FirstName
End Function
You can also use some local variables in the function
to perform an assignment and then assign their result to the name of the
function.
|
Practical Learning: Creating a Function
|
|
- To add a project to the current solution, on the main menu, click
File -> Add -> New Project
- Set the Name to Rectangular and click OK
- In the Solution Explorer, under Rectangular, right-click Module1 and
click Rename
- Type Rectangle.vb and press Enter
- To create a function, change the file as follows:
Public Module Rectangle
Private Function CalculatePerimeter() As Double
Dim dblLength As Double
Dim dblWidth As Double
dblLength = InputBox("Enter Rectangle Length: ")
dblWidth = InputBox("Enter Rectangle Width: ")
CalculatePerimeter = (dblLength + dblWidth) * 2
End Function
Public Sub Main()
End Sub
End Module
|
- Save all
As done for the sub procedure, in order to use a function in your program,
you must call it. Like a sub procedure, to call a function, you can simply type
its name in the desired section of the program. Here is an example:
Sub Main()
CallMe
End Sub
Since the primary purpose of a function is to return a value, to better
take advantage of such a value, you can assign the name of a function to a
variable in the section where you are calling the function.
Here is an example:
Module Exercise
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
Return LastName & ", " & FirstName
End Function
Friend Sub Main()
Dim FullName$
FullName = GetFullName()
MsgBox(FullName)
End Sub
End Module
Here is an example of running this program:



|
Practical Learning: Calling a Function
|
|
- To call a function, change the Rectangular.vb file as follows:
Public Module Rectangle
Private Function CalculatePerimeter() As Double
Dim dblLength As Double
Dim dblWidth As Double
dblLength = InputBox("Enter Rectangle Length: ")
dblWidth = InputBox("Enter Rectangle Width: ")
CalculatePerimeter = (dblLength + dblWidth) * 2
End Function
Public Sub Main()
Dim Perimeter As Double
Perimeter = CalculatePerimeter()
MsgBox("=-= Square Characteristics=-=" & vbCrLf & _
"Perimeter: " & Perimeter)
End Sub
End Module
|
- Execute the application
- Enter the length as 25.55 and the width as 20.05
- Close the DOS window and return to your programming environment
|
A Function and a Procedure
|
|
Depending on an author, in the Visual Basic language, the
word "procedure" includes either a sub-procedure created with the Sub
keyword, or a function created with the Function keyword. In the same
way, for the rest of our lessons, the word procedure will be used to represent
both types. Only when we want to be precise will we use the expression "a
sub-procedure" to explicitly mean the type of procedure that does not
return a value. When the word "function" is used in our lessons, it
explicitly refers to the type of procedure that returns a value.
The Visual Basic Language uses a special procedure called Main.
The Main procedure is the entry point of a program as we
have used it so far. Particularly, Main can be used as a sub
procedure or a function. So far, we have used Main only as a sub
procedure. To use Main as a function, type the Function keyword
required for each function, followed by Main(), followed by As
Integer. When declared like this, the Main function must return
an integer. The most regularly return value is 0, which indicates that the
function ended successfully. Here is an example:
Module Exercise
Friend Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
Return LastName & ", " & FirstName
End Function
Friend Function Main() As Integer
Dim FullName$
FullName = GetFullName()
MsgBox(FullName)
Return 0
End Function
End Module
|
Practical Learning:
Using the Main Function
|
|
- To use Main() as a function, change it as follows:
Module Central
Private Function CalculatePerimeter() As Double
Dim dblLength As Double
Dim dblWidth As Double
dblLength = InputBox("Enter Rectangle Length: ")
dblWidth = InputBox("Enter Rectangle Width: ")
CalculatePerimeter = (dblLength + dblWidth) * 2
End Function
Public Function Main() As Integer
Dim Perimeter As Double
Perimeter = CalculatePerimeter()
MsgBox("=-= Square Characteristics=-=" & vbCrLf & _
"Perimeter: " & Perimeter)
Return 0
End Function
End Module
|
- Execute the application
- Enter the length as 88.16 and the width as 44.14
- Close the DOS window and return to your programming environment
In the previous lesson, we saw that you could declare a
global variable outside of any procedure. When using various procedures in a
code file, one of the characteristics of a global variable is that it is
automatically accessible to other procedures:
- Private: A private global variable can be accessed by any
procedure of the same module. No procedure of another module, even of the
same program, can access it

- Friend: A friendly global variable can be accessed by any procedure
of any module of the same project. A procedures of another program cannot
access that variable

- Public: A public global variable can be accessed by any procedure
of its project and procedures of other projects

Based on this characteristic of the procedures of a module
having access to global variables of the same program, you can declare such
variables and initialize or modify them in any procedure of the same code file.
|
Practical Learning:
Using Global Variables
|
|
- To use global variables, change the document as follows:
Public Module Rectangle
Private Length As Double
Private Width As Double
Private Sub GetLength()
Length = InputBox("Enter Rectangle Length:")
End Sub
Private Sub GetWidth()
Width = InputBox("Enter Rectangle Width:")
End Sub
Private Function CalculatePerimeter() As Double
CalculatePerimeter = (Length + Width) * 2
End Function
Public Function Main() As Integer
Dim Perimeter As Double
GetLength()
GetWidth()
Perimeter = CalculatePerimeter()
MsgBox("=-= Square Characteristics=-=" & vbCrLf & _
"Length: " & vbTab & Length & vbCrLf & _
"Width: " & vbTab & Width & vbCrLf & _
"Perimeter: " & Perimeter)
Return 0
End Function
End Module
|
- Execute the application
- Enter the length as 32.08 and the with as 24.84
- Close the message box and the DOS window
|
Introduction to Arguments
|
|
So far, to use a value in a procedure, we had to
declare it. In some cases, a procedure may need an external value in order
to carry its assignment. A value that is supplied to a procedure is called
an argument.
When creating a procedure that will use an external
value, declare the argument that represents that value between the
parentheses of the procedure. For a sub procedure, the syntax you use would
be:
Sub ProcedureName(Argument)
End Sub
If you are creating a function, the syntax would be:
Function ProcedureName(Argument) As DataType
Function Sub
The argument must be declared as a normal variable,
omitting the Dim keyword. Here is an example that creates a function
that takes a string as argument:
Function CalculatePayroll(strName As String) As Double
Function Sub
A certain procedure can take more than one argument.
In this case, in the parentheses of the procedure, separate the arguments
with a comma. Here is an example of a sub procedure that takes two
arguments:
Sub EvaluateInvoice(EmplName As String, HourlySalary As Currency)
End Sub
In the body of a procedure that takes one or more
arguments, use the argument(s) as you see fit as if they were locally
declared variables. For example, you can involve them with values inside
of the procedure. You can also exclusively use the values of the arguments
to perform the assignment.
|
Calling a Procedure With Argument
|
|
To call a procedure that takes an argument, type its name and a
space, followed by a value for each argument between parentheses. The value provided for an
argument is also called a parameter. If there is more than one
argument, separate them with a comma. Here is an example:
Module Exercise
Private Function GetFullName$(strFirst As String, _
strLast As String)
Dim FName As String
FName = strFirst & " " & strLast
GetFullName = FName
End Function
Public Function Main() As Integer
Dim FirstName, LastName As String
Dim FullName As String
Dim ComputerLanguage As String = "Visual Basic"
FirstName = inputbox("Enter First Name: ")
LastName = inputbox("Enter Last Name: ")
FullName = GetFullName(FirstName, LastName)
msgbox("Hello, " & FullName)
Welcome(ComputerLanguage)
Return 0
End Function
Sub Welcome(ByVal strLanguage As String)
msgbox("Welcome to the wonderful world of " & strLanguage)
End Sub
End Module
As mentioned previously, you can also use the Call keyword to
call a procedure.
When you call a procedure that
takes more than one argument, you must provide the values of the arguments in
the exact order they are listed inside of the parentheses of the function.
Fortunately, you do not have to. If you know the names of the arguments, you can
type them in any order and provide a value for each. To do that, on the right
side of each argument, type the := operator followed by the desired value for
the argument. Here is an example:
Public Module Exercise
Private Function GetFullName$(MI As String, _
LastName As String, _
FirstName As String)
GetFullName = FirstName & " " & MI & " " & LastName
End Function
Public Function Main() As Integer
Dim FullName As String
Dim ComputerLanguage As String = "VBasic"
FullName = GetFullName(LastName:="Roberts", FirstName:="Alan", MI:="R.")
MsgBox("Hello " & FullName)
Call Welcome(ComputerLanguage)
Return 0
End Function
Private Sub Welcome(ByVal strLanguage As String)
MsgBox("Welcome to the wonderful world of " & strLanguage)
End Sub
End Module
|
Practical Learning: Passing Arguments to a Procedure
|
|
- To pass arguments to a function, change the file as follows (when
you type the argument, Microsoft Visual Studio, actually the Visual
Basic language parser, will add the ByVal keywords; in the next
sections, we will learn what that keyword means; for now, keep but
ignore it):
Public Module Rectangle
Private Function GetValue(TypeOfValue As String) As Double
Dim Value As Double
Value = InputBox("Enter the " & TypeOfValue & ":")
Return Value
End Function
Private Function CalculatePerimeter(Length As Double, _
Width As Double) As Double
CalculatePerimeter = (Length + Width) * 2
End Function
Public Function Main() As Integer
Dim L As Double, W As Double
Dim Perimeter As Double
L = GetValue("Length")
W = GetValue("Width")
Perimeter = CalculatePerimeter(L, W)
MsgBox("=-= Square Characteristics=-=" & vbCrLf & _
"Length: " & L & vbCrLf & _
"Width: " & W & vbCrLf & _
"Perimeter: " & Perimeter)
Return 0
End Function
End Module
|
- Execute the application
- Enter the length as 44.14 and the with as 30.76
- Close the message box and the DOS window
|
Techniques of Passing Arguments |
|
|
Passing Arguments (By Value)
|
|
When calling a procedure that takes an argument, we
were supplying a value for that argument. When this is done, the procedure
that is called makes a copy of the value of the argument and makes that
copy available to the calling procedure. That way, the argument itself is not
accessed. This is referred to as passing an argument by value. This can be
reinforced by typing the ByVal keyword on the left side of the
argument. Here is an example:
Private Sub Welcome(ByVal strLanguage As String)
MsgBox("Welcome to the wonderful world of " & strLanguage)
End Sub
If you create a procedure that takes an argument by
value and you have used the ByVal keyword on the argument, when
calling the procedure, you do not need to use the ByVal keyword;
just the name of the argument is enough, as done in the examples on
arguments so far. Here is an example:
Public Module Exercise
Public Function Main() As Integer
Dim ComputerLanguage As String = "Visual Basic"
Welcome(ComputerLanguage)
Return 0
End Function
Private Sub Welcome(ByVal strLanguage As String)
MsgBox("Welcome to the wonderful world of " & strLanguage)
End Sub
End Module
This would produce:

|
Passing Arguments By Reference
|
|
An alternative to passing arguments as done so far is to pass the
address of the argument to the called procedure. When this is done, the
called procedure does not receive a simple copy of the value of the
argument: the argument is accessed by its address. That is, at its memory
address. With this technique, any action carried on the argument will be
kept. If the value of the argument is modified, the argument
would now have the new value, dismissing or losing the original value it
had. This technique is referred to as passing an argument by reference.
Consider the following program:
Public Module Exercise
Private Function Addition#(ByVal Value1 As Double, ByVal Value2 As Double)
Value1 = InputBox("Enter First Number: ")
Value2 = InputBox("Enter Second Number: ")
Addition = Value1 + Value2
End Function
Public Function Main() As Integer
Dim Result As String
Dim Number1, Number2 As Double
Result = Addition(Number1, Number2)
MsgBox(Number1 & " + " & Number2 & " = " & Result)
Return 0
End Function
End Module
Here is an example of running the program:



Notice that, although the values of the arguments were
changed in the Addition() procedure, at the end of the procedure, they lose
the value they got in the function. If you want a procedure to change the
value of an argument, you can pass the argument by reference.
To pass an argument by reference, on its left, type
the ByRef keyword. This is done only when creating the procedure.
When the called procedure finishes with the argument, the argument would
keep whatever modification was made on its value. Now consider the
same program as above but with arguments passed by reference:
Public Module Exercise
Private Function Addition#(ByRef Value1 As Double, ByRef Value2 As Double)
Value1 = InputBox("Enter First Number: ")
Value2 = InputBox("Enter Second Number: ")
Addition = Value1 + Value2
End Function
Public Function Main() As Integer
Dim Result As String
Dim Number1, Number2 As Double
Result = Addition(Number1, Number2)
MsgBox(Number1 & " + " & Number2 & " = " & Result)
Return 0
End Function
End Module
Here is an example of running the program:
Using
this technique, you can pass as many arguments by reference and as many
arguments by value as you want. As you may guess already, this technique is also
used to make a sub procedure return a value, which a regular sub routine
cannot do. Furthermore, passing arguments by reference allows a procedure
to return as many values as possible while a regular function can return
only one value.
|
Practical Learning: Passing Arguments by Reference
|
|
- To pass an argument by reference, change the file as
follows:
Public Module Rectangle
Private Sub GetValues(ByRef Length As Double, ByRef Width As Double)
Length = InputBox("Enter the length:")
Width = InputBox("Enter the width:")
End Sub
Private Function CalculatePerimeter(ByVal Length As Double, _
ByVal Width As Double) As Double
CalculatePerimeter = (Length + Width) * 2
End Function
Private Function CalculateArea(ByVal Length As Double, _
ByVal Width As Double) As Double
CalculateArea = Length * Width
End Function
Private Sub ShowCharacteristics(ByVal Length As Double, _
ByVal Width As Double)
Dim Result As String
Result = "=-= Rectangle Characteristics =-=" & vbCrLf & _
"Length: " & vbTab & vbTab & CStr(Length) & vbCrLf & _
"Width: " & vbTab & vbTab & CStr(Width) & vbCrLf & _
"Perimeter: " & vbTab & _
CalculatePerimeter(Length, Width) & vbCrLf & _
"Area: " & vbTab & vbTab & _
CalculateArea(Length, Width)
MsgBox(Result)
End Sub
Public Function Main() As Integer
Dim L As Double, W As Double
GetValues(L, W)
ShowCharacteristics(L, W)
Return 0
End Function
End Module
|
- Execute the application
- Enter the length as 24.55 and the width as 22.85

- Close the message box and the DOS window
|