VB Topic 7 Functions and Subprograms
VB Topic 7 Functions and Subprograms
0 SUB-PROGRAMS
Specific Objectives
By the end of this topic, the trainee should be able to:
1. Describe sub-programs
2. Describe various types of subprograms
3. Describe the scope of variables
CONTENT
Description of Sub-programs
Types of Sub-programs
Scope of variables
Creating Procedures
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.
Event procedures
VB automatically calls event procedures in response to keyboard, mouse, or system actions.
For example, command buttons have click event procedure. The code we place in a Click
event procedure is executed when the user clicks a command button.
Each control has fixed set of event procedures. The event procedures for each control are
listed in a drop-down list box in the code window.
Example
General Procedures
General Procedures are Sub or Function procedures that are created to perform specific
tasks. To execute a general procedure, we must explicitly invoke it.
1
To create a general procedure, we open a code window and click Add procedure on the
Tools menu. We can also create a new procedure by typing the procedure heading Sub,
followed by our procedure name, on a blank line in a code window.
If you have duplicate code in several event procedures, we can place the code in a general
procedure, and then call the general procedure from the event procedures.
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:
arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. To call a Sub, you use the Call statement. The examples below shows how the
Call statement is used.
Example2:
Use of procedure with Parameters both ByVal and ByRef
Type the following module in the General declaration area
2
'Note p1 and p2 are Value Parameters and M2 is Reference Parameter
m2 = p1 / p2
End Sub
Example 3:
ByRef: When variables are passed by reference, only the memory addresses of the variables are
passed. This means that the values passed can be modified by the subroutine and would have the
3
new value after the subroutine exits and returns control to the calling program. A variable that is
expected to contain a "return" value or output value must be passed by reference.
ByVal: When variables are passed by value, a copy of the variable is passed. This means that
even if the values passed are modified by the subroutine, those modified values remain local to
that subroutine. When the subroutine exits and returns control to the calling program, the
variables that were passed by value retain the value they originally had before the call.
Appropriate variables to pass by value would be "input" values to the subroutine. "Input" values
to the subroutine can be passed either by reference or by value; it would be "proper" to pass them
by value. As long as the subroutine does not modify the input variables, there is no "harm" in
passing them by reference.
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 return a value that indicates the results of the tasks complete
within the function.
They are two types of function, the built-in functions (or internal functions) and the functions
created by the programmers (user-defined functions).
Built-in Functions
There are two very basic but useful internal functions, i.e. the MsgBox( ) and InputBox ( )
functions.
MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a
command button before he /she can continues. This message box format is as follows:
The first argument, Prompt, will display the message in the message box.
The Style Value will determine what type of command buttons appear on the message box, The
Title argument will display the title of the message board.
4
Style Values
Style Value Named Constant Buttons Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constant in place of integers for the second argument to make the programs
more readable. In fact, VB6 will automatically shows up a list of names constant where you can
select one of them.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values
are determined by the type of buttons being clicked by the users. It has to be declared as Integer
data type in the procedure or in the general declaration section. Table below shows the values,
the corresponding named constant and buttons.
Example
i. The Interface:
5
ii. The procedure for the test button:
When a user click on the test button, the image like the one shown below will appear. As the user
click on the OK button, the message "Testing successful" will be displayed and when he/she
clicks on the Cancel button, the message "Testing fail" will be displayed.
To make the message box looks more sophisticated, you can add an icon besides the message.
There are four types of icons available in VB as shown as shown in table below
ICONS ALLOWED IN VB
Value Named Constant Icon
16 vbCritical
32 vbQuestion
6
48 vbExclamation
64 vbInformation
Example
End Sub
myMessage is a variant data type but typically it is declared as string, which accept the
message input by the users. The arguments are explained as follows:
Prompt - The message displayed normally as a question asked.
Title - The title of the Input Box.
default-text - The default text that appears in the input field where users can use it as his
intended input or he may change to the message he wish to key in.
x-position and y-position - the position or the coordinate of the input box.
Example
7
i. The Interface
Mathematical Functions
The mathematical functions are very useful and important in programming because very often
we need to deal with mathematical concepts in programming such as chance and probability,
variables, mathematical logics, calculations, coordinates, time intervals and etc. The common
mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs, Exp, Log, Sin, Cos, Tan , Atn, Fix
and Round.
8
Rnd is very useful when we deal with the concept of chance and probability. The Rnd function
returns a random value between 0 and 1. When you run the program, you will get an output of 10
random numbers between 0 and 1. Randomize Timer is a vital statement here as it will
randomize the process.
Example
Random numbers in its original form are not very useful in programming until we convert them
to integers. For example, if we need to obtain a random output of 6 random integers ranging
from 1 to 6, which make the program behave as a virtual die, we need to convert the random
numbers using the format Int(Rnd*6)+1. Let’s study the following example:
In this example, Int(Rnd*6) will generate a random integer between 0 and 5 because the function
Int truncates the decimal part of the random number and returns an integer. After adding 1, you
will get a random number between 1 and 6 every time you click the command button. For
example, let say the random number generated is 0.98, after multiplying it by 6, it becomes 5.88,
and using the integer function Int(5.88) will convert the number to 5; and after adding 1 you will
get 6.
Example 2
Now, run the program and then click on the command button
9
The Numeric Functions
The numeric functions are Int, Sqr, Abs, Exp, Fix, Round and Log.
a) Int is the function that converts a number into an integer by truncating its decimal part
and the resulting integer is the largest integer that is smaller than the number.For
example, Int(2.4)=2, Int(4.8)=4, Int(-4.6)= -5, Int(0.032)=0 and so on.
b) Sqr is the function that computes the square root of a number. For example, Sqr(4)=2,
Sqr(9)=2 and etc.
c) Abs is the function that returns the absolute value of a number. So Abs(-8) = 8 and
Abs(8)= 8.
e) Fix and Int are the same if the number is a positive number as both truncate the decimal
part of the number and return an integer. However, when the number is negative, it will
return the smallest integer that is larger than the number.For example, Fix(-6.34)= -6
while Int(-6.34)=-7.
f) Round is the function that rounds up a number to a certain number of decimal places. The
Format is Round (n, m) which means to round a number n to m decimal places. For
example, Round (7.2567, 2) =7.26
g) Log is the function that returns the natural Logarithm of a number.For example, Log 10=
2.302585
Example 3
This example computes the values of Int(x), Fix(x) and Round(x,n) in a table form. It uses the
Do Loop statement and the Rnd function to generate 10 numbers. The statement x = Round (Rnd
* 7, 7) rounds a random number between 0 and 7 to 7 decimal places. Using commas in between
items will create spaces between them and hence a table of values can be created. The program
code is shown below
10
FORMATTING FUNCTIONS
Formatting output is a very important part of programming so that the data can be presented
systematically and clearly to the users. To have better control of the output format, we can use a
number of formatting functions in Visual basic.
The three most common formatting functions in VB are Tab, Space, and Format
Example
Example
Means that the words Visual and Basic will be separated by 10 spaces
11
The Format function
The Format function is a very powerful formatting function which can display the numeric
values in various forms. There are two types of Format function, one of them is the built-in or
predefined format while another one can be defined by the users.
Format (n, “style argument”) where n is a number and the list of style arguments is shown in
Table below
Example
12
Now, run the program and you will get an output like the figure below:
Although it is known as user-defined format, we still need to follows certain formatting styles.
Examples of user-defined formatting style are listed in Table below.
Example
13
The output is shown in the following figure:
14
Rtrim(“Phrase”)
For example,
Rtrim (“Visual Basic ”, 4) = Visual basic
vi. The Trim function
The Ttrim function trims the empty spaces on both side of the phrase.
The format isTrim(“Phrase”)
For example,
Trim (“ Visual Basic ”) = Visual basic
vii. The Mid Function
The Mid function extracts a substring from the original phrase or string. It takes the
following format:
Mid(phrase, position, n)
Where position is the starting position of the phrase from which the extraction
process will start and n is the number of characters to be extracted.
For example,Mid(“Visual Basic”, 3, 6) = ual Bas
viii. The InStr function
The InStr function looks for a phrase that is embedded within the original phrase and
returns the starting position of the embedded phrase. The format is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the embedded
phrase.
For exampleInstr(1, “Visual Basic”,” Basic”)=8
ix. The Ucase and the Lcase functions
The Ucase function converts all the characters of a string to capital letters. On the
other hand, the Lcase function converts all the characters of a string to small
letters.For example,
Ucase(“Visual Basic”) =VISUAL BASiC
Lcase(“Visual Basic”) =visual basic
x. The Str and Val functions
The Str is the function that converts a number to a string while the Val function
converts a string to a number. The two functions are important when we need to
perform mathematical operations.
xi. The Chr and the Asc functions
The Chr function returns the string that corresponds to an ASCII code while the Asc
function converts an ASCII character or symbol to the corresponding ASCII code.
ASCII stands for “American Standard Code for Information Interchange”. Altogether
there are 255 ASCII codes and as many ASCII characters. Some of the characters
may not be displayed as they may represent some actions such as the pressing of a
key or produce a beep sound. The format of the Chr function is Chr(charcode)and the
format of the Asc function isAsc(Character)The following are some
examples:Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38
15
CREATING USER-DEFINED FUNCTIONS
Creating Your Own Function
The general format of a function is as follows:
NB// Public indicates that the function is applicable to the whole project and Private indicates
that the function is only applicable to a certain module or procedure. If user defined function are
left without indicating scope it assigned public by default.
16
Example 2:The following program will automatically compute examination grades based
on the marks that a student obtained.
17