Vous êtes sur la page 1sur 73

Date-Time

6793

Visual Basic 6 Tutorials


The small and concise lessons of this VB6 tutorial site will help you learn the
Visual Basic 6.0 language most effectively, and the sample programs given in the
lessons enable practical learning so that you can achieve the potential to
develop your own software.

Table of Contents:Lesson 1: Introduction


Lesson 2: Starting Visual Basic
Lesson 3: The Integrated Development Environment
Lesson 4: An overview of VB controls
Lesson 5: Your first Visual Basic program
Lesson 6: Concept of event driven programming
Lesson 7: Variables and data types
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson

8: Scope of a variable
9: Operators & expressions
10: How to make an executable(.exe) file
11: Naming Conventions
12: Common properties
13: Label & TextBox
14: The CommandButton control
15: Input and Output operations
16: Data type conversion
17: If Blocks
18: Nested If-Else
19: Select Case blocks
20: Do Loops
21: For...Next Loops
22: OptionButton & Frame
23: The CheckBox Control
24: Graphical style of OptionButton & CheckBox
25: Image & PictureBox
26: Common events

Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson
Lesson

27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:

Control flow functions


Form Templates
The Form events
Mouse Hover effect
Line & Shape
Important methods
The Object Browser
Numeric Functions
Formatting Functions
String Concatenation
String functions
Working with date and time
Data inspection functions
The ListBox Control
Multiple selection feature of the listbox control
The ComboBox Control
Scroll bars
DriveListBox, DirListBox & FileListBox
Fixing the overflow error
Animation - The Timer Control
Working with numbers
Named constants
Date-time functions
Array
Multi-dimensional arrays
Dynamic Array
Control Array
Collection [Part 1]
Collection [Part 2]
Using the data types [Part 1]
Using the data types [Part 2]
User-Defined Type (UDT)
Sub Procedures [Part 1]
Sub Procedures [Part 2]
Function Procedures
Menus
Popup Menu
Using multiple forms
Splash screen
MDI forms
The Screen Object
Standard BAS module
Validation
Error Handling
The Clipboard Object

Like my facebook page:


www.facebook.com/vbtutes for free updates!

Functions
Lesson 49

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

There are many useful functions for the date-time operations in VB6.
Visual Basic gives you enough power for handling the date and time. Here
youll learn about those functions in brief.
This post will include 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
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
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)

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)
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")
The first argument is the interval which can have the value among the
interval constants mentioned above.
Related topics:

Working with date and time

Formatting functions

Using the data types - Part 1

Using the data types - Part 2

Like my facebook page: www.facebook.com/vbtutes for free updates!


<<Previous Lesson
Newer Post Older Post Home

<<Table Of Contents>>

Next Lesson>>

Main Menu

Home

Visual Basic 6 Tutorials

VB6 Code Samples

Visual Basic 2010 Samples

Blog

Blog Articles
6 Effective Ways to Learn Visual Basic
Programming with Visual Basic for a Living
Guide to Good Programming Habits
Comparison between VB6 and VB.NET
5 Reasons Why VB is a Good Choice for Making Business Solutions

Google+ Followers
Get weekly updates
Email Address

Subscribe

xml search
Array in Visual Basic 6

Lesson 50
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

An array is a collection of items of the same data type. All items have the same
name and they are identified by a subscript or index. When you need to work

with several similar data values, you can use array to eliminate the difficulties of
declaring so many variables. For example, if you want to compute the daily
sales and sum the sales amount after 30 days, you don't need to have 30
variables. Just simply declare an array of size 30 and get your work done !

Declaring an array
Syntax: Dim Variable_Name(index) As [Type]

Example:
Dim month(10) As Integer '11 elements
'or
Dim month(1 to 12) as Integer '12 elements
In the first line, month(10) is a collection of 11 integer values or items.
month(0) is the 1st item and month(10) is the 10th & last item of the array. So
0 and 10 are respectively the lower bound and upper bound of the array.
In the other line, month(1 to 12) is a collection of 12 integer values or elements
or items where month(1) is the 1st item and month(12) is the last. So 1 and 12
are respectively the lower bound and upper bound of the array.

Types of array
The array used in the example is a one-dimensional and fixed-size array. An
array can have more than one dimension. The other types of arrays are multidimensional arrays, Dynamic arrays and Control arrays.

Fixed-Size Array: We know the total number of items the array in the above
example holds. So that is a Fixed-Size array.

The LBound and UBound functions

The LBound and Ubound functions return the lower bound and upper bound of
an array respectively.

Example:
Private Sub cmdDisplay_Click()
Dim arr(10) As Integer
a = LBound(arr)
b = UBound(arr)
MsgBox "Lower bound = " & a & " Upper bound = " & b
End Sub

Initializing an array
You can use For Loop to initialize an array.

Example:
Dim day(10) As Integer, i As Integer
For i = 0 To 10
day(i) = InputBox("Enter day value")
Next i

You can also initialize each array item separately in the way a variable is
initialized.

Example: This program inputs the Sale amount of each day and sums the total
amount of 5 days.
Private Sub cmdStart_Click()
Dim SaleDay(1 To 5)
'Sale in a particular day
Dim i As Integer, Sale As Long
Sale = 0
For i = 1 To 5
SaleDay(i) = InputBox("Enter Sale amount of Day " & i)
Sale = Sale + SaleDay(i)

Next i
MsgBox "Total Sale of 5 days = $" & Sale
End Sub

Related topics:

Multi-dimensional array

Dynamic array

Control array

Collection

Multi-Dimensional Arrays
Lesson

51
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

An array can be multi-dimensional that means, it can have more than one
dimension. A list of data is represented in a one-dimensional array where a
multi-dimensional array represents a table of data. An array can be two
dimensional, three dimensional and so on. We generally don't need an array of
more than two dimensions, it is enough to use one and two dimensional arrays.
You can use a higher dimensional array when the program is too complex. A two
dimensional array takes the row-column form.
Declaration:
Dim value(5, 5) As Integer
'two dimensional
'Or,
Dim value(1 to 5, 1 to 5) As Double
Dim number(6, 9, 8) As Integer 'three dimensinoal

Initialization:
To initialize the array elements, you first need to recognize the array elements.
For example, the array 'value(2, 2)' has 9 elements. They are value(0,0),
value(0,1), value(0,2), value(1,0), value(1,1), value(1,2), value(2,0),
value(2,1), value(2,2). For the initialization, you may wish to use For Loop or

initialize each element like variables. Using For Loop is a better choice as it
reduces the number of lines of code. But sometimes, separately initializing each
element like a variable is much more convenient. And it also depends on the
type of program you are writing .

Addition of 2D matrices : Example of


a two dimensional array
Example:
Private Sub cmdSum_Click()
Dim matrix1(1, 1) As Integer, matrix2(1, 1) As Integer
Dim sum(1, 1) As Integer
'initializiation of matrix1
matrix1(0, 0) = Val(Text1.Text)
matrix1(0, 1) = Val(Text2.Text)
matrix1(1, 0) = Val(Text3.Text)
matrix1(1, 1) = Val(Text4.Text)
'initializiation of matrix2
matrix2(0, 0) = Val(Text5.Text)
matrix2(0, 1) = Val(Text6.Text)
matrix2(1, 0) = Val(Text7.Text)
matrix2(1, 1) = Val(Text8.Text)
'Summation of two matrices
For i = 0 To 1
For j = 0 To 1
sum(i, j) = matrix1(i, j) + matrix2(i, j)
Next j
Next i
'Displaying the result
Print "The resultant matrix"
For i = 0 To 1
For j = 0 To 1
Print sum(i, j);
Next j
Print ""

Next i
End Sub

Sample program:

Matrix Addition

Related topics:

Array

Control array

Dynamic array

Collection

Dynamic Array
Lesson

52
<<Previous Lesson <<Table Of Contents>> Next Lesson>>

In case of a fixed size array, we have seen that the size of the array is fixed or
unchanged, but there may be some situations where you may want to change
the array size. A dynamic array can be resized at run time whenever you want.

Declaring dynamic arrays


1. Declare the array with empty dimension list.
Example : Dim arr() As Integer
2. Resize the array with the ReDim keyword.
Example : ReDim arr(5) As Integer
or, ReDim arr(2 To 5) As Integer
Example:
Dim ar() As Integer
ReDim ar(2) As Integer

Note: Unlike the Dim and Static statements, the ReDim statements are
executable. So a ReDim statement can only be in a procedure and when you
execute the ReDim statement, all the values stored in the array are lost. You can
use the ReDim statement repeatedly to change the array size.

Preserving the values of Dynamic


arrays
The ReDim statement deletes all the values stored in the array. You can preserve
the element values using the Preserve keyword. So using Preserve keyword with
ReDimstatements enables you to change the array size without losing the data in
the array.
Example:
Dim arr() As Integer
ReDim arr(2) As Integer
For i = 0 To 2
arr(i) = InputBox("Enter the value")
Next i
ReDim Preserve arr(3) As Integer
arr(3) = 9
Print arr(0), arr(1), arr(2), arr(3)
Output: If the input values through InputBox are 5,6,7 then the following will be
printed on the form.
5
6
7
9

Related topics:

Array

Multi-dimensional array

Control array

Collection - part 1

Collection - part 2

User-define type (UDT)

Dynamic Array
Lesson

52
<<Previous Lesson <<Table Of Contents>> Next Lesson>>

In case of a fixed size array, we have seen that the size of the array is fixed or
unchanged, but there may be some situations where you may want to change
the array size. A dynamic array can be resized at run time whenever you want.

Declaring dynamic arrays


1. Declare the array with empty dimension list.
Example : Dim arr() As Integer
2. Resize the array with the ReDim keyword.
Example : ReDim arr(5) As Integer
or, ReDim arr(2 To 5) As Integer
Example:
Dim ar() As Integer
ReDim ar(2) As Integer
Note: Unlike the Dim and Static statements, the ReDim statements are
executable. So a ReDim statement can only be in a procedure and when you
execute the ReDim statement, all the values stored in the array are lost. You can
use the ReDim statement repeatedly to change the array size.

Preserving the values of Dynamic


arrays

The ReDim statement deletes all the values stored in the array. You can preserve
the element values using the Preserve keyword. So using Preserve keyword with
ReDimstatements enables you to change the array size without losing the data in
the array.
Example:
Dim arr() As Integer
ReDim arr(2) As Integer
For i = 0 To 2
arr(i) = InputBox("Enter the value")
Next i
ReDim Preserve arr(3) As Integer
arr(3) = 9
Print arr(0), arr(1), arr(2), arr(3)
Output: If the input values through InputBox are 5,6,7 then the following will be
printed on the form.
5
6
7
9

Related topics:

Array

Multi-dimensional array

Control array

Collection - part 1

Collection - part 2

User-define type (UDT)

Control Array
Lesson

53
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Till now we have discussed array of variables. Similarly you can also have an
array of controls by grouping a set of controls together. The controls must be of
the same type like all TextBoxes or all CommandButtons.

Creating control arrays


1.Place some same type of controls say CommandButtons on the form. Make
their name properties same and then a warning (see picture below) dialog box
will come asking whether you want to create a control array, click Yes.

Or, after placing a control on the form, copy that and paste on the form. It will
create control array for you.
2. Set the Index property of each control or you may not change as it is
automatically set.
3. Now its done. You are ready to use the control array in your code.

Using control array


Syntax to refer to a member of the control array :
Control_Name(Index).Property
Example: Set the Style property of Command1(1) to 1 to work with the
BackColor property.
Private Sub Command1_Click(Index As Integer)
Command1(1).BackColor = vbGreen
End Sub
Example: Create a control array of 5 CommandButton controls and then set
their Style property to 1.
Private Sub Command1_Click(Index As Integer)
Dim i As Integer
For i = 0 To 4

Command1(i).BackColor = vbBlue
Next i
End Sub
You can also pass a value to the Index parameter from other procedures.
Control array is useful when you want to clear a set of TextBox fields. Create a
control array of 5 TextBox controls and write the following code in the Click
event procedure of a CommandButton control.

Example:
Private Sub cmdClearAllFields_Click()
Dim i As Integer
For i = 0 To 4 'Or, For i=Text1.LBound To Text1.UBound
Text1(i).Text = ""
Next i
End Sub
Output:

Sharing Event procedures


Create a control array of some command buttons with the name "Command1".
Note that Visual Basic automatically passes the Index parameter value. So the
following code will work for all controls in the control array. You don't need to
write code for all the CommandButton controls. Click on any CommandButton,
the following single block of code will work for all.

Example:

Private Sub Command1_Click(Index As Integer)


Command1(Index).BackColor = vbBlack
End Sub

Creating controls at run-time


Once you have created a control array, you can create controls at run-time using
the Load command.

Example: First of all, create Text1(0) and Text1(1) at design time.


Private Sub Command1_Click()
Load Text1(2)
'Move the control where you want
Text1(2).Move 0, 100
Text1(2).Visible = True
End Sub
On clicking the Command1 button, a new TextBox control will be created.
You can remove any control from the control array using the Unload command.
Unload Text1(2)

Related topics:

Array

Multi-dimensional array

Dynamic array

Collection - part 1

Collection - part2

User-defined type

Collection [Part 1] in Visual Basic 6

Lesson 54
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Collections are objects in Visual Basic that are used to store a group of data
values. Collections are similar to array. But there are some special features that
differentiate the collections from arrays.
We have seen that array elements must be of the same data type. But the
Collection members can be of any data type and you don't need to set the size
of the Collection object. You can easily add items to the collection and it will
grow accordingly.

Creating a Collection
To use a Collection in your code, you first need to declare and create it.
Example:
Dim names As Collection
'Declaring the Collection
Set names = New Collection 'Creating the Collection

Or, replace the above code with this one line code
Dim names As New Collection

'Declaration and creation

Adding items to a Collection : The


Add method

You can add one item at a time using the Add method.
Example:
Dim names As New Collection
names.Add "john"
names.Add "david"

You may use a string key associated with the item. The string key is used to
refer to a Collection item.
Dim names As New Collection
names.Add "John", "one"

' "one" is the string key, used to refer to the item

Retrieving item values : The Item


method
You can refer to a particular item of the collection using the Item method. Here
you may use either the index or key value. The index value starts from 1.
Syntax : Collection_Name.Item(Index)
or,
Collection_Name.Item(Key)
Example: Retrieving a particular item using the index of the item
Private Sub cmdShow_Click()
Dim names As New Collection
names.Add "John", "one"
names.Add "David"
Print names.Item(2) '2 is the index of the item
End Sub
Output: David
Example: Retrieving a particular item using the string key of the item

Private Sub cmdShow_Click()


Dim names As New Collection
names.Add "John", "one"
names.Add "David"
Print names.Item("one")
End Sub
Output: John
The Item method is the default member of the Collection class, so you may omit
it in your code.
Example:
Private Sub cmdShow_Click()
Dim names As New Collection
names.Add "John", "one"
names.Add "David"
Print names("one")
Print names(2)
End Sub
Output:
John
David

Related topics:

Array

Multi-dimensional array

Dynamic array

Control array

User-defined type

Collection [Part 2] - Visual Basic 6


Lesson

55
<<Previous Lesson <<Table Of Contents>> Next Lesson>>

Using the Before and After argument


of the Add method
You can choose to store the item values exactly where you want using the
Before and After argument of the Add method.
Example:
Private Sub cmdShow_Click()
Dim items As New Collection
items.Add "one"
items.Add "two"
items.Add "three", , 1
For i = 1 To 3
Print items.Item(i)
Next i
End Sub
Output:
three
one
two

Removing an item : The Remove


method

You can remove a particular item from the Collection using the Remove method.
Example:
Private Sub Command1_Click()
Dim country As New Collection
country.Add "USA"
country.Add "UK"
country.Add "Japan", "j"
country.Remove (1)
country.Remove ("j")
End Sub

Number of items in a Collection :


The Count method
Example:
Private Sub cmdCount_Click()
Dim country As New Collection
country.Add "USA"
country.Add "India"
country.Add "Japan", "j"
Dim n As Integer
n = country.Count
Print n
End Sub
Output: 3

Retrieving the last item


Example:

Private Sub Command1_Click()


Dim country As New Collection
country.Add "Germany"
country.Add "India"
country.Add "China", "j"
Print country.Item(country.Count)
End Sub
Output: China

Deleting all items from the Collection


Use a Do While loop to delete all item from the Collection object.
Example:
Private Sub cmdDeleteAll_Click()
Dim country As New Collection
country.Add "Bangladesh"
country.Add "Australia"
country.Add "Russia", "j"
Do While (country.Count > 0)
country.Remove 1
Loop
Print country.Count
End Sub
Output: 0
Another way to delete all items is to destroy the Collection object. The following
code destroys the Collection object and thus deletes all the items.
Set items = Nothing
'Or,
Set items = New Collection

Related topics:

Array

Multi-dimensional array

Dynamic array

Control array

User-defined type

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson
Using the data types [Part 1]
Lesson

<<Table Of Contents>>

Next Le

56
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Visual Basic 6 is rich in data type. So you should know the usage of all the data
types to make a powerful application.

Integer values
Among the data types for storing integer values, Integer is the most used data
type for its efficiency. But sometimes you may use the Long data type instead of
Integer especially when you want to reduce the overflow error as it can hold a
very large value, from -2,147,483,648 to 2,147,483,647 where an Integer can
only store a value from -32,768 to 32767.
For small integer values, use the Byte data type, the value range is from 0 to
255 only in this case.

The Boolean Data Type

The Boolean variables stores only 0 and 1 that stand for False and True
respectively. To use a Boolean variable in your code, firstly declare the variable
as Boolean and then assign a True/False value.
Example:
Private Sub cmdCheck_Click()
Dim TextOff As Boolean 'Declaring the variable

'Assigning value
If Text1.Visible = False Then
TextOff = True
End If
'Using the Boolean variable
If TextOff = True Then
MsgBox "TextBox is hidden"
Else
MsgBox "TextBox is shown"
End If
End Sub
Output:

Floating point values


Single and Double are the mostly used data types. For small decimal values, use
the Single data type and Double for large values. Decimal is a floating point data
type. The Decimal data type is higher in precision and lower in range compared
to Double. In case of Decimal data type, you can't explicitly declare it (As
Decimal). To use it, convert a value to Decimal data type with the CDec function
and assign it to a variant.

Example: The Decimal Data Type

Dim num As Variant


expr = 22.45 * 5.987
num = CDec(expr)

Related topics:

Variables and data types

User-defined types (UDT)

Like my facebook page: www.facebook.com/vbtutes for free updates!


Using the data types [Part 2] - Visual Basic 6
Lesson

57
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

The String Data Type


String data types can be variable length or fixed-length. When you know the
length of your string value, you may use the fixed-length data type. But
remember that variable length strings are faster than the fixed-length strings.
Example:
Dim s As String
Dim s1 As String * 10

'variable length string


'fixed-length string

The fixed-length string in the above example takes 10*2=20 bytes memory
space.

The Currency Data Type

The value range of a Currency data type from -922,337,203,685,477.5808 to


922,337,203,685,477.5807. Currency values always include 4 decimal digits.
This data type is used for storing monetary values.

The Date Data Type


The Date data types are useful in the sense that they can be used to perform
math operations on date values. You can truncate, add or subtract the date
values. You first need to assign the date value to a variable for that.

Example:
Private Sub cmdShow_Click()
Var = Now
Var = Var + 14 '14 days from today
Print Var
End Sub

The Object Data Type


Visual Basic is fully an object-based programming language. So Object data type
plays a very important role in the language. The Object data type is used to
store a reference object. There are several objects in visual basic like forms,
textbox, database and so on.
You first need to declare the object variable and then assign an object reference
to the object variable using the Set keyword.

After assigning, you can use the object variable to access the properties and
methods of the original object.

Example:
'Declaration
Dim frm As Form

Dim txt As TextBox


'Assign object reference
Set frm = Form1
Set txt = Text1
'Using object variable to access the original object
frm.BackColor = vbGreen
txt.Text = "hello world"

Clearing a group of TextBox controls


Create a control array of text boxes with the name "Text1" and then write the
following code.

Example:
Private Sub cmdClear_Click()
Dim field As TextBox 'Declaring as Object
For Each field In Text1 'Text1 is a control array
field.Text = ""
Next
End Sub

This is just a brief discussion on Object data type. You'll learn more later in the
tutorial.

Related topics:

Variables and data types

User-defined types (UDT)

Like my facebook page: www.facebook.com/vbtutes for free updates!

User-Defined Type (UDT)

Lesson 58
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

User defined type in Visual Basic 6 is a compound data structure. It holds several
variables of different data types. After defining a UDT, you can assign values to
the member variables of the UDT.

Defining the user defined type


Before using the UDT in your code, you must first define it using the Type
directive in the Declarations section of a module, for example, a form module.
The following block of code is called the Type structure.
Example:
Private Type BookDetails
title As String
author As String
pages As Long
End Type

'in Declarations section

After defining the UDT variable, declare variables of that type.

Assigning values
Private Sub cmdSetValue_Click()
Dim book1 As BookDetails 'Declaring book1 as the type
'BookDetails

'Assigning values
book1.author = "Balagurusamy"
book1.title = "C Programming"
book1.pages = 600
End Sub

The "With...End with" structure


Use "With...End with" structure for the better readability of your code. It eases
up the structure.
Example:
Dim book1 As BookDetails
With book1
.author = "Balagurusamy"
.title = "C Programming"
.pages = 600
End With
With book1
Print .author, .pages, .title
End With

Sub structure of a user defined type


The Type structure can also have sub structures. In this case, you have to access
the nested structure using the nested "With...End With" structure.
Example:
'Sub structure of UDT
Private Type AddressDetails
city As String
state As String
pin As Long

ph_no As String
End Type
Private Type StudentDetails
name As String
stream As String
DepartmentId As String
address As AddressDetails
End Type
__________________________________________________________
Private Sub cmdSetDetails_Click()
Dim student1 As StudentDetails
'Nested With...End With structure
With student1
.name = "XYZ"
.stream = "Computer Science"
.DepartmentId = "C900"
MsgBox .name & vbTab & .stream & vbTab & .DepartmentId
With .address
.city = "London"
.state = "abc gdf"
.pin = 77764
.ph_no = "998765432"
MsgBox .city & vbTab & .ph_no & vbTab & .pin & vbTab _
& .state
End With
End With
End Sub

Sample program: Student Details

Related topics:

Array

Multi-dimensional array

Control array

Dynamic array

Collection - part 1

Collection - part 2

Using the data types - part 1

Using the data types - part 2

Variables and data types

Like my facebook page: www.facebook.com/vbtutes for free updates!


Sub Procedures [Part 1]

Lesson 59
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Read Lesson 8 : Scope of a Variable before staring this lesson.


As we have discussed in lesson 8, that procedures are of three types :
1. Sub Procedure,
2. Function Procedure,
3. Property Procedure.

The Property Procedure will be explained later in the tutorial.


Again Sub Procedures are of two types :
a. Event Procedure,
b. General Procedure.

Every procedure has a unique name, a scope and a list of arguments. The
function procedure, in addition, has a return value. Sub procedure and property
procedure does not return value.

Scope of a procedure
A procedure can be Private, Public or Friend. You can invoke a Private procedure
only from within the module. A Public procedure can be called from anywhere of
the current project -- from within the module, from other modules of your
application project, and in some cases from outside the program using COM. And
a friend procedure can be called from anywhere of the current project but not
from outside.

Understanding the Event Procedure


An event procedure does not return any value and you can call it from other
procedures of the module. The procedure is called using the Call command.
Example:
Private Sub Command1_Click()
Call Command2_Click
End Sub
____________________________________________________________
Private Sub Command2_Click()
Print "hello"
MsgBox "hello"
End Sub

So if you click the Command1 button, the Command2_Click event procedure is


called, and the lines of code inside it are executed.
You may omit the Call command while calling a procedure.
Example:
Private Sub Command1_Click()
Command2_Click
End Sub
__________________________________________________________
Private Sub Command2_Click()

MsgBox "hello"
End Sub

Public event procedure


Example: Place a CommandButton on Form1. Now add a new form from the
menu : Project > Add Form > Form. Place a CommandButton on Form2.

'In Form1
Private Sub Command1_Click()
Call Form2.Command1_Click
End Sub

'In form2
Public Sub Command1_Click() 'Scope is Public
MsgBox "You have called a procedure of form2"
End Sub
When you'll click the CommandButton on Form1, Command1_Click procedure of
the form2 module will be called. As the scope of the procedure in Form2 is
Public, the procedure is accessible from anywhere of the current project, and if
the procedure is Private, the procedure cannot be invoked from other modules.
In the Form2 module, if you change the procedure scope to Private, it can then
only be called from the Form2 module. This aspect will be clearer when you'll
learn about working with multiple forms in the next lessons.

Related topics:

Sub procedures - part 2

Function procedures

Standard BAS module

Scope of a variable

Like my facebook page: www.facebook.com/vbtutes for free updates!

Sub Procedures [Part 2]

Lesson 60
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Understanding the general sub


procedure
General sub procedure can be very useful when you want to use a block of code
repeatedly in your program. Instead of writing the same lines of code again and
again, define a General SubProcedure, and call it where you need. These
procedures do not return values.
Say you need to print some lines of text again and again. So define a general
sub procedure xprint , and call it wherever in the program its necessary.
Note: Public is the default scope for procedures, so you may omit it.
Example:
Sub txt()
MsgBox "welcome"
End Sub

Example:
Private Sub Command1_Click()
Call xprint
'Function calling
End Sub
___________________________________________________________
Private Sub xprint() 'Function Definition
Print "Hello World"
Print "";
Print "*****"
Print "New"

End Sub
___________________________________________________________
Private Sub Command2_Click()
Call xprint
'Function calling
End Sub

Using sub procedures in your code is a good programmer's habit. Because it


reduces the number of lines of code. Besides, a large complex program becomes
very easy and comprehensive when you use your own sub procedure in the
code.
You can change the scope to Public when you want to access the procedure from
outside the module.

Public general sub procedure


Add a new form from menu : Project > Add Form > Form. Public general sub
procedures are useful when want to invoke your procedure from wherever you
want, from any module.
Example:
'In Form1
Private Sub Command1_Click()
Call Form2.xprint
End Sub

'In form2
Public Sub xprint()
Form2.Show
Print "Hello World !"
Print "";
Print "***"
Print "New"
End Sub
_____________________________________________________________
Private Sub Command1_Click()

Call xprint
End Sub
The concept of Public general sub procedure will be clearer to you when you'll
learn about working with multiple forms in the next chapters.

Related topics:

Sub procedures - Part 1

Scope of a variable

Function procedures

Standard BAS module

Like my facebook page: www.facebook.com/vbtutes for free updates!


Function Procedures

Lesson 61
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

A function procedure in Visual Basic 6 has a scope, a unique name, parameter


list and return value. You can pass any datatype to a procedure e.g Integer,
Boolean, Long, Byte, Single, Double, Currency, Date, String and Variant. Object
data types and arrays are also supported. This is same for the return type
values.

Difference between argument and


parameter
The value you're passing, while calling the function, is called argument and the
variable, in the function definition, that will receive the value is called parameter.

Both the terms are used for the same value.


A function procedure may not return a value.
Example: In this example, 32 and 54 are passed to the function 'sum' from
Form_Load procedure.
'Function Definition
Private Function sum(n1 As Integer, n2 As Integer) 'n1, n2 are 'parameters
Text1.Text = n1 + n2
End Function
________________________________________________________________
__
Private Sub Form_Load()
Text1.Text = ""
'Function callgin
Call sum(32, 54)
End Sub

'32 and 54 are arguments

Output:

Function procedure that returns


value
Example:
'Function Definition
Private Function sum(n1 As Integer, n2 As Integer) As Integer
'Returns a value
sum = n1 + n2

End Function
____________________________________________________________
Private Sub Form_Load()
Text1.Text = ""
'Function calling and assigning the returned value
Text1.Text = sum(60, 40)
End Sub

Passing arguments: By Value or By


Reference
You can pass an argument either by value or by reference. Arguments are
passed by value using the ByVal keyword and by reference using the ByRef
keyword or by omitting any specifier.
While passing the arguments by reference, references of the variables are
passed. So if the argument is passed by reference, it can be modified by the
called procedure and the original value of the argument in the calling procedure
will be changed. But the argument value will be unchanged if you call the
procedure using constants or expressions as parameters.
Example:
'Calling procedure
Private Sub Command1_Click()
Dim a As Integer
'The value of a is 0 after declaration
Call num(a)
Print a 'Value of a is 1, modified
End Sub
________________________________________________________________
___
'Called procedure
Public Function num(ByRef x As Integer) 'You may omit ByRef
x=x+1
End Function

On the other hand, when the arguments are passed by value, the actual values
are passed. So the called procedure cannot change their original values in any
way.
Example:
'Calling procedure
Private Sub Command1_Click()
Dim a As Integer 'The value of a is 0 after declaration
Call num(a)
Print a 'The value of a is 0, its unchanged
End Sub
________________________________________________________________
___
'Called procedure
Public Function num(ByVal x As Integer)
x=x+1
End Function

Note: Both Sub and Function procedures can accept parameters.

Related topics:

Sub procedures - Part 1

Sub procedures - Part 2

Standard BAS module

Scope of a variable

Like my facebook page: www.facebook.com/vbtutes for free updates!


How to Add a Menu to Your VB6 Program

Lesson 62
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Menus are one of the most important features of a software product. Every
standard software must have menus. You generally see a menu on top of a
software interface. Menus are controls but different from the controls in the
ToolBox and they don't work like the other controls. You can drop a menu on the
form from the Menu Editor Window. Press Ctrl+E to show the Menu Editor
Window or right-click on the form and click Menu Editor. The Menu Editor
Window can also be shown from the Menu Editor icon of the ToolBar.

Building a menu
Building a menu is very simple, you can do it on your own. Simply fill the
Caption and Name field in the Menu Editor Window and click ok to create it.

Click the right-arrow button to create a submenu. Click Next to create the next
menu item, and click ok once you're done editing the menu items.

A simple form with menu:

Properties of the menu items


The important properties of the menu items are Name, Caption, Checked,
Enabled, Shortcut and Visible. As per your programming need, set the properties
either in run-time or in design time. You can create a shortcut key for a menu
item. In some situations you may want to disable a menu item, you can acquire
it through the Enabled property.
The menu control exposes only one event, the Click event.

Example: Make a menu as same as the following image.

Now write the following code.


Private Sub mnuBlue_Click()
Form1.BackColor = vbBlue 'Makes the Form blue
End Sub
______________________________________________________________
Private Sub mnuGreen_Click()
Form1.BackColor = vbGreen 'Makes the form green
End Sub
______________________________________________________________
Private Sub mnuRed_Click()
Form1.BackColor = vbRed 'Makes the form red
End Sub
______________________________________________________________
Private Sub mnuWhite_Click()
Form1.BackColor = vbWhite 'Makes the form white
End Sub

Now run the program and Click on the menu items and see what happens.

The Checked property


Design a form like the output image of the following program. Create a Help
menu and drop a Label control on the form with the caption 'Help'.
Now write the following code.
Private Sub mnuShowHelp_Click()
If mnuShowHelp.Checked = True Then
mnuShowHelp.Checked = False
Label2.Visible = False
ElseIf mnuShowHelp.Checked = False Then
mnuShowHelp.Checked = True
Label2.Visible = True

End If
End Sub
Output:

Related topics:

Popup menu

CheckBox control

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson
Visual Basic 6 Popup Menu

<<Table Of Contents>>

Next Lesson>

Lesson 63
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Most of the commercial software products have popup menus as they can make
the application more user-friendly and powerful. When you right click on
windows desktop, a popup menu appears. Visual Basic 6.0 provides a Popup

menu method that you can use in your program to show the popup menu on the
form's surface.
To use the Popup menu method, you first need to create a menu. For example,
create a menu with the name "View". See the example given below.

The PopupMenu method


Syntax:
PopupMenu Menu, [Flags], [X], [Y], [DefaultMenu]
Note: Arguments in [ ] brackets are optional.
Now write the following code in the form's MouseDown event to invoke the
popup menu.
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y
As Single)
If Button = vbRightButton Then
PopupMenu mnuView 'PopupMenu is a method
End If
End Sub

If you need only the popup menu but not the menu bar, set the Visible property
of the menu control to False in design time.
Sample: Colors PopUp
Related topic:

How to add a menu to your VB6 program

Like my facebook page: www.facebook.com/vbtutes for free updates!


Using Multiple Forms
Lesson

64
<<Previous Lesson

<<Table Of Contents>> Next Lesson>>

In Visual Basic 6, a windows application may have more than one window. Most
of the windows applications contain several windows. You can make a multiple
windows software by adding some forms to your project as because forms are
nothing but the windows of the final product.

Adding a form to your existing


project
To add a form, go to Project >Add Form from the menu bar of the IDE. A window
will appear to choose a form template.

You may change the Name property of the added form for your advantage.
Remember, the forms are considered as objects.

Showing a form
You can show the newly added form using the Show method.
Syntax:
Form.Show [Modal], [Owner form]
[Modal] means whether the form is modal or not. A modal form forces you to
stay on the form until you close it or enter some data. You may have noticed this
kind of form in several windows programs.

[Owner form] constant determines which form to be set as the owner form.
Example:
Form2.Show
or, Form2.Show vbModal
or, Form2.Show vbModeless
or, Form2.Show vbModal, Form1

Example:
'in Form1
Private Sub cmdShowForm2_Click()
Form2.Show vbModal
End Sub

'in Form1
Private Sub cmdShowForm2_Click()
Form2.Show
Unload Me 'unloads the current form
End Sub

Unloading a form

'in Form1
Private Sub cmdUnloadForm2_Click()
Unload Form2
End Sub
You can also use the Hide method.

Example:
Form2.Hide

When you unload a form, it releases the memory which was allocated for the
form. But the Hide method only hides the form, it doesn't unload it from the
memory.

Controlling a form from another form


You can change the properties of another form.

Example:
'in Form1
Private Sub Command1_Click()
Form2.BackColor = vbBlue
End Sub

You can even set the controls' properties which are on another form.

Example:
'in Form1
Form2.Text1.Text = "Welcome!"

Sample: Login System

In the next lesson, you'll learn about the splash screen which is a special form
template.

Related topics:

MDI forms

Splash screen

Standard BAS module

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson

57

Google +

<<Table Of Contents>> Next Lesson>>

49

Lesson 65
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

You can use splash screen in your windows app to make the program more
attractive. The splash screen is a form template which you should set to appear
before the main window or the actual program appears. This screen only stays
for some second showing the company name, logo, product name, product
version, copyright information and some other information.
Example:

How to make a splash screen


1. You can choose from the default template. Go to Project >Add Form from
the menu bar and select splash screen. Then modify the form as per your
needs.
2. The other way is, add a form to your existing project. Set the BorderStyle
property to None. Then edit the form according to your choice.

Working with the splash screen


1. Take a timer on the splash screen form. Set the interval to some seconds,
for example 3 seconds. Then you need to set the Timer's Interval property
to 3000.
2. Write the following code in the Timer's Timer Event. Suppose the form you
want to load after the splash screen is frmMain.

Private Sub Timer1_Timer()


Timer1.Enabled = False
frmMain.Show
Unload Me
End Sub

On executing the code, the splash screen stays for 3 seconds and then the Main
Window is shown after the splash form is unloaded.

Related topics:

Using multiple forms

MDI forms

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson
MDI Forms in Visual Basic 6

<<Tab

Lesson 66
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Today I'll share my knowledge of MDI forms with you. In the previous lessons
you've learned about forms -their properties, events and methods. The concept
of form is very vast, so many things have been discussed, and many things are
yet to be discussed.

What is an MDI form?


MDI stands for Multiple Document Interface. You have probably seen many MDI
applications. When you want to handle multiple documents simultaneously, MDI
forms are useful.

How to add an MDI form to the


current project?

Project -> Add MDI form. Click Project from the menu bar and click Add MDI
form. Its simple! Remember, a project can have only one MDI form.

Restrictions of the MDI form


1. You can have only one MDI form per project.
2. You can't place most controls on an MDI form. The only controls that can
be placed on the surface of the MDI form are Menus, Timer,
CommonDialog, PictureBox, ToolBar and StatusBar.
These restrictions are there because MDI forms are special type of forms, only
used to handle multiple child forms.

How does the MDI form work?


In your project, there will be only one MDI parent form with one or more MDI
child forms (or simply child forms).

MDI child form: To add a child form, you have to add a regular form,
and set the MDIchild property to True. You can have many child forms.
You can show an MDI child form using the Show method as same as the
regular forms.

AutoShowChildren property of an MDI form: The default value is


True. When its True, the MDI child forms are displayed when they are
loaded. When the value is False, only then you can keep it hidden after
loading, otherwise not.

Restrictions of the MDI child forms:


1.You can't display an MDI child form outside its parent.
2.You can't display a menu bar on the MDI child form.

Now coming to the point, how the MDI form works. There is generally a menu
bar in the parent form. From there the user opens or creates a new document.
In this way, the user accomplishes his/her work in one or multipledocuments,
then saves and closes the document(form). You create instances of a single form
in the code using the Set keyword ( Remember the object variables).
'Inside the MDIForm module
Private Sub mnuFileNew_Click()
Dim frm As New Form1
frm.Show
End Sub

ActiveForm property: This is the Object type read-only property of the


MDI form. You can apply this property to one of the children which is the

active form. For example, you can close the active form using this
property from the Close menu command of the menu bar.
'In the MDI form
Private Sub mnuFileClose_Click()
If Not (ActiveForm Is Nothing) Then Unload ActiveForm
End Sub

If you cannot understand the above piece of code, don't worry. You'll get it when
you'll learn about Classes and Objects later in this tutorial. For now, just note
that (ActiveForm Is Nothing) represents that there is no active form. The Not
keyword before it negates the value.

Sample program
I've written an MDI demo application to simplify the topic for you.
Download it now! MDI demo

Related topics:

Multiple forms

BAS module

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson
126

<<Table Of Contents>>

Next Lesson>>

Screen Object in Visual Basic 6

Lesson 67
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Now after the previous lesson (MDI forms), lets move on to the next topic 'the
Screen Object'. After coming to the 67th lesson, I think its not necessary to tell

you about what an object is. Although I'll give you some hints.

Object
You have come across many controls throughout this tutorial. All the controls i.e
CommandButton, Label, TextBox are objects. Besides the form is also an object.
Collection is an object. See the lessons of collection object to clear any doubt.
Collection Object - part 1
Collection Object - Part 2
Some more examples are Clipboard, Dictionary object, Drive and folder objects,
App object, and printer object. There are many. The Screen object is also an
object like them.

What is Screen Object?


The one line answer: The screen object corresponds to the visible desktop.
While working with the form's properties, you have set Left, Top, Height and
Width properties with a numeric value. Do you know the unit in which they are
expressed? They are in twips.
On the printer, 1 inch = 1,440 twips.

Converting twips values into pixels


You can easily convert twips values into pixels using the TwipsPerPixelX and
TwipsPerPixelY properties of the screen object.
Your computer screen's resolution:
sWidth = Screen.Width / Screen.TwipsPerPixelX
sHeight = Screen.Height / Screen.TwipsPerPixelY
MsgBox "Resolution is " & sWidth & " X " & sHeight
Thus you get the result in pixels.

Some more properties of the Screen


Object
Have a look at some more properties of the Screen Object.

MouseIcon: The MouseIcon property sets a custom mouse icon.

The MousePointer property: Changes the mouse pointer. But it applies to


the current application only.

Screen.MousePointer = vbCross

FontCount and Font properties: The FontCount property gives you the
number of fonts for the current display device, and the Fonts property
returns the font names.

The following program shows the font names.


Dim i As Integer
For i = 0 To Screen.FontCount - 1
Print Screen.Fonts(i)
Next i

The ActiveForm property: This property returns the form that is the active
window.

The ActiveControl property: Returns the control that has the focus.

Text1.SetFocus
Screen.ActiveForm.Caption = "New Form"
Screen.ActiveControl.Text = "New text"

The ActiveForm and ActiveControl properties also only applies to the current
application.
Note: All the properties except MouseIcon and MousePointer are read-only
properties here.

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

<<Table Of Contents>>

Next Lesson>>

1409

Standard BAS Module

Lesson 68
<<Previous Lesson

Visual Basic 6 stores its code in the form of module that makes your program
more structured. So its very important to learn about it.

Before You start


Its recommended that you first have the concepts of scope, procedure,functions
and multiple forms. The following lessons are helpful.

Scope of a variable

Procedures - Part 1

Procedures - Part 2

Function procedure

Multiple Forms

What is a module?
Module is a separate code file in Visual Basic that contains procedures and
declarations.
Your entire VB6 program code does not come line by line. Instead they are
separated in code files called modules, each of them is separated into

procedures. Thus your VB6 program becomes well structured which is the key
part of developingVisual Basic applications.

Form Module
The complete code including procedures and declarations part of a form is
referred to as the form module.

Advantages of a BAS module


When the problem is large, its better to break it down into smaller parts to make
it easy.

Breaks down the problem: It makes your program more


understandable.

Executing common code repeatedly: You generally write the common


piece of code in the routines of a module. Then you can execute the same
piece of code repeatedly without writing them several times. That means
the common piece of code resides in module.

Time & effort: Saves time and effort.

Accessibilty: The procedures stored in the BAS module are accessible


from all forms, from any part of your project.

How to add a Standard BAS module


to the current project?
Project -> Add Module. Click Project menu from the menu bar and select add
module.

A separate project file with the .bas extension is saved on your hard disk as soon
as you add a standard module to your current project. You can change the Name
property of your newly added standard module from the properties window.
Choose a meaningful name, it will benefit you while writing the code.
The modules are shown in project explorer window:

Contents of the standard module:


1. Procedure definitions
2. Variable, type and constant declarations.

The variables and constants declared using the Public keyword in the Declrations
section of the module are global, accessible from all parts of your current
application.
An easy example:
'Inside the BAS Module
'Scope is Public to make it accessible from anywhere of the application
Public Sub show()
MsgBox "Welcome to vbtutes"
MsgBox "This is a message"
MsgBox "New message!"
MsgBox "List of messages"
End Sub
__________________________________________________
Public Function increment(number As Integer) As Integer
increment = number + 1
End Function

'In form1
Private Sub cmdShow_Click()
Dim num As Integer
Dim m As Integer
num = InputBox("Enter the number", "Input")
m = Module1.increment(num)
MsgBox m
Call Module1.show
End Sub

' In Form2
Private Sub Form_Load()
Call Module1.show
End Sub

' In Form3
'The show sub procedure is global
Private Sub Form_Load()
Call Module1.show
End Sub

Note: BAS modules are especially useful in large projects. So if you're


developing a big VB6 application, include them.

Related topics:

Multiple forms

MDI forms

Like my facebook page: www.facebook.com/vbtutes for free updates!

Validation in Visual Basic 6

Lesson 69
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Today I'll show you the techniques of validation in VB6. Validation is a very
useful feature of VB6 which you implement not only in the registration and login
forms but also in a variety of situations. Many applications have login systems.
So while designing the login and registration forms, it is a must to include the
validations for the controls on the forms.

What is validation?
You must have noticed in many applications that when you enter a data
incorrectly or when you leave the field blank, it warns you with a message. This
is called validation.
More precisely, when you leave the text field and move to another control, you
get a warning message and the input focus goes back to the previous field.

Examples:

I have already shown you an example of this type in the Registration program
sample, but VB6 validation techniques were not used in that sample.
You may say that you can do it without using the validation code, but VB6
provides a better way, a more convenient way to achieve the same which is
obviously the better solution to the problem.
The Validation event and the CausesValidation property makes the solution
working together. And sometimes the ValidateControls method is required. That's
all.
The default value of the CausesValidation property is True, and most of the
controls, even the external controls, support this property.
You have to write the code in the Validate event of the control where you input
the data, may be the TextBox control. After that you move to another control,
may be a CommandButton, a TextBox or any other. That means the first control
where you entered the data lost the input focus, and the other control is about
to recieve the focus. If the CausesValidation property of the control, which is
about to recieve the focus, is True only then Visual Basic fires the Validate event
of the first control that lost the focus.

Example:
Take two TextBox controls, a submit button; set their CausesValidation property
to True. Take a Cancel button, set its CausesValidation property to False.
Set the TabIndex value of the txtName control to 0.

Download this sample.

Private Sub txtName_Validate(Cancel As Boolean)


If txtName.Text = "" Then
MsgBox "Please enter your name!", vbExclamation, ""
Cancel = True
End If
End Sub
When the Cancel parameter is True, the input focus goes back to the txtName
control.

Private Sub txtPhone_Validate(Cancel As Boolean)


If Len(txtPhone.Text) < 10 Then
MsgBox "Enter the phone number in 10 digits!", vbExclamation, ""
Cancel = True

End If
End Sub
In this case, the input focus moves back to the txtPhone control when the the
Cancel parameter is set to True.

The IsNumeric function


What if the user enters a non-numeric i.e a string value in the txtPhone field? So
now you may want your users only to enter numeric values there. The IsNumeric
function can do it for you.
It returns True if it is a numeric value.

If Not IsNumeric(txtPhone.txt) Then

Cancel = TrueEnd If

The ValidateControls method


You generally use this method so that the user cannot close the form without
validating first.
This method invokes the Validate event of the control which has the input focus.
You generally use it in the Unload or QueryUnload event prcedure.

Private Sub Form_Unload(Cancel As Integer)


On Error Resume Next
ValidateControls
If Err = 380 Then
Cancel = True
End If
End Sub

This method returns an Error 380 in the case when the cancel paramter was set
to True in the Validate event procedure of the control having the input focus.

Download this sample here.

Related topics:

Form events

TextBox control

Like my facebook page: www.facebook.com/vbtutes for free updates!

<<Previous Lesson

2402

Google +

<<Table Of Contents>>

Next Lesson>>

218

Error Handling in Visual Basic 6

Lesson 70
<--Previous Lesson <Table of Contents> Next Lesson-->
In this lesson, I'll talk about error handling in Visual Basic 6. I will discuss, in
brief, how you can handle errors in your Visual Basic program. I'm not going to
give you an in-depth concept of error handling. Because that is beyond the
scope of this text which is targeted to the beginner learners. But I will discuss a
few features of Visual Basic 6 that enable you to efficiently manage the errors in
your program.

Related topic:

Fixing the overflow error

See the following pages for more tutorials:

Visual Basic 6 tutorials

VB6 code samples

VB2010 sample projects

What happens when error occurs?


When an error is encountered in your program, the program stops running
showing an error message in a dialog box. So this is going to be a real problem
if you cannot find the bug.
For example, say, you have developed a software. And also say, there's a bug,
an error. Then while using your software, the end-user will face the problem. The
program will stop running reporting an error. So you have to find a solution to
this problem.

How to deal with bugs?


So as I said you have to find a solution to this problem, there are some options
at your hand. You either have to programmatically ignore the error or display a
warning message to the end-user or find the bug and debug your program.

Error handling statements


Some useful error handling statements are there in Visual Basic 6 which help
you ignore, bypass or handle errors in your program. Three such statements are
helpful. They are as follows:

On Error Resume Next statement: If any error occurs, it is ignored,


and the control goes to the next statement.

On Error Goto label: If any error occurs, the control jumps to a label.

On Error Goto 0: This statement cancels the effect of 'On Error Resume
Next' and 'On Error Goto label' statements.

On Error Resume Next


If Visual Basic encounters an error, it ignores the error. Then the control goes to
the next statement. More precisely, Visual Basic causes a jump to the next
statement. And Visual Basic executes the statements ignoring the statement
where the error is found. Consider this example.
Example:
On Error Resume Next
a=6/0
Print "hello"

On Error Goto label


If Visual Basic encounters an error in a statement, the On Error Goto label
statement tells Visual Basic to jump to the named label. Thus the control jumps
to the named label. Then the code following the named label is executed.
Consider the following example.
Example:
On Error GoTo A
A=6/0
A:
Print "hello"
Print "Welcome"

On Error Goto 0

On Error Goto 0 statement tells Visual Basic to cancel any effect of 'On Error
Resume Next' and 'On Error Goto label' statements. So this statement cancels
the effect of errorhandling in your program.

The Err function


The Err function can help you handle the error using the error code. For
example, you can display a warning message to the end-user. The following
example clarifies this.
Example:
On Error Resume Next
b = 88 / 0
If Err = 11 Then
MsgBox "Error: Division by zero!"
End If
Example:
On Error GoTo Label5
b = 88 / 0
Label5:
If Err = 11 Then
MsgBox "Error: Division by zero!"
End If

Related topic:

Fixing the overflow error

See the following pages for more:

Visual Basic 6 tutorials

VB6 code samples

VB2010 sample projects

Like my facebook page: www.facebook.com/vbtutes for free updates!

The Clipboard Object in VB6

Lesson 71
<--Previous Lesson <Table of Contents> Next Lesson-->
The clipboard object is a simple object in Visual Basic 6 that stores data. You can
retrieve the data from the clipboard using appropriate methods of the clipboard
object.
In the Windows operating system, when you copy some data, the data is
automatically copied or stored in the clipboard object. You can place data in the
clipboard object and retrieve the data from clipboard.

Visual Basic study materials:

Visual Basic 6 tutorials

VB6 code samples

VB2010 sample projects

You can easily copy and paste data among applications - from one application to
another using the clipboard object.
The clipboard object has no properties. It has a few methods that help you work
upon the data.
Download this sample: Copy-paste sample

The SetTex method

The SetTex method puts text in the clipboard. In other words, you can place text
in the clipboard object using this method.
Example:
Clipboard.SetText Text1.Text

The Clear method


The Clear method clears the clipboard.
Example:
Clipboard.Clear

The GetTex method


The GetTex method lets you retrieve the text which is in clipboard.
Example:
Text2.Text = Clipboard.GetText

The SetData method


The SetData method places data e.g an image in clipboard.
Example:
Clipboard.SetData Picture1.Picture
' or
Clipboard.SetData LoadPicture("d:\mypic.bmp")

The GetData method

The GetData method retrieves data, for example an image, from the clipboard
object.
Example:
Picture2.Picture = Clipboard.GetData

Download sample: Copy-paste sample

Tutorials:

Control flow functions

The Form events

Fixing the overflow error

The Screen object

More >>>>>>>

Code samples:

Calculator

Number system converter

Photo Viewer

Contacts Manager

More >>>>>>>>>

Blog articles you may like:

6 Effective Ways to Learn Visual Basic

5 Reasons Why VB is a Good Choice for Making Business Solutions

Guide to Good Programming Habits

Comparison between VB6 and VB.NET

Vous aimerez peut-être aussi