0% found this document useful (0 votes)
5 views17 pages

VB Topic 7 Functions and Subprograms

This document provides an overview of sub-programs in Visual Basic, detailing their types, including event and general procedures, and the scope of variables. It explains how to create and use sub procedures and functions, including the differences between passing variables by reference and by value. Additionally, it covers built-in functions, mathematical functions, and formatting functions to enhance programming efficiency and output presentation.

Uploaded by

carmarriemaish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

VB Topic 7 Functions and Subprograms

This document provides an overview of sub-programs in Visual Basic, detailing their types, including event and general procedures, and the scope of variables. It explains how to create and use sub procedures and functions, including the differences between passing variables by reference and by value. Additionally, it covers built-in functions, mathematical functions, and formatting functions to enhance programming efficiency and output presentation.

Uploaded by

carmarriemaish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

7.

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.

In VB there are two types of procedures we will work with:


1) Event procedures and 2) General procedures

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

Private Sub Form_Load()


....statement block..
End Sub

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:

[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. To call a Sub, you use the Call statement. The examples below shows how the
Call statement is used.

Examples of Procedure codes:


Example1: Use of procedure with Parameters
Type the following module in the General declaration area

Sub Multiply(ByVal mult As Double, ByRef m1, m2 As Long)


mult = m1 * m2
MsgBox ("Your answer is "& mult) 'Can only be output in the procedure
End Sub

Double click the command and type the following code

Private Sub Cmdsub2_Click()


'program to Multiply two numbers using parameters
Dim ans As Double
Dim No1, no2 As Long
No1 = InputBox("Enter the first Number")
no2 = InputBox("Enter the Second Number")
Call Multiply(ans, No1, no2)
End Sub

Example2:
Use of procedure with Parameters both ByVal and ByRef
Type the following module in the General declaration area

Sub Multiply1(ByVal p1, p2 As Single, m2 As Double)

2
'Note p1 and p2 are Value Parameters and M2 is Reference Parameter
m2 = p1 / p2
End Sub

Double click the command and type the following code

Private Sub cmdsub3_Click()


'program to Multiply two numbers using parameters
Dim Number1, Number2 As Single
Dim m1 As Double
Number1 = InputBox("Enter the first Number")
Number2 = InputBox("Enter the Second Number")
Call Multiply1(Number1, Number2, m1)
MsgBox ("Your answer is "& m1)
End Sub

Example 3:

Private Sub findsum(ByVal x As Integer, ByRef y As Integer)


Print "recieved value of x="; x
Print " received value of y="; y
x=2*x
y=2*y
Print "modified value of x="; x
Print "modified value of y="; y
Print
End Sub

Private Sub Command1_Click()


Dim num1 As Integer, num2 As Integer
num1 = 12
num2 = 15
Print "passed value of x="; num1
Print "passed value of y="; num2
Print
Call findsum(num1, num2)
End Sub

ByRef vs. ByVal


Variables can be passed to a subroutine "by reference" or "by value". The default is "by
reference". The examples above show the different example using the two ways of passing
variables. The differences are as follows:

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).

The general format of a function is

functionName(arguments) ie StudDetails(fistname as string) as string

where arguments are values that are passed on to the 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:

yourMsg=MsgBox(Prompt, Style Value, Title)

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.

example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")

and yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")

are the same.

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.

Return Values and Command Buttons


Value Named Constant Button Clicked
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button

Example

i. The Interface:

You draw three command buttons and a label as shown in below

5
ii. The procedure for the test button:

Private Sub Test_Click()


Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
Display.Caption = "Testing Successful"
Else
Display.Caption = "Testing fail"
End If
End Sub

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

In this example, the following message box will be displayed:

Private Sub test2_Click()


Dim testMsg2 As Integer
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg2 = 6 Then
display2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else
display2.Caption = "Testing fail"
End If

End Sub

The InputBox( ) Function


An InputBox( ) function will display a message box where the user can enter a value or a
message in the form of text. The format is:

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

 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

ii. The procedure for the OK button

Private Sub OK_Click()


Dim userMsg As String
userMsg = InputBox("What is your message?", _
"Message Entry Form", "Enter your messge here", 500, 700)
If userMsg <> "" Then
Label1.Caption = userMsg
Else
Label1.Caption = "No Message"
End If
End Sub
When a user click the OK button, the input box as shown in below will appear. After user
entering the message and click OK, the message will be displayed on the caption, if he click
Cancel, "No message" will be displayed.

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

Private Sub Form_Activate


Randomize Timer
For x=1 to 10
Print Rnd
Next x
End Sub

The Output for example above is shown below:

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

Dim num as integer


Private Sub Command1_Click ( )
Randomize Timer
Num=Int(Rnd*6)+1
Label1.Caption=Num
End Sub

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.

d) Exp of a number x is the value of ex.For example, Exp(1)=e1 = 2.7182818284590

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

Private Sub Form_Activate ()


n=1
Print " n", " x", "Int(x)", "Fix(x)", "Round(x, 4)"
Do While n < 11
Randomize Timer
x = Round (Rnd * 7, 7)
Print n, x, Int(x), Fix(x), Round(x, 4)
n=n+1
Loop
End Sub

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

The Tab function


Tab (n); x
The item x will be displayed at a position that is n spaces from the left border of the output form.
There must be a semicolon in between Tab and the items you intend to display (VB will actually
do it for you automatically).

Example

Private Sub Form_Activate


Print "I"; Tab(5); "like"; Tab(10); "to"; Tab(15); "learn"; Tab(20); "VB"
Print
Print Tab(10); "I"; Tab(15); "like"; Tab(20); "to"; Tab(25); "learn"; Tab(20); "VB"
Print
Print Tab(15); "I"; Tab(20); ; "like"; Tab(25); "to"; Tab(30); "learn"; Tab(35); “VB"
End sub

The Output for example above is shown below:

The Space function


The Space function is very closely linked to the Tab function. However, there is a minor
difference. While Tab (n) means the item is placed n spaces from the left border of the screen,
the Space function specifies the number of spaces between two consecutive items. For example

Example

Private Sub Form_Activate()


Print "Visual"; Space(10); "Basic"
End Sub

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.

(a) The syntax of the predefined Format function is

Format (n, “style argument”) where n is a number and the list of style arguments is shown in
Table below

Style Explanation Example


argument
General To display the number
Number without having separators Format(8972.234, “General
between thousands. Number”)=8972.234
Fixed To display the number
without having separators Format(8972.2, “Fixed”)=8972.23
between thousands and
rounds it up to two decimal
places.
Standard To display the number with
separators or separators Format(6648972.265, “Standard”)=
between thousands and 6,648,972.27
rounds it up to two decimal
places.
Currency To display the number with
the dollar sign in front, has Format(6648972.265, “Currency”)=
separators between $6,648,972.27
thousands as well as
rounding it up to two
decimal places.
Percent Converts the number to the
percentage form and displays Format(0.56324, “Percent”)=56.32 %
a % sign and rounds it up to
two decimal places.

Example

Private Sub Form_Activate()


Print Format (8972.234, "General Number")
Print Format (8972.2, "Fixed")
Print Format (6648972.265, "Standard")
Print Format (6648972.265, "Currency")
Print Format (0.56324, "Percent")
End Sub

12
Now, run the program and you will get an output like the figure below:

(b) The syntax of the user-defined Format function is

Format (n, “user’s format”)

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 Explanation Output


Format(781234.57,”0”) Rounds to whole number without 781235
separators between thousands.
Format(781234.57,”0.0”) Rounds to 1 decimal place without 781234.6
separators between thousands.
Format(781234.576,”0.00”) Rounds to 2 decimal places without 781234.58
separators between thousands.
Format(781234.576,”#,##0.00”) Rounds to 2 decimal places with 781,234.58
separators between thousands.
Format(781234.576,”$#,##0.00”) Shows dollar sign and rounds to 2 $781,234.58
decimal places with separators
between thousands.
Format(0.576,”0%”) Converts to percentage form without 58%
decimal places.
Format(0.5768,”0.00%”) Converts to percentage form with 2 57.68%
decimal places.

Example

Private Sub Form_Activate()


Print Format(781234.57, "0")
Print Format(781234.57, "0.0")
Print Format(781234.576, "0.00")
Print Format(781234.576, "#,##0.00")
Print Format(781234.576, "$#,##0.00")
Print Format(0.576, "0%")
Print Format(0.5768, "0.00%")
End Sub

13
The output is shown in the following figure:

STRING MANIPULATION FUNCTIONS


String manipulation function are used to manipulate string data type, they include function such
as Len, Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase, Instr, Val, Str ,Chr and Asc.
i. The Len Function: The length function returns an integer value which is the length
of a phrase or a sentence, including the empty spaces. The format is Len (“Phrase”)
For example, Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22The Len
function can also return the number of digits or memory locations of a number that is
stored in the computer. For example,
Private sub Form_Activate ( )
X=sqr (16)
Y=1234
Z#=10#
Print Len(x), Len(y), and Len (z)
End Sub
will produce the output 1, 4 , 8. The reason why the last value is 8 is because z# is a
double precision number and so it is allocated more memory spaces.
ii. The Right Function: The Right function extracts the right portion of a phrase. The
format is
Right (“Phrase”, n)
Where n is the starting position from the right of the phrase where the portion of the
phrase is going to be extracted.
For example,
Right(“Visual Basic”, 4) = asic
iii. The Left Function
The Left$ function extract the left portion of a phrase. The format is
Left(“Phrase”, n)
Where n is the starting position from the left of the phase where the portion of the
phrase is going to be extracted.
For example,
Left (“Visual Basic”, 4) = Visu
iv. The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase. The
format is
Ltrim(“Phrase”)
.For example,
Ltrim (“ Visual Basic”, 4)= Visual basic
v. The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase. The
format is

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:

Public FunctionfunctionName (Arg As dataType,..........) As dataType


or
Private FunctionfunctionName (Arg As dataType,..........) As dataType
Example
Public function AddNumbers (num1 as integer, num2 as interger) as double
Private function AddNumbers (num1 as integer, num2 as interger) as double

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.

Working user defined functions examples

Example1: Using function with parameters to calculate future value

Public Function FV(PV As Variant, i As Variant, n As Variant) As Variant


'Formula to calculate Future Value(FV)
'PV denotes Present Value
FV = PV * (1 + i / 100) ^ n
End Function

Private Sub compute_Click()


'This procedure will calculate Future Value
Dim FutureVal As Variant
Dim PresentVal As Variant
Dim interest As Variant
Dim period As Variant
PresentVal = PV.Text
interest = rate.Text
period = years.Text
FutureVal = FV(PresentVal, interest, period)
MsgBox ("The Future Value is " & FutureVal)
End Sub

16
Example 2:The following program will automatically compute examination grades based
on the marks that a student obtained.

Function grade(mark As Variant) As String


mark = Val(Text1.Text)
Select Case mark
Case Is >= 80
grade = "A"
Case Is >= 70
grade = "B"
Case Is >= 60
grade = "C"
Case Is >= 50
grade = "D"
Case Is >= 40
grade = "E"
Case Else
grade = "F"
End Select
End Function

Private Sub Command1_Click()


Text2.Text = grade(mark)
End Sub

Example3:Used to add 5 to every value entered in text1

Function ongezatano(x As Integer) As Integer


ongezatano = x + 5
End Function
Private Sub Command1_Click()
Dim numyetu As Integer
Dim numpya As Integer
numpya = Val(Text1.Text)
MsgBox ("our new num:" &ongezatano(numpya))
End Sub

17

You might also like