Nothing Special   »   [go: up one dir, main page]

Sub Programs in Vbnew

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 80

WEEK 9 LESSON 1

SUB PROGRAMS IN VB
Outputting variables
 There are several methods to output variable x as stated in the
following:
 On form
 Print x

NB: in load event we must use the statement:


 (form1.show)

 to text tool
 textno.text =X

 to label tool
 Labelno.caption=x

 By message box
 msgbox (x)
 Or msgbox ("remark"& x

 On Picture box tool


 Pictureno.print x
By the end of the lesson, the learner should be able to:
 Define Sub programs
 Explain types of sub programs
Definition of sub programs
Refers to any set of statements forming part of the program used to
perform a specific action.
They are procedures, modules or parts within the program that are used to
carry out a specific task before passing control to the main program.
A properly constructed subprogram should be self contained perform
defined operation on a well defined data and have an internal structure
independent of the program in which it’s contained.
Types of sub-programs in visual basic
A function is similar to a procedure, except it returns a value to the calling code

Procedures
A procedure is a block of Visual Basic statements inside Sub, End Sub
statements. Procedures do not return values
A procedure is a block of code that performs some operation. or example,
associating code with a CommandButton to quit an application is a procedure.

The difference between the two is that functions return values, procedures do
not.
advantages of using procedures and functions
 A procedure and function is a piece of code in a larger program. They
perform a specific task.

 Reducing duplication of code


 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding
Types of procedures
Sub Procedure – It performs a certain action. It does not return a value to
the calling code.

Event Handling Procedure – These procedures occur due to an event raised


by user action or by the program.

Operator Procedure – It defines the behavior of a standard operator when


one or both of the operands are a newly defined class or structure.

Property Procedure – It returns and assigns values of properties on objects


or modules.
Types of procedures
Indicates that the procedure is available to all modules. If Option Private is used in the
Public
module, the procedure is not available to modules outside of the project.

Indicates that the procedure is only available to other procedures or functions in the
Private
current module or form.

Indicates that all variables declared within the procedure are retained, even when the
Static
procedure is out of scope.

The name of the procedure. Must be unique to the module if declared Private,
procName otherwise unique to the project. The name of the procedure follows the naming rule for
Variables.
A list of variables passed to the procedure as arguments, and their data types. Multiple
arglist arguments are separated by commas. Arguments may be Optional, and may be Read
Only.
functions
 A function is any normal procedure but it is used to accept certain inputs and pass
them to main program to finish execution. It is used to pass or return a value which
will be used to do a certain operation.

 There are two types of function in vb


I. Built-in functions (or internal functions)

II. User defined functions


The syntax of a function is:

Function Name (arguments)


Statements
End function
Built-in functions

a) Msgbox() functions
A message box is a special dialog box used to display a piece of
information to the user. As opposed to a regular form, the user cannot type
anything in the dialog box.
It is used to output a message to the user (at running stage) the code
needed could be written in code sheet and in any event or command.
The objective of the Msgbox function is to produce a pop-up message box
and prompts the user to enter or click on a command button before he/she
can continue.
Format


Message=Msgbox (prompt, stylevalue, title)

Prompt – will display the message in a message box.

Style value – determine the type of command button will appear on the
message box.
Title -String expression displayed in the title bar of the dialog box. If you
omit title, the application name is placed in the title bar.
Message box
Style Value NAMED CONSTANT BUTTON DISPLAYEED

0 VbOk Ok only

1 VbOkCancel Ok and Cancel

2 VbAbortRetryIgnore Abort, Retry and Ignore

3 VbYesNoCancel Yes, No, Cancel

4 VbYesNo Yes, No

5 Vbretycancel Retry, Cancel


example
 Private Sub Command1_Click()
 Dim message As String
 message = MsgBox("are you", 4 + 16, "rtryy")
 If message = vbYes Then
 Unload Me

 End If

 End Sub
example
 Private Sub Command1_Click()
 Dim message As String
 Dim num As Integer
 num = InputBox("enter num", "Number", 76)
 If num > 50 And num < 100 Then
 message = MsgBox("you have passed", 2 + vbInformation, "Well done")
 Else
 message = MsgBox("You have failed", 1 + vbCritical, "Pull your socks")
 End If

 End Sub
Input box function
 The input box function is used to display a message box where the user can enter a value or
message in form of text.
 Format

 Message=inputbox (prompt, title, default text, x-position, y-position)

 Prompt – the message normally displayed as a question.

 Title – the title of the input box function.

 Default text – a text that appears in the input box field where the users can use it as his or her
intended input or information he wishes to key in.
 X and y position – indicate the coordinates of input box.
InputBox function cont’
The Input Box function prompts the users to enter values. After entering
the values, if the user clicks the OK button or presses ENTER on the
keyboard, the InputBox function will return the text in the text box.

 If the user clicks the Cancel button, the function will return an empty
string ("").
 Function findArea()
 Dim Length As Double
 Dim Width As Double

 Length = Val(InputBox("Enter Length ", "Enter a Number“,4))
 Width = Val(InputBox("Enter Width", "Enter a Number“5))
 findArea = Length * Width
 End Function

 Private Sub Command1_Click()

 MsgBox ("area is" & findArea)



 End Sub
Mathematical Functions
The common mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs,
Exp, Log, Sin, Cos, Tan , Atn, Fix and Round.
FUNCTION DESCRIPTION
Abs(x) Absolute of x
Sqr(x) Square root of x
Int(x) Integer of x
Exp(x) Exponential of x (ex)
Fix(x) Take the integer part
Sin(x), cos(x), tan(x) Trigonometric functions
Log(x) Natural logarithms
Len(x) Number of character of variable x
Lcase(x) Change the text x to small letters
Ucase(x) Change the text x to capital letters
CONVERSION FUNCTIONS
Cint(x) Convert x to integer
Clong(x) Convert x to long integer
Cdbl(x) Convert x to double precision
Cstr(x) Convert variable x to string
Val(x) Convert string x to numerical variable
The Rnd Function

 Rnd is is very useful function for dealing with the concept of chance and probability.
The Rnd function returns a random value between 0 and 1.

 Private Sub Command1_Click()


 Text1.Text = Rnd
 End Sub

 Private Sub Form_Activate


 Dim x as integer
 For x=1 to 10
 Print Rnd
 Next
 End Sub
The sqr() function
the sqr() function gives the square root of any number. The argument for
the sqr() function must be a Double mean a real number.

In the example program below, we accept a number and return its square
root.
example
Private Sub Command1_Click()
Dim result As Double

result = Sqr(Val(Text1.Text))
MsgBox (result)

End Sub
Private Sub Command2_Click()
Dim ans As Double
ans = Sqr(Val(InputBox("enter a", "number", 4)))

MsgBox (ans)

End Sub
Log() Function
The Log function takes the Log x of a number x. To know the correct log
value of a number you must refer to a log table.

For example, logex = loge10 = 2.302585


examples
 Private Sub Command1_Click()

 Dim Num As Double, Result As Double

 Num = Val(Text1.Text)

 Result = Log(Num)

 Text2.Text = Str(Result)

 End Sub

 Private Sub Command2_Click()


 Text1.Text = ""
 Text2.Text = ""
 End Sub
Int() Function
The int() function will change any double or real number into integer and
drop the real part.

For example,

234.56 becomes 234


 Private Sub Command1_Click()

 Dim Num As Double, Result As Double

 Num = Val(Text1.Text)

 Result = Int(Num)

 Text2.Text = Str(Result)

 End Sub

 Private Sub Command2_Click()

 Text1.Text = ""
 Text2.Text = ""

 End Sub
STRING FUNCTIONS IN VISUAL BASIC
UCase() and LCase()
Takes a string and returns uppercase or lowercase version depending on
user choice.

Private Sub Command1_Click()

Text2.Text = UCase(Text1.Text)

End Sub
Len()
Len() return the length of a given string.

Private Sub Command1_Click()


Dim vip As String
vip = Text1.Text
Text2.Text = Len(vip)
End Sub
The Ltrim function
Removes the blank spaces from the left side of the string.

Dim var as Variant


 var = " Microsoft Visualbasic"
 msgbox ("After Ltrim : " & LTrim(var))
The Mid Function
Returns a specified number of characters from a given input string.
Returns a portion of a string
String − A required parameter. Input String from which the specified
number of characters to be returned.
Start − A required parameter. An Integer, which specifies the starting
position of the string.
Length − An optional parameter. An Integer, which specifies the number
of characters to be returned.
Private Sub Command1_Click()

 Dim var As Variant


 var = "Microsoft VBScript"
 MsgBox ("Line 1 : " & Mid(var, 2))
 MsgBox ("Line 2 : " & Mid(var, 2, 5))
 MsgBox ("Line 3 : " & Mid(var, 5, 7))


End Sub
The Rtrim function
 Removes the blank spaces from the right side of the string.
 Removes trailing spaces from a string

 Syntax

 RTrim(String)

 Private Sub Command1_Click()

 Dim var As Variant


 var = "Microsoft VBScript "
 MsgBox ("After Rtrim : " & RTrim(var))


 End Sub
The Trim function
 Removes both the leading and the trailing blank spaces of the given input string.
 Syntax

 Trim(String)

 Private Sub Command1_Click()

 var = " Microsoft VBScript "


 MsgBox ("After Trim : " & Trim(var))
 End Sub
The Len function
Returns the length of the given input string including the blank spaces.
Returns the length of a string or size of a variable
 Syntax
o Len(String)

 Private Sub Command1_Click()

 Dim var1 As Variant


 Dim var2 As Variant

 var1 = "Microsoft VBScript"
 MsgBox ("Length of var1 is : " & Len(var1))

 var2 = " Visual programming "
 MsgBox ("Length of var2 is : " & Len(var2))


 End Sub
The Replace function
replaces a specified part of a string with a
specific string, a specified number of times.
Syntax
Replace(string,find,replacewith[,start[,co
unt[,compare]]])
The Replace function
 Parameter Description

 String − A required parameter. The Input String which is to be searched for replacing.

 Find − A required parameter. The part of the string that will be replaced.

 Replacewith − A required parameter. The replacement string, which would be replaced against the find
parameter.

 Start − An optional parameter. Specifies the start position from where the string has to be searched and
replaced. Default value is 1.

 Count − An optional parameter. Specifies the number of times the replacement has to be performed.

 Compare − An optional parameter. Specifies the comparison method to be used. Default value is 0.
 Private Sub Command1_Click()

 Dim var As Variant


 var = "This is VBScript Programming"

 'VBScript to be replaced by MS VBScript
 MsgBox ("Line 1: " & Replace(var, "VBScript", "MS VBScript"))

 'VB to be replaced by vb
 MsgBox ("Line 2: " & Replace(var, "VB", "vb"))

 ''is' replaced by ##

 End Sub
The String function
fills a string with the specified character for specified number of times.
Syntax
 String(number,character)

Parameter Description
Number − A required parameter. An integer value, which would be
repeated for a specified number of times against the character parameter.
Character − A required parameter. Character value, which has to be
repeated for a specified number of times.
Private Sub Command1_Click()

 MsgBox ("Line 1 :" & String(3, "$"))


 MsgBox ("Line 2 :" & String(4, "*"))
 MsgBox ("Line 3 :" & String(5, "u"))
 MsgBox ("Line 4 :" & String(6, "y"))
End Sub
strComp()
Is a string handling function that compares two given string and returns an
integer value. If the strings are same, a 0 is returned and if they are
different then -1 is returned.
 Private Sub Command1_Click()
 Dim result As Integer

 result = StrComp(Text1.Text, Text2.Text)

 If result = 0 Then

 Text3.Text = "True"
 Else

 Text3.Text = "False"
 End If

 End Sub
DATE FUNCTION IN VB 6
DateValue


 Returns the date portion of a Date/Time value, with the time portion "zeroed out".
(Note: When the vb6 time portion of a date/time variable is "zeroed out", the time
would be interpreted as 12:00 AM.)

 Example:

 Dim dtmTest As Date


 dtmTest = DateValue(Now)

 At this point, the date portion of dtmTest is 8/31/2001, with a time portion of 0 (12:00
AM midnight).
TimeValue

 Returns the time portion of a Date/Time value, with the date portion "zeroed
out". (Note: When a date/time variable is "zeroed out", the date will actually be
interpreted as December 30, 1899.)

 Example:

 Dim dtmTest As Date


 dtmTest = TimeValue(Now)

 At this point, the time portion of dtmTest is 9:15:20 PM, with a date portion of
0 (12/30/1899).
WeekdayName


 Returns a string containing the weekday name ("Sunday" thru "Saturday"), given a numeric argument with the
value 1 through 7.

 Example:
 strDOW = WeekdayName(6) ' strDOW = "Friday"

 The WeekdayName function takes an optional, second argument (Boolean) indicating whether or not to
abbreviate the weekday name. By default, the second argument is False, meaning do not abbreviate and return
the full name. If True, the first three letters of the weekday name will be returned:

 Example:
 strDOW = WeekdayName(6, True) ' strDOW = "Fri"

 You can nest the Weekday function within the WeekdayName function to get the weekday name for a given date:
Month


Returns a number from 1 to 12 indicating the month portion of a given
date.

Example:
intMonth = Month(Now) ' intMonth = 8
MonthName

Returns a string containing the month name ("January" thru "December"),


given a numeric argument with the value 1 through 12.

Example:
strMoName = MonthName(8) ' strMoName = "August"

The MonthName function takes an optional, second argument (Boolean)


indicating whether or not to abbreviate the month name. By default, the
second argument is False, meaning do not abbreviate and return the full
name. If True, the first three letters of the month name will be returned:
Day


Returns a number from 1 to 31 indicating the day portion of a given date.

Example:
intDay = Day(Now) ' intDay = 31
Year


Returns a number from 100 to 9999 indicating the year portion of a given
date.

Example:
intYear = Year(Now) ' intYear = 2001
User defined functions

These are those functions that user/programmer creates to perform a


certain operation.

Format

Public function functionname (arg as datatype………….) as datatype

Private function functionname (arg as datatype………..) as datatype
Private Function Name(byval a as )
is the function procedure header. The header contains the keyword
function, the function name and parentheses. The declarations and
statements that the programmer will insert between the header and End
Function form the function procedure body,
A function procedure return value is specified in the body by assigning a
value to the function
procedure name, as in
Fact=N^2
Then returns (along with the value returned) to the calling statement
Private Function Fact( N )
Fact=N^2
End Function
Private Function Area (s1 as single,s2 as single)
Area=s1*s2
End Function
Declaring a function
Function FunctionName [(ParameterList)] As ReturnType
 ' The following statement immediately transfers control back
 ' to the calling code and returns the value of Expression.
 Return Expression
End Function
Public and private function
Public indicates that the function is applicable to the whole program and
private indicates that the function applicable to certain modules, statement
or procedures only.

User defined function can be created with add procedure dialog box. They
can also be created in the code window by typing directly into it
A parameter
A parameter represents a value that the procedure expects you to pass
when you call it.
Parameter is variable defined in function declaration.
Argument is the actual value of this variable that get passed to the
function .
Function parameters are the names listed in the function's definition.
Function arguments are the real values passed to the function. Parameters
are initialized to the values of the arguments supplied.
Program to calculate the area of a rectangle
 Private Function area(ByVal a As Integer, ByVal b As Integer) As Integer
 area = a * b
 End Function

 Private Sub Command1_Click()


 Dim L As Integer, W As Integer, TOTAL As Integer
 L = Val(InputBox("ENTER LEMGTH"))
 W = Val(InputBox("ENTER WIDTH"))
 TOTAL = area(L, W)
 MsgBox ("the area is" & TOTAL)
 End Sub
example
 Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
 Add = x + y
 End Function

 Private Sub Form_Load()
 Dim a As Integer
 Dim b As Integer
 Dim c As Integer

 a = 32
 b = 64
 c = Add(a, b)

 MsgBox c
 End Sub
Write a code program to read three integer numbers. Using a define sub
Function
(Min) to determine the smallest of three integers. Display the smallest value
in textbox
 Solution:
 Private Sub Command1_Click()
 Dim Num1 As Single, Num2 As Single, Num3 As Single, Result As Single
 Num1 = Fix(Text1.Text)
 Num2 = Fix(Text2.Text)
 Num3 = Fix(Text3.Text)
 Result =MinNum1, Num2, Num3)
 Text4.Text = Str(Result)
 End Sub
 Private Function Min(Num1, Num2, Num3)
 Min = Num1
 If Num2 < Min Then Min = Num2
 If Num3 < Min Then Min = Num3
 End Function
Using a visual basic function calculate the area of a circle given
 Public Function area(r As Variant) As Variant

 Const pi = 3.142

 area = pi * r * r

 End Function
 Private Sub Command1_Click()

 Dim radius As Variant

 radius = Val(Text1.Text)

 Dim areas As Variant

 areas = area(radius)

 MsgBox ("The area is:" & areas)

 End Sub
Example
Write a visual basic function using a function to calculate the grade of
student based on average mark.
Types of procedures in visual basic

Event procedures
These are procedures used to design programs that respond to events. For
example


 Private Sub cmdcompute_Click()
Block of statements
End Sub

General procedures

These are procedures that are used to access any statement in a program.
For example

Const pi=3.142
Rate=10%
Sub programs
 These are sub-routines which are logically accessed by programs in projects. They are local to the main
program :
 Is a part of a program that performs one or more related tasks, has its own name and it is written as a
separate part of the program.
 -Its syntax is:
o Private sub procedurename()
o Statement(s)
o End sub

Private Sub cmdcompute_Click ()


Block of statements
End Sub

 A subprogram or a subroutine is a program called by another program to perform a particular task or


function for the program
Private Sub DisplayAdd(x As Integer, y As Integer)
 MsgBox x + y
End Sub

Private Sub Form_Load()
 DisplayAdd 5, 2
End Sub
Example:
A program that accepts and calculates the sum of two numbers using a sub procedure.

 Private Sub add(n1 As Single, n2 As Single)


 Dim S As Single
 S = n1 + n2
 Picture1.Print S
 End Sub

 Private Sub Command1_Click()


 Dim x As Single, y As Single
 x = Val(Text1.Text)
 y = Val(Text2.Text)
 Call add(x, y)
 End Sub
 Private Sub add(a As Double, w As Double)
 Dim sum As Double
 sum = a + w
 MsgBox ("sum is" & sum)
 End Sub

 Private Sub Command2_Click()


 Dim length As Double, width As Double
 length = InputBox("add length")
 width = InputBox("add width")
 Call add(length, width)

 End Sub
Pass by Value and pass by reference
What is Pass by Value

In pass by value, the value of a function parameter is copied to another


location of the memory.
When accessing or modifying the variable within the function, it accesses
only the copy. Thus, there is no effect on the original value.
When we pass arguments by value, the function works only with the copies of
the values. This may lead to performance overheads, when we work with
large amounts of data.
What is Pass by Reference

In pass by reference, the memory address is passed to that function. In


other words, the function gets access to the actual variable.
When we pass values by reference, the function receives a reference to the
actual values. The original values are affected, when modified. This way
of passing values is more time and space efficient. On the other hand, it is
more error prone.
Difference Between Pass by Value and Pass by Reference

 Definition

 Pass by value refers to a mechanism of copying the function parameter value to another variable while the
pass by reference refers to a mechanism of passing the actual parameters to the function. Thus, this is the
main difference between pass by value and pass by reference.

 Changes

 In pass by value, the changes made inside the function are not reflected in the original value. On the other
hand, in pass by reference, the changes made inside the function are reflected in the original value. Hence,
this is another difference between pass by value and pass by reference.

 Actual Parameter

 Moreover, pass by value makes a copy of the actual parameter. However, in pass by reference, the address
of the actual parameter passes to the function.
Public Sub probyvalue(ByVal a As Integer, ByVal b As Integer)
Dim temp As Integer
temp = a
a = b
b = temp

End Sub
Public Sub probyref(ByRef a As Integer, ByRef b As Integer)
Dim temp As Integer
temp = a
a = b
b = temp
End Sub
 Private Sub Command1_Click()
 Dim x As Integer, y As Integer
 x = Val(Text1.Text)
 y = Val(Text2.Text)
 Call probyvalue(x, y)
 Label3.Caption = x
 Label4.Caption = y
 End Sub

 Private Sub Command2_Click()


 Dim x As Integer, y As Integer
 x = Val(Text1.Text)
 y = Val(Text2.Text)
 Call probyref(x, y)
 Label3.Caption = x
 Label4.Caption = y
 End Sub
Using a function write a program that prints numbers from 10 to 0 but
when it goes below zero it exits from executing.

Write a visual basic program that accepts any three integers and then
determines the highest number among them. Use a function.

Write a visual basic program that accepts any three integers. Let the
program divide the integers by numbers of integers entered. If it attempts
to divide by zero exit the execution.

You might also like