1. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page1
Pondicherry University Community College
Department of Computer Science
Course : BCA
Year : II
Semester : III
Subject : Programming with Visual Basic
Unit III Study Material
Prepared by
D.GAYA
Assistant Professor,
Department of Computer Science,
Pondicherry University Community College,
Lawspet, Puducherry-08.
2. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page2
MODULE –III
Functions and Procedure - Passing arguments by value and reference – Arrays,
dynamic arrays –User defined data types – symbolic constants – using Dialog boxes: Input
box, Message box functions - String functions, date and Time function, numeric functions
Functions and Procedure
Functions
A function is a named section of code that returns a value. You can reuse functions
many times within your program. For calculation purposes, you can pass information into
functions. The information that you pass into a function is called a parameter, also known as
an argument.
A function is a block of Visual Basic statements inside Function, End
Function statements. Functions return values.
There are two basic types of functions. Built-in functions and user defined ones. The built-in
functions are part of the Visual Basic language. There are various mathematical, string or
conversion functions.
Procedures
A procedure is an assignment you ask the compiler to take care of inside of your
program. The assignment is performed behind the scenes. The program developer writes the
function and the user would only see the result.
In reality, there are two types of procedures you will use in your programs: those that
have already been created thus made available to you, and those you will create yourself.
Creating a Sub Procedure
To create a new sub procedure, in the Routines file, type sub
SquarePerimeter and press Enter. This produces:
Sub SquarePerimeter()
End Sub
3. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page3
To create another sub routine, on the main menu, click Tools -> Add
Procedure...
In the Name edit box, type SquareArea
Click OK
Implement both routines as follows:
Sub SquarePerimeter()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = Form1.txtSide
dblPerimeter = dblSide * 4
Form1.txtPerimeter.Text = dblPerimeter
End Sub
Public Sub SquareArea()
Dim dblSide As Double
Dim dblArea As Double
dblSide = Form1.txtSide
dblArea = dblSide * dblSide
Form1.txtArea.Text = dblArea
End Sub
Save all
4. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page4
Calling a Sub Procedure
Display the form
Double-click the top Calculate button and, in its body, type SquarePerimeter
Double-click the bottom Calculate button and, in its body, type SquareArea
Private Sub cmdCalcArea_Click()
SquareArea
End Sub
Private Sub cmdCalcPerimeter_Click()
SquarePerimeter
End Sub
Text the application
Close the form and return to VB
Function Creation
To create a function, you use the Function keyword followed by a name and
parentheses. Unlike a sub routine, because a function returns a value, you should/must
specify the type of value the function will produce.
To give this information, on the right side of the closing parentheses, type the As
keyword, followed by a data type. To indicates where a function stops, type End Function.
Based on this, the minimum syntax used to create a function is:
Function FunctionName() As DataType
End Function
5. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page5
The name of a function follows the same rules and suggestions we reviewed for sub
routines. The DataType factor indicates the type of value that the function will return. If the
function will produce a word or a group of words, you can create it as String.
If the function will check something and determine whether it produce a true or a
false value, you can create it as Boolean. The other data types are also valid in the contexts
we reviewed them.
As mentioned already, the section between the Function and the End Function lines is
the body of the function. It is used to describe what the function does. As done on a sub
routine, one of the actions you can perform in a function is to declare a (local) variable and
use it as you see fit. Here is an example:
Function CallMe() As String
Dim Salute As String
Salute = "You can call me AI"
End Function
After performing an assignment in a function, to indicate the value it returns,
somewhere after the assignment and before the End Function line, type the name of the
function, followed by the = sign, followed by the value the function returns.
Here is an example in which a function returns a name:
Function CallMe() As String
CallMe = "You can call me AI"
End Function
You can also use some local variables in the function to perform an assignment and
then assign their result to the name of the function. Here is an example:
Function CallMe() As String
Dim Salute As String
Salute = "You can call me AI "
CallMe = Salute
End Function
6. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page6
Creating a Function
Display the Routines module and delete (only) the previously implemented routines
To create a new function, at the end of the file, type function RectPerimeter and press
Enter
To create another function, on the main menu, create Tools -> Add Procedure...
In the Name edit box, type RectArea
In the Type section, click Function
Press Enter
Implement both functions as follows:
Function RectPerimeter()
Dim dblLength As Double
Dim dblHeight As Double
dblLength = Form1.txtLength.Text
dblHeight = Form1.txtHeight.Text
RectPerimeter = (dblLength + dblHeight) * 2
End Function
Public Function RectArea()
Dim dblLength As Double
Dim dblHeight As Double
7. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page7
dblLength = Form1.txtLength.Text
dblHeight = Form1.txtHeight.Text
RectArea = dblLength * dblHeight
End Function
Save all
Calling a Function
As done for the sub routines, in order to use a function in your program, must call it.
Like a sub routine, to call a function, you can simply type its name in the desired section of
the program. Here is an example:
Private Sub Form_Load()
CallMe
End Sub
Since the primary purpose of a function is to return a value, to better take advantage
of such a value, you can assign the name of a function to a property or a variable in the
section where you are calling the function.
In the following example, the return value of the CallMe function is assigned to the
Caption property of the form from its own Load event:
Private Sub Form_Load()
Caption = CallMe
End Sub
8. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page8
Calling a Function
Display the form and double-click the Calculate button
Implement its event as follows:
Private Sub cmdCalculate_Click()
txtPerimeter = RectPerimeter
txtArea = RectArea
End Sub
Test the application
Arguments or Parameters
To use a value in a procedure, we had to declare it. In some cases, a procedure may
need an external value in order to carry its assignment. A value that is supplied to a procedure
is called an argument.
When creating a procedure that will use an external value, declare the argument that
represents that value between the parentheses of the procedure. For a sub routine, the syntax
you use would be:
Sub ProcedureName (Argument)
End Sub
If you are creating a function, the syntax would be:
Function ProcedureName (Argument)
Function Sub
The argument must be declared as a normal variable, omitting only the Dim keyword.
Here is an example that creates a function that takes a string as argument:
Function CalculatePayroll(strName As String) As Double
Function Sub
9. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page9
A certain procedure can take more than one argument. In this case, in the parentheses
of the procedure, separate the arguments with a comma. Here is an example of a sub routine
that takes two arguments:
Sub EvaluateInvoice(strEmplName As String, dblHourlySalary As Currency)
End Sub
In the body of a procedure that takes one or more arguments, use the argument(s) as
you see fit as if they were locally declared variables. For example, you can involve them with
values inside of the procedure. You can also exclusively use the values of the arguments to
perform the assignment.
Passing Arguments to a Procedure
To pass arguments to a function, change the functions in the Routines module as follows:
Function RectPerimeter(dblLength As Double, dblHeight As Double)
RectPerimeter = (dblLength + dblHeight) * 2
End Function
Public Function RectArea(dblLength As Double, dblHeight As Double)
RectArea = dblLength * dblHeight
End Function
Save
Passing Arguments (By Value)
To call a procedure that takes an argument, type its name and a space, followed by
value for each argument. The value provided for an argument is also called a parameter. If
there is more than one argument, separate them with a comma. Here is an example:
Private Sub txtResult_GotFocus()
Dim dblHours As Double
Dim dblSalary As Double
10. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page10
dblHours = txtHours
dblSalary = txtSalary
CalcAndShowSalary dblHours, dblSalary
End Sub
Sub CalcAndShowSalary(Hours As Double, Salary As Double)
Dim dblResult As Double
dblResult = Hours * Salary
txtResult = dblResult
End Sub
Alternatively, you can use the Call keyword to call a sub routine. In this case, when
calling a procedure using Call, you must include the argument(s) between the parentheses.
using Call, the above GotFocus event could call the CalcAndShowSalary as follows:
Private Sub txtResult_GotFocus()
Dim dblHours As Double
Dim dblSalary As Double
dblHours = txtHours
dblSalary = txtSalary
Call CalcAndShowSalary(dblHours, dblSalary)
End Sub
If you use the above technique to call a procedure that takes more than one argument,
you must provide the values of the arguments in the exact order they are listed inside of the
parentheses of the function.
Fortunately, you don't have to. If you know the name of the arguments, you can type
them in any order and provide a value for each. To do that, on the right side of each
argument, type the := operator followed by the desired value for the argument. Here is an
example:
11. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page11
Function DisplayName(FirstName As String, LastName As String) As
String
Dim FullName As String
FullName = FirstName & " " & LastName
DisplayName = FullName
End Function
Private Sub Form_Load()
Caption = DisplayName(LastName:="Nguyen",
FirstName:="Hermine")
End Sub
Passing Arguments by Value
Display the form and double-click the Calculate button
To call the above functions, change the button's event as follows:
Private Sub cmdCalculate_Click()
Dim dblLen As Double
Dim dblHgt As Double
Dim dblPerim As Double
Dim dblArea As Double
dblLen = txtLength.Text
dblHgt = txtHeight.Text
dblPerim = RectPerimeter(dblLen, dblHgt)
dblArea = RectArea(dblLen, dblHgt)
txtPerimeter.Text = dblPerim
txtArea.Text = dblArea
End Sub
12. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page12
Test the application
Close the form and return to MSVB
Passing Arguments By Reference
When calling a procedure that took an argument, we were supplying a value for that
argument. When this is done, the procedure that is called makes a copy of the value of the
argument and make that copy available to calling procedure.
That way, the argument itself is not accessed. This is referred to as passing an
argument by value. This can be reinforced by typing the ByVal keyword on the left side of
the argument. Here is an example:
Sub GetFullName(ByVal FullName As String)
FullName = "Nguyen, Hermine"
End Sub
If you create a procedure that takes an argument by value and you have used
the ByVal keyword on the argument, when calling the procedure, you don't need to use
the ByVal keyword; just the name of the argument is enough, as done in the examples on
arguments so far. Here is an example:
This would produce
13. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page13
An alternative to this technique is to pass the address of the argument to the called
procedure. When this is done, the called procedure doesn't receive a simple copy of the value
of the argument: the argument is accessed at its root.
That is, at its memory address. With this technique, any action carried on the
argument will be kept. That is, if the value of the argument is modified, the argument would
now have the new value, dismissing or losing the original value it had. This technique is
referred to as passing an argument by reference.
To pass an argument by reference, on its left, type the ByRef keyword. This is done
only when creating the function. When the called procedure finishes with the argument, the
argument would keep whatever modification was made on its value. Now consider the
following:
Private Sub Form_Load()
Dim FName As String
FName = "Albert Edou Nkoulou"
GetFullName FName
Caption = FName
End Sub
Sub GetFullName(ByRef FullName As String)
FullName = "Nguyen, Hermine"
End Sub
This would produce:
14. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page14
Using this technique, you can pass as many arguments by reference as many
arguments by value as you want. As you may already, this technique is also used to make a
sub routine return a value, which a regular sub routine cannot do. Furthermore, passing
arguments by reference allows a procedure to return as many values as possible while a
regular function can return only one value.
Arrays
In visual basic, Arrays are useful to store multiple elements of the same data type at
contiguous memory locations and arrays will allow us to store the fixed number of elements
sequentially based on the predefined number of items.
An array can start storing the values from index 0. Suppose if we have an array
with n elements, then it will start storing the elements from index 0 to n-1.
Following is the pictorial representation of storing the multiple values of the same type in a
visual basic array data structure.
15. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page15
Visual Basic Arrays Declaration
In visual basic, Arrays can be declared by specifying the type of elements followed by the
brackets () like as shown below.
Dim array_name As [Data_Type]();
Here, array_name represents the name of an array and Data_type will represent the data type
of elements to store in an array.
For example, the following are the different ways of declaring an array with
different data types in a visual basic programming language.
' Store only int values
Dim numbers As Integer()
' Store only string values
Dim names As String()
' Store only double values
Dim ranges As Double()
Declaring two dimensional Array
The general syntax to declare a two dimensional array is as follow:
Dim ArrayName(Sub1,Sub2) as dataType
The code
Private Sub cmdAdd_Click()
Dim prod, mth As Integer ' prod is product and mth is month
Dim saleVol(1 To 4, 1 To 6) As Integer
Const j = 1
listVolume.AddItem vbTab & "January" & vbTab & "February" & vbTab & "March"
_
& vbTab & "Apr" & vbTab & "May" & vbTab & "June"
16. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page16
listVolume.AddItem vbTab &
"____________________________________________"
For prod = 1 To 4
For mth = 1 To 6
saleVol(prod, mth) = InputBox("Enter the sale volume for" & " " & "product" & " " &
prod & " " & "month" & " " & mth)
Next mth
Next prod
For i = 1 To 4
listVolume.AddItem "Product" & "" & i & vbTab & saleVol(i, j) & vbTab &
saleVol(i, j + 1) & vbTab & saleVol(i, j + 2) _
& vbTab & saleVol(i, j + 3) & vbTab & saleVol(i, j + 4) & vbTab & saleVol(i, j + 5)
Next i
End Sub
17. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page17
Dynamic Array
In VB6, the dynamic array can be resized when the program is executing. The first
step in declaring a dynamic array is by using the Dim statement without specifying the
dimenson list, as follows:
Dim myArray()
Then at run time we can specify the actual array size using the ReDim statement,as follows:
ReDim myArray(1 to n) when n is decided during run time
You can also declare a two dimensional array using ReDim statement, as follows:
ReDim myArray(1 to n, 1 to m) when m and n are known during run time
Example:
To display the elements of an array in a list box.The size of the array will only be
known during run time.
The Code
Private Sub cmd_display_Click()
Dim myArray() As Integer
Dim i, n As Integer
n = InputBox("Enter the upper bound of array")
List1.Clear
For i = 1 To n
ReDim myArray(i)
myArray(i) = i ^ 2
List1.AddItem myArray(i)
Next
End Sub
18. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page18
User defined data types
Variables of different data types when combined as a single variable to hold several
related information is called a User-Defined data type.
A Type statement is used to define a user-defined type in the General declaration
section of a form or module.
User-defined data types can only be private in form while in standard modules can be
public or private.
An example for a user defined data type to hold the product details is as given below.
Private Type ProductDetails
ProdID as String
ProdName as String
Price as Currency
End Type
The user defined data type can be declared with a variable using the Dim statement as
in any other variable declaration statement. An array of these user-defined data types can also
be declared.
An example to consolidate these two features is given below.
Dim ElectronicGoods as ProductDetails ' One Record
Dim ElectronicGoods(10) as ProductDetails ' An array of 11 records
19. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page19
A User-Defined data type can be referenced in an application by using the variable
name in the procedure along with the item name in the Type block.
For example if the text property of a TextBox namely text1 is to be assigned the name
of the electronic good, the statement can be written as given below.
Text1.Text = ElectronicGoods.ProdName
If the same is implemented as an array, then the statement becomes
Text1.Text = ElectronicGoods(i).ProdName
User-defined data types can also be passed to procedures to allow many related items as one
argument.
Sub ProdData( ElectronicGoods as ProductDetails)
Text1.Text = ElectronicGoods.ProdName
Text1.Text = ElectronicGoods.Price
End Sub
Symbolic constants
Visual Basic defines a large number of constants for many activities, sometimes you
need to define your own constants.
Constants are defined with the Const keyword statement to give the constant a name
and a value, as shown in the following syntax:
Const CONSTANT_NAME [As ConstantType] = value
Naming conventions for constants
Constants are typically named with all uppercase characters and, if necessary, with an
underscore character (_) to separate the characters into words: SECRET_NUMBER = 42.
Now that Visual Basic supports its own constants and constants dedicated to classes,
20. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page20
however, it's conventional to name constants in mixed case, with a lowercase prefix:
snNumber = 42.
This statement appears similar to the declaration of a variable. As with declaring a
variable, you provide a name for the constant and optionally specify the type of data it will
hold.
The Const keyword at the beginning of the statement tells Visual Basic that this
statement defines a constant. This distinguishes the statement from one that just assigns a
value to a variable.
Finally, to define a constant, you must include the equal sign (=) and the value to be
assigned. If you're defining a string, remember to enclose the value in quotes ("").
Using Dialog boxes
Input box
Displays a prompt in a dialog box, waits for the user to input text or click a button,
and returns a String containing the contents of the text box.
Syntax:
memory_variable = InputBox (prompt[,title][,default])
memory_variable 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:
21. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page21
Prompt - String expression displayed as the message in the dialog box. If prompt
consists of more than one line, you can separate the lines using the vbCrLf constant
Title - String expression displayed in the title bar of the dialog box. If you omit the
title, the application name is displayed in the title bar
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 inputbox
Following example demonstrates the use of InputBox function
* Open a new project and save the Form as InputBox.frm and save the Project as
InputBox.vbp
* Design the application as shown below.
Object Property Setting
Form Caption
Name
InputBox test
frmInputBox
Label Caption
Name
You entered
lbl1
Label
Caption
Name
BorderStyle
( empty)
lbl2
1-Fixed Single
CommandButton Caption
Name
OK
cmdOK
22. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page22
Following code is entered in cmdOK_Click ( ) event
Private Sub cmdok_Click()
Dim ans As String
ans = InputBox("Enter something to be displayed in the
label", "Testing", 0)
If ans = "" Then
lbl2.Caption = "No message"
Else
lbl2.Caption = ans
End If
End Sub
Save and run the application. As soon as you click the OK button you will get the
following InputBox
Here I have entered "Hello World" in text field. As soon as you click OK the output is shown
as shown below
23. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page23
Message box 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. To support message boxes, the Visual Basic language provides a
function named MsgBox.
The MsgBox function displays a message box and waits for the user to click a button
and then an action is performed based on the button clicked by the user.
Syntax :
MsgBox ( Prompt [,icons+buttons ] [,title ] )
memory_variable = MsgBox ( prompt [, icons+ buttons] [,title] )
The arguments are explained as follows:
24. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page24
Prompt : String expressions displayed as the message in the dialog box. If prompt
consist of more than one line, you can separate the lines using the vbrCrLf constant.
Icons + Buttons : Numeric expression that is the sum of values specifying the number
and type of buttons and icon to display.
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.
To display a simple message box, you can use the MsgBox() function with the following
formula:
MsgBox(Message)
Inside the parentheses, pass a string. Here is an example:
Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Welcome to Microsoft Visual Basic")
End Sub
If the message is made of different sections, you can concatenate them using the & operator.
You can also first declare a String variable, initialize it, and pass it to the function.
The Return Value of a Message Box
Besides displaying a message, a message box can be used to let the user make a
decision by clicking a button and, depending on the button the user would have
clicked, the message box would return a value. To be able to return a value, the
MsgBox() function is declared as follows:
Public Shared Function MsgBox ( _
Prompt As Object, _
<OptionalAttribute> Optional Buttons As MsgBoxStyle =
MsgBoxStyle.OkOnly, _
<OptionalAttribute> Optional Title As Object = Nothing _
) As MsgBoxResult
The value returned by a message box corresponds to a button the user would have
clicked (on the message box). The return value of the MsgBox() function is based
25. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page25
on the MsgBoxResult enumeration. The buttons and the returned values are as
follows:
The Buttons of a Message Box
If you create a simple message box by providing only the message, it would
appear with only one button labeled OK. If you want the user to be able to make a
decision and communicate it to you, provide a second argument. The second
argument must be based on the MsgBoxStyle enumeration. When it comes to
buttons, some members of this enumeration are:
To use any of these combinations of buttons, call
the MessageBoxStyle enumeration and access the desired combination. Here is an
example:
Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Now we will move to the next step", MsgBoxStyle.OkCancel)
26. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page26
End Sub
This would produce:
The Caption of a Message Box
If you create a simple message box by providing only the message, the dialog box
would appear with the name of the project in the title. To allow you to specify a
caption of your choice, provide a second string as the third argument to
the MsgBox() function. Here is an example:
Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Now we will move to the next step", _
MsgBoxStyle.OkCancel, "Lessons Objectives")
End Sub
This would produce:
The Icon of a Message Box
To enhance the appearance of a message box, you can display an icon on it.
To support icons, the MsgBoxStyle enumeration provides the following additional
members
27. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page27
To apply one of these buttons, combine its style with that of the button, using the
OR operator. Here is an example:
Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Are you ready to provide your credit card information?", _
MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _
"Customer Order Processing")
End Sub
This would produce:
The Default Button of a Message Box
When a message box is configured to display more than one button, the operating
system is set to decide which button is the default. The default button has a thick
border that sets it apart from the other button(s). If the user presses Enter, the
message box would behave as if the user had clicked the default button. If the
message box has more than one button, you can decide what button would be the
default. To support the default button, the MsgBoxStyle enumeration provides the
following additional options:
MsgBoxStyle
Integral
Value
If the message box contains
more than one button, the
default button would be
28. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page28
DefaultButton1 0 the first
DefaultButton2 256 the second
DefaultButton3 512 the third
Here is an example:
Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox("Are you ready to provide your credit card information?", _
MsgBoxStyle.YesNoCancel Or _
MsgBoxStyle.Question Or _
MsgBoxStyle.DefaultButton2, _
"Customer Order Processing")
End Sub
Following is an example illustrates the use of message boxes
* Open a new Project and save the Form as messageboxdemo.frm and save the Project as
messageboxdemo.vbp
* Design the application as shown below.
Object Property Setting
Form Caption
Name
MessageBoxDemo
frmMessageBoxDemo
Label Caption
Name
lblName
Name
TextBox Name
Text
txtName
( empty )
29. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page29
ListBox Name lstName
CommandButton Caption
Name
Add
cmdAdd
CommandButton Caption
Name
Delete
cmdDelete
CommandButton Caption
Name
Exit
cmdExit
Following code is entered in the txtName_Change ( ) event
Private Sub txtName_Change()
If Len(txtName.Text) > 0 Then
cmdAdd.Enabled = True
End If
End Sub
Following code has to be entered in the cmdAdd_Click ( ) event
Private Sub cmdAdd_Click()
answer = MsgBox("Do you want to add this name to the list box?",
vbExclamation + vbYesNo,
"Add Confirm")
If answer = vbYes Then
30. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page30
lstName.AddItem txtName.Text
txtName.Text = ""
txtName.SetFocus
cmdAdd.Enabled = False
End If
End Sub
Following code is entered in the cmdDelete_Click ( ) event
Private Sub cmdDelete_Click()
Dim remove As Integer
remove = lstName.ListIndex
If remove < 0 Then
MsgBox "No names is selected", vbInformation, "Error"
Else
answer = MsgBox("Are you sure you want to delete " & vbCrLf & "the
selected name?",_
vbCritical + vbYesNo, "Warning")
If answer = vbYes Then
If remove >= 0 Then
lstName.RemoveItem remove
txtName.SetFocus
MsgBox "Selected name was deleted", vbInformation, "Delete Confirm"
End If
End If
End If
End Sub
Following code is entered in the cmdExit_Click ( ) event
Private Sub cmdExit_Click()
answer = MsgBox("Do you want to quit?", vbExclamation + vbYesNo,
"Confirm")
If answer = vbYes Then
End
31. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page31
Else
MsgBox "Action canceled", vbInformation, "Confirm"
End If
End Sub
String functions
String functions are mainly used to manipulate the string in Visual basic. There are
many useful string functions in Visual Basic 6. The string functions are defined in the
"Strings" module, which can be found in the Object Browser.
The Len Function
The Len function returns an integer value which is the length of a phrase or a
sentence, including the empty spaces. The syntax is
Len (“Phrase”)
For example,
Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22
The Len function can also return the number of digits or memory locations of a
number that is stored in the computer. For example,
X=sqr (16)
Y=1234
Z#=10#
Then Len(x)=1, Len(y)=4, and Len (z)=8
The reason why Len(z)=8 is because z# is a double precision number and so it is
allocated more memory spaces.
The Right Function
The Right function extracts the right portion of a phrase. The syntax is
Right (“Phrase”, n)
32. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page32
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
The Left Function
The Left$ function extract the left portion of a phrase. The syntax 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
The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase. The syntax is
Ltrim(“Phrase”)
.For example,
Ltrim (“ Visual Basic”)= Visual basic
The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase. The syntax is
Rtrim(“Phrase”)
.For example,
Rtrim (“Visual Basic ”, 4) = Visual basic
The Trim function
The Trim function trims the empty spaces on both side of the phrase. The syntax is
Trim(“Phrase”)
.For example,
33. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page33
Trim (“ Visual Basic ”) = Visual basic
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
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 syntax 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 example
Instr(1, “Visual Basic”,” Basic”)=8
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
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.
34. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page34
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 syntax of the Chr function is
Chr(charcode)
and the syntax of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38
We can create a Asc to Chr and Chr to Asc converter in the following Example:
In this example, we create two buttons, label one of them as ASC and the other one as
CHR. Insert two textboxes, one for the user to enter an ASC code and the other one to enter
the CHR character. When the user enter an ASC code, he or she can check for the
corresponding character by clicking the CHR button. Likewise, he or she can check the
corresponding ASC code after entering a character.
The Code
Private Sub CmdASC_Click()
TxtASC.Text = Asc(TxtCHR.Text)
End Sub
Private Sub CmdCHR_Click()
TxtCHR.Text = Chr(TxtASC.Text)
End Sub
35. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page35
Output
The String function
The String function has two arguments, a number and a single-character string, and
returns a string consisting of the specified character repeated the speficified number of times.
The syntax of the String function is:
String(n,"Character")
For example, String(30, "#") will return the # sign 30 times, as shown in the program below:
Private Sub Form_Load()
Form1.Show
Print String(30, "#")
End Sub
The output
36. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page36
The vbCrLf Named Constant
The vbCrLf named constant is a combination of two abbreviations Cr and Lf. Cr has
numeric code Chr(13) which represents carriage return and Lf has numeric code Chr(10)
which represents line feed. Carriage return means move the cursor to the left of the text field,
and line feed means move down one row in the text field. By combining Cr and Lf, vbCrLf
make it possible to display multiple lines in a text field such as in a message box, as shown in
the following example.
Private Sub Command1_Click()
Dim message As String
Dim display As String
message = "Mission to Mars"
display = String(30, "*") & vbCrLf & message & vbCrLf & String(30, "*")
MsgBox display
End Sub
The output
Performing Word Search
We can make use of various string functions to perform word search from a
textbox.In the following example, we insert a textbox and set the multiline property to true.
We also insert a textbox for the user to enter the word to search and a command button to
perform the search. Besides that, we also include a label control to display the result. In the
37. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page37
code, we use the set setFocus property to highlight the word found. In addition, we also use
the SelStart to set the starting point of text selected.
The Code
Private Sub cmdSearch_Click()
Dim n, m, l As Integer
Dim myAricle, myWord As String
myArticle = TxtArticle.Text
myWord = TxtWord.Text
l = Len(myWord)
n = InStr(1, myArticle, myWord)
If n = 0 Then
LblResult.Caption = "Your word not found, try again."
Else
LblResult.Caption = "Found your word " & myWord & " at " & " Position " & n
TxtArticle.SetFocus
TxtArticle.SelStart = n - 1
TxtArticle.SelLength = Len(myWord)
End If
End Sub
The Output
38. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page38
Date and Time Function
There are many useful functions for the date-time operations in VB6. Visual Basic
gives you enough power for handling the date and time.The functions that are defined in the
DateTime module of the VBA library. Search "DateTime" in Object Browser.
Weekday
The weekday function returns the day of the week. It returns a number representing the day.
Syntax
Variable = weekday(Date, [FirstDayOfWeek])
This function takes two arguments, one is the optional. You need to pass a date string to this
function, and the first day of week which is optional is set to vbSunday by default.
The constant values of FirstDayOfWeek paramenter are as follows:
vbSunday
vbMonday
vbTuesday
vbWednesday
39. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page39
vbThursday
vbFriday
vbSaturday
vbUseSystemDayOfWeek
Example
Print Weekday("1/4/2014")
Output
7
Year
The year function returns the year from the date.
Example
Print Year("1/4/2014")
Output
2014
Month
The month function returns the month of the year.
Example
Dim m As Integer
m = Month("27 / 3 / 2013")
MsgBox m
Output
3
DateValue
40. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page40
The DateValue function returns the date part from a date/time value.
Example
Dim dt As Date
dt = DateValue(Now)
Print dt
Output
1/4/2014
TimeValue
Returns the time part from a date/time value.
Example
Dim dt As Date
dt = TimeValue(Now)
Print dt
Output
12:51:25 PM
Day
Returns the day part from a date
Example
Dt = Day(Now)
Hour
Returns the hour of the day.
Example
Print Hour(Now)
41. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page41
Minute
Returns the minute of the hour.
Example
Print Minute(Now)
Second
Returns the second of the minute.
Example
Print Second(Now)
DatePart
Returns a specific part from a date.
Syntax
DatePart(Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear])
The interval parameter is the interval part of a date you want. Pass a date value through the
Date parameter. FirstDayOfWeek and FirstWeekOfYear are optional parameters, the values
of which are vbSunday and vbFirstJan1
Example
Print "year = " & DatePart("yyyy", "4/1/2014")
Print "month = " & DatePart("m", Now)
Print "day = " & DatePart("d", Now)
Print "week = " & DatePart("ww", Now)
Print "hour = " & DatePart("h", Now)
Print "minute = " & DatePart("n", Now)
Print "second = " & DatePart("s", Now)
42. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page42
Print "weekday = " & DatePart("y", Now)
The interval values can be:
"yyyy"-Year
"m"- Month
"d"-Day
"ww"-Week
"h"-Hour,
"n"-Minute
"s"-Second
"y"-weekday
DateSerial
Returns a Date for a specific year, month and day.
Example
Print DateSerial(2014, 1, 4)
TimeSerial
Returns a time for a specific hour, minute and second.
Example
Print TimeSerial(13, 15, 55)
DateDiff
Returns the number of time intervals between two dates.
Example
dt = DateDiff("d", "5 / 5 / 1990", "26 / 4 / 2013")
43. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page43
Numeric Functions
There are three numeric functions: SQR, INT, and Round
The Sqr function
The Sqr function returns the square root of a number. This function takes a Double type
argument and returns a Double implying that you can work with large numbers using the Sqr
function.
Example
Print Sqr(9)
Output: 3
The Int function
The Int function returns the greatest integer less than or equal to the number. It discards the
decimal part of a number.
This function greatly helps in truncating the decimal part of a number. But be aware that in
case of a negative decimal number, it returns a rounded up value, resulting in an increment of
integer part as it's shown in example 3 below.
Example
Print Int(2.9)
Output: 2
Example
Print Int(5)
Output: 5
Example 3
Print Int(-5.8)
Output: -6
44. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page44
The Round function
The Round function rounds a numeric value.
Syntax
Round(Number, [no. of digits after decimal]
If the second parameter is omitted, the number is rounded to a whole number.
Example
Print Round(5.8)
Output: 6
Example
Print Round(5.8, 1)
Output: 5
Example
Print Round(5.4568, 2)
Abs
It returns the absolute value of a number.
Example
Private Sub Form_Load()
Form1.Show
Print abs(-10)
End Sub
Output
10
45. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page45
Sin, Cos and Tan
These functions return the sine, cosine and tangent of an angel. These functions receive
arguments in radian. Convert radian to degree multiplying Pi/180. You may declare a Pi
constant at the beginning.
Example
Private Sub Form_Load()
Form1.Show
Print Sin(90)
Print Cos(0)
Print Tan(45)
End Sub
Output
0.893996663600558
1
1.61977519054386
Exp
The Exp function returns e (the base of natural logarithms) raised to a power.
Example
Private Sub Form_Load()
Form1.Show
Print Exp(5) 'equivalent to e^5
End Sub
Output
148.413159102677
46. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page46
Log
The Log function returns the natural logarithm of a number.
Example
Private Sub cmdPrint_Click()
Print Log(10)
End Sub
Output
2.30258509299405
Sgn
This function indicates the sign of a number. It returns -1, 0 or 1 if the number is negative,
zero or positive respectively.
Example
Private Sub cmdShowSign_Click()
Print Sgn(-10)
End Sub
Output
-1
The Fix function
Fix function truncates the decimal part of a number. In Lesson 34, you have seen that
the Int function also truncates the decimal part of a number. But this function is different
from the Fix function. You see the difference when the number is negative in case of the Int
function. So the function that actually truncates the decimal part of a number is Fix.
Example
Private Sub cmdTruncate_Click()
47. D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page47
Print Fix(4.5)
Print Fix(-4.5)
End Sub
Output
4
-4
The Rnd function
Sometimes, we need to generate some random values. The Rnd function returns a
random value between 0 and 1.
Example
Each time the CommandButton is clicked , it gives a different value between 0 and 1.
Private Sub cmdGenerateRandomNumbers_Click()
Randomize() 'Randomizes the number
lblResult.Caption = Rnd
End Sub
Output