Você está na página 1de 14

DEC5062 VISUAL BASIC PROGRAMMING PTSB

LAB 3 : PROCEDURE

TITLE : SUB PROCEDURE AND FUNCTION PROCEDURE


________________________________________________________________
___
LEARNING OUTCOME

By the end of this lab, students should be able to:

1) Apply a new sub procedure, a new function procedure and argument to


procedure.

THEORY AND CONCEPTS

1.0 DEFINITION
A unit of code that performs a specific task and can be called from other locations
of the program. Visual Basic uses several types of procedures:
Sub procedures perform actions but do not return a value to the calling
code.
Event-handling procedures are Sub procedures that execute in response
to an event raised by user action or by an occurrence in a program.
Function procedures return a value to the calling code. They can perform
other actions before returning.

2.0 SUB PROCEDURE


Sub Procedure is a procedure that performs action. It has its own name
Programmer can use the Call statement to call the procedure. A sub procedure
can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed

Example :

Private Sub ProcedureName()

Statement Block

End Sub
A statement to call the Sub Procedure :

Call ProcedureName()

3.0 FUNCTION PROCEDURE

Prepared by: Intan Shafinaz Binti Abd. Razak Page 1


DEC5062 VISUAL BASIC PROGRAMMING PTSB

Function Procedure is defined by user and almost same like Sub Procedure.
The way of using the function procedure is like the way of using the existing
functions.

Functions are like sub procedures, except they return a value to the calling
procedure. They are especially useful for taking one or more pieces of data,
called arguments and performing some tasks with them. Then the functions
returns a value that indicates the results of the tasks complete within the function.

Example :

Private Function FunctionName(Var1 As DataType, Var2 As DataType) As DataType

FunctionName = expression

End Function

4.0 PASSING ARGUMENTS


Arguments may be passed to a called procedure by value or by reference
a) ByRef- the memory address of the original value is passed to the
procedure, allowing the procedure to change the original value.
b) ByVal- only a copy of the original value is passed; the called procedure
cannot alter the original value

5.0 PROCEDURE IN VISUAL BASIC

Visual Basic offers different types of procedures to execute small sections of coding in
applications. The various procedures are elucidated in details in this section. Visual Basic
programs can be broken into smaller logical components called Procedures. Procedures are
useful for condensing repeated operations such as the frequently used calculations, text and
control manipulation etc. The benefits of using procedures in programming are:

It is easier to debug a program a program with procedures, which breaks a program into
discrete logical limits.

Procedures used in one program can act as building blocks for other programs with slight
modifications.

A Procedure can be Sub, Function or Property Procedure.

i. Sub Procedures

A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure
is as follows:

Prepared by: Intan Shafinaz Binti Abd. Razak Page 2


DEC5062 VISUAL BASIC PROGRAMMING PTSB

[Private | Public] [Static] Sub Procedurename [( arglist)]


[ statements]
End Sub

arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. There are two types of Sub Procedures namely general procedures and event
procedures.

ii. Event Procedures

An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.

Private Sub Form_Load()


....statement block..
End Sub

Event Procedures acquire the declarations as Private by default.

iii. General Procedures

A general procedure is declared when several event procedures perform the same actions. It is
a good programming practice to write common statements in a separate procedure (general
procedure) and then call them in the event procedure.

In order to add General procedure:

The Code window is opened for the module to which the procedure is to be
added.
The Add Procedure option is chosen from the Tools menu, which opens an Add
Procedure dialog box as shown in the figure given below.
The name of the procedure is typed in the Name textbox
Under Type, Sub is selected to create a Sub procedure, Function to create a
Function procedure or Property to create a Property procedure.
Under Scope, Public is selected to create a procedure that can be invoked
outside the module, or Private to create a procedure that can be invoked only from
within the module.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 3


DEC5062 VISUAL BASIC PROGRAMMING PTSB

We can also create a new procedure in the current module by typing Sub ProcedureName,
Function ProcedureName, or Property ProcedureName in the Code window. A Function
procedure returns a value and a Sub Procedure does not return a value.

iv. Function Procedures

Functions are like sub procedures, except they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and performing
some tasks with them. Then the functions returns a value that indicates the results of the tasks
complete within the function.

The following function procedure calculates the third side or hypotenuse of a right triangle,
where A and B are the other two sides. It takes two arguments A and B (of data type Double)
and finally returns the results.

Function Hypotenuse (A As Double, B As Double) As Double


Hypotenuse = sqr (A^2 + B^2)
End Function

The above function procedure is written in the general declarations section of the Code
window. A function can also be written by selecting the Add Procedure dialog box from the
Tools menu and by choosing the required scope and type.

v. Property Procedures

A property procedure is used to create and manipulate custom properties. It is used to create
read only properties for Forms, Standard modules and Class modules.Visual Basic provides
three kind of property procedures-Property Let procedure that sets the value of a property,
Property Get procedure that returns the value of a property, and Property Set procedure that
sets the references to an object.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 4


DEC5062 VISUAL BASIC PROGRAMMING PTSB

Exercise 1:

Subprocedures with no arguments

i) Build a form as shown below:

ii) Double-click on the command button and to key-in the procedure in the space
between Private Sub............. End Sub.

iii) Get the output

iv) With your Code Window open, select Tools-Add Procedure from the Visual Basic
MenuBar, and the following dialog box will appear.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 5


DEC5062 VISUAL BASIC PROGRAMMING PTSB

v) Let's call the Procedure Calculate (use Mixed case in naming your procedures), and
leave the Type as 'Sub' for Subprocedure, and the Scope as Public. When you click
on the OK button, Visual Basic will create a Subprocedure for you in the form
called 'Calculate()', and you'll then see it in the Code Window.

vi) What we need to do at this point is take the code out of the Click Event Procedure
of the command button, and place it in the 'Calculate' Subprocedure. We can do
that by selecting the code in the click event procedure, and 'cutting and pasting' it
into the Subprocedure. This is the way the Subprocedure should read after we have
done that.
vii) Now we need to add a single line of code to the click event procedure of the
command button to call the Subprocedure. There are two ways to call the
Subprocedure---with the Call Statement or without. I prefer to use the 'Call'
statement because it alerts me to the fact that 'Calculate' is a procedure of my
own.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 6


DEC5062 VISUAL BASIC PROGRAMMING PTSB

Run the program and get the output.

Exercise 2:

Subprocedures with one or more arguments

i) Use the Exercise 1 form, modify the source code as shown below:

ii) Run the program and get the output

Exercise 3:

Subprocedures with one or more arguments

i) Use the Exercise 2 form, modify the source code as shown below:

Prepared by: Intan Shafinaz Binti Abd. Razak Page 7


DEC5062 VISUAL BASIC PROGRAMMING PTSB

ii) Change call calculate() to

a. Call Calculate(22, 11, "+")


b. Call Calculate(22, 11, "-")
c. Call Calculate(22, 11, "x")
d. Call Calculate(22, 11, "/")

iii) Run the program and explain the outputs.

Exercise 4

To create an Optional argument, all you need to do is precede the argument name in the
Procedure heading with the word 'Optional'. Optional arguments must appear last in the
Procedure header---in other words, we can't declare an Optional argument, and then
follow it up with a mandatory one. You can have as many optional arguments as you
need, but they must be declared after all of the mandatory arguments have been
declared.

i) Use the Exercise 2 form, modify the source code as shown below:

Prepared by: Intan Shafinaz Binti Abd. Razak Page 8


DEC5062 VISUAL BASIC PROGRAMMING PTSB

ii) Run the output and it will be like this:

Account what your code should do if the optional arguments are not supplied. How can we
check for a non-supplied Optional argument? To do that, we'll need to make a slight change in
our code, and there are two ways of doing that.
First, we can check to see if the Op argument is a empty string. If it is, we can then just assign
the plus sign to it like so...

If Op = " " then Op = " * "

iii) Modidy the Subprocedure as shown below.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 9


DEC5062 VISUAL BASIC PROGRAMMING PTSB

iv) Now if we run the program, and pass the Subprocedure just the two required
arguments, the Calculate Subprocedure is smart enough to presume addition, as we get
this result.

Exercise 5.

Function procedures

The second way is to use the Visual Basic function IsMissing, which was designed to do exactly
what we did ourselves a minute ago in code. One quirk of the IsMissing function, however, is
that it only works properly if the Optional Argument is declared as a Variant.

That means we need to change the Optional variable declaration of 'Op' to a Variant, in
addition to using the IsMissing function in our code.

i) Modify the source code as shown on next page:

Prepared by: Intan Shafinaz Binti Abd. Razak Page 10


DEC5062 VISUAL BASIC PROGRAMMING PTSB

ii) Run the program and get the output. (Question: What is Variant?)

iii) Since 'Calculate' is now a Function, we need to handle its return value. Use the return
value in an expression; modify the source code as below:

iv) Run the program and get the output.

Exercise 6

Function procedures

i) Create a program to calculate triangle area using value of height and base.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 11


DEC5062 VISUAL BASIC PROGRAMMING PTSB

ii) Use function procedure as below:

Private Function TriangleArea(A As Integer, B As Integer) As Single


TriangleArea = 1 / 2 * A * B
End Function

iii) Then set sub procedure as below:

Private Sub cmdCalculate_Click()


Dim Base As Integer
Dim Height As Integer
Dim Area As Integer

Base = Val(txtBase.Text)
Height = Val(txtHeight.Text)
Area = TriangleArea(Base, Height)
lblDisplay.Caption = "Triangle Area : " & Area & " cm squared"
End Sub

THINK! THINK! THINK!


Build one (1) standalone application programmes that:

i. By using Procedures AND Function Procedures, create a program that can calculate the
perimeter and area of a circle.

Prepared by: Intan Shafinaz Binti Abd. Razak Page 12


DEC5062 VISUAL BASIC PROGRAMMING PTSB

ii. The output as shown below (the output will be shown on MsgBox):

iii. The formula for finding the perimeter and area of circle as shown below:

0 1 2 3 4 5 Remarks

Prepared by: Intan Shafinaz Binti Abd. Razak Page 13


DEC5062 VISUAL BASIC PROGRAMMING PTSB

THINK! THINK! THINK!


Can solve the given tasks within a stipulated time CLO3
frame. (time management)
The application runs without error (ie. It won't CLO3
crash)
Able to use identify the suitable components (lbl, CLO3
txt,cmd,cmb etc.) in the project
Able to use proper naming conventions for CLO3
variables and objects.
Able to code the project to fulfill the CLO3
requirements outlined in the assignment.
Use of procedure, meet the objectives. CLO3

TOTAL:

Rubric for Laboratory

0 represents completely false


1 represents just barely true
2 represents somewhat true but mostly untrue
3 represents about half right
4 represents mostly true
5 represents completely true

References:

http://www.johnsmiley.com/cis18/Smiley027.pdf
http://www.functionx.com/vb6/Lesson08.htm
http://www.vb6.us/tutorials/understanding-subroutines-and-functions-vb

Prepared by: Intan Shafinaz Binti Abd. Razak Page 14

Você também pode gostar