Sub Programs in Vbnew
Sub Programs in Vbnew
Sub Programs in Vbnew
SUB PROGRAMS IN VB
Outputting variables
There are several methods to output variable x as stated in the
following:
On form
Print x
to text tool
textno.text =X
to label tool
Labelno.caption=x
By message box
msgbox (x)
Or msgbox ("remark"& x
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.
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.
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)
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
4 VbYesNo Yes, No
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
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.
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.
Num = Val(Text1.Text)
Result = Log(Num)
Text2.Text = Str(Result)
End Sub
For example,
Num = Val(Text1.Text)
Result = Int(Num)
Text2.Text = Str(Result)
End Sub
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.
Text2.Text = UCase(Text1.Text)
End Sub
Len()
Len() return the length of a given string.
Syntax
RTrim(String)
Trim(String)
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()
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()
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:
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:
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
Example:
strMoName = MonthName(8) ' strMoName = "August"
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
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
Const pi = 3.142
area = pi * r * r
End Function
Private Sub Command1_Click()
radius = Val(Text1.Text)
areas = area(radius)
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
End Sub
Pass by Value and pass by reference
What is Pass by Value
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
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.