Sie sind auf Seite 1von 5

Lesson XIV.

Modules, Event Procedures, Sub Procedures, &


Function Procedures

Objectives
To understand how to construct programs modularly from procedures and functions
To be able to create new procedures and functions
To understand the mechanisms used to pass information between procedures and
functions
To understand the Exit Sub and Exit Function Statement
To understand how the visibility of identifiers is limited to specific regions of programs
To be able to create and use code modules

Notes
A Visual Basic project is made up of modules such as Form Modules. A Form Module consists of
pieces of codes called Procedures. In this lesson, we will discuss the four types of procedures,
namely: Visual Basic Procedures, Sub Procedures, Event Procedure, and Function
Procedures.
Type
Visual Basic
Procedures
Sub Procedures
Event Procedures
Function
Procedures

Description
Procedures provided by Microsoft to perform common
tasks (e.g. Format(), Str(), Val())
A block of statements that perform a particular task.
They may receive data from the calling Procedure.
Similar to Sub Procedures but the Procedure is
executed as a response to an event (e.g. keypress)
Similar to Sub Procedures but return a value to the
calling Procedure

Sub and Function Procedures are invoked by another Procedure through a Procedure call made
by a Caller Procedure. The call specifies the Procedure name and provides information (if needed;
as arguments) that the callee needs to do its job.
IN FOCUS: SUB PROCEDURES
The syntax of Sub Procedures is as follows:
Private Sub <procedure_name>( )
One or more VB Statement
End Sub
Private Sub <Procedure_Name>(<arguments>)
One or more VB statements
End Sub
Examples are as follows:
Example of a Sub Procedure
Private Sub ComputeSum( )
x=y+z
lblSum.Caption = Sum is & Str(x)
End Sub
IN FOCUS: FUNCTION PROCEDURES
The syntax of Function Procedures is as follows:
Private Sub <procedure_name>( ) As <data_type>
One or more VB Statement
<procedure_name> = <expression>
End Sub
Private Sub <Procedure_Name>(<arguments>) As <return_value_data_type>
One or more VB statements
<procedure_name> = <expression>
End Sub

Examples are as follows:


Examples of Function Procedures
Private Sub GetNameLength( ) As String
GetNameLength = Len(lblName.Caption)
End Sub
Private Sub ComputeProduct(y As Integer, z As Integer) As Integer
ComputeProduct = y * z
End Sub

c=
ComputeSum(a,b)

Caller

Private Sub ComputeSum(x As Integer, y As


Integer)
ComputeSum = x + y
End Sub
Callee

<return_value_data_type> specifies the data type of the return value. Recall that all Function
Procedures must return a value to the calling procedure. How do we return a result? You assign the
result to a variable whose name is the same with the Function Procedure name. In the example
above, we return the result through ComputeSum variable. Note: <return_value_data_type> is
optional. If you dont specify it, the return value will have a Variant data type.
Another thing that you should take note in using Function Procedures are the arguments. Function
Procedures may have arguments, and in this case, the calling procedure must pass the same
number of arguments. The order of the arguments to be passed to the Function must correspond to
the order of arguments in the Function header with respect to the data types. This means that if the
Function requires 2 values, one String and one Boolean, the calling procedure must pass one String
and one Boolean in this order. We will learn more about this parameter passing process in the
following section.
IN FOCUS: PARAMETER PASSING
Parameter Passing is a process by which the caller (or the calling procedure) passes (or transmits)
the parameter (or actual arguments) to a called procedure and binds the actual arguments to the
formal parameters. Procedures communicate with each other through this process. A particular
procedure might have this particular capability and for other procedures to take advantage of its
services, it needs to know the procedures name and the data it needs, if any.
There are two parameter passing conventions supported by Visual Basic: Pass-by-Value and Passby-Reference.
Call-by-Value
In Call-by-Value, a copy of the arguments value is passed, thus, the called procedure do not
manipulate the callers data because it is the copy that it received. There is one known
disadvantage: if we have numerous arguments with large sizes, we incur an overhead of copying
large amounts of data. This may cause our application to run slow.
You call a procedure by Call-by-Value through the Call statement as we have discussed, but you
should tell the procedures to be called to receive the just value of the passed arguments:
Precede the corresponding parameter variable in the procedure definition with keyword
ByVal
e.g. Function X (ByVal x as Boolean) As Integer
Enclose the argument in parentheses ( )
e.g. Function X ( (x) as Boolean) As Integer
Call-by-Reference
Call-by-Reference is the default method. The caller gives the called procedure the ability to directly
access the callers data and to modify the data if the called procedure chooses. This is
accomplished by passing the reference (the addresses of the variables) to the arguments. Because
of this, duplication is avoided but it has weak security.

Since this is the default passing convention, you need do tell the called procedure to receive the
reference instead of the value. There is one explicit way of doing this: precede the corresponding
parameter variable in the procedure definition with keyword ByRef as in the following example:
Function Sample (ByRef x As Boolean) As Integer
IN FOCUS: OPTIONAL ARGUMENTS
Visual Basic allows programmers to create procedures that take one or more optional arguments
the caller has the option of passing that particular argument.
In the following example, variable z is optional as denoted by the keyword Optional. This means
that the calling procedure may or may not pass an argument to z.
Private Sub AAA(y as Boolean, Optional z as Long)
.
End Sub
----Call AAA()
Invalid because the first argument is mandatory
Call AAA(True)
Valid
Call AAA(True, 10)
Valid
IN FOCUS: EXIT SUB AND EXIT FUNCTION
Exit Sub and Exit Function alter the flow of control. They cause an immediate exit from a Sub
Procedure and Function Procedure, respectively. When this happens, control is then returned to the
caller and the next statement in sequence after the call is executed.
In the following example, Exit Sub terminates PrintNumbers when num<0.
Private Sub PrintNumbers (num as Integer)
If num>=0 Then
.
Else
Exit Sub
End If
End Sub
IN FOCUS: STATIC PROCEDURES AND VARIABLES
Variables declared within procedures, also known as local variables, are allocated space when the
procedure is active (when it is currently being executed) and deallocated space when the
procedure terminates. Programming Languages are designed this way to save space
outside of the procedures, local variables are often not needed, and thus we can just do
away with these. When a variable is deallocated space, the datum stored in it is erased.
There are cases when you want to maintain a variable all throughout the programs execution time.
You can do this either by declaring the variable outside of Procedures or by making them Static.
Static variables are allocated and initialized once the Form is loaded. You declare a Static variable
through preceding a variable declaration with the keyword Static. For example,
Static Dim x as Integer
If you want to make all local variables Static, you can just create a Static Procedure.
Private Static Sub MyProcedure() Static Procedure
Dim x, y, z As Integer

End Sub
In the above procedure, x, y, and z are Static variables regardless of whether or not variables are
explicitly declared Static.

Lesson in Action
Lets create a simple application that determines the smallest value among 3 numbers entered in 3
TextBoxes. What we need is an interface and a Function that will determine the smallest value.

Write the following procedures.


Private Sub cmdGetMin_Click()
Dim v1 As Integer, v2 As Integer, v3 As Integer
v1 = val(txtNum1.Text)
v2 = val(txtNum2.Text)
v3 = val(txtNum3.Text)
Call GetMinimum Function and pass the v1, v2, and v3
smallest = GetMinimum(v1, v2, v3)
lblOutput.Caption = "Smallest value is " & Str(smallest)
End Sub
Private Function GetMinimum(min_val As Integer, y As Integer, z As Integer) As Integer
Assume that the first number is the smallest. We just then compare this to the other 2
numbers.
If (y < min_val) Then
min_val = y
End If
If (z < min_val) Then
min_val = z
End If
GetMinimum = min_val
End Function
Save your work as Less14.vbp.

On your Own
1. Write a Function Procedure that accepts an Integer and returns its square.
2. Write a Function Procedure named IsEven that accepts an Integer and returns True if this
Integer is even, False if it is odd.
3. Write the procedure header for the following:
a. RectArea takes two Double arguments, length and height, and returns a Double result.
b. OutputResult does not receive any arguments and does not return a value
c. ChangeString takes 1 String and 1 Integer argument, and returns a String.

Das könnte Ihnen auch gefallen