VB 6.0 Tutorials
VB 6.0 Tutorials
Programming means writing coded instructions or programs to instruct a computer or other devices to
perform specific tasks automatically. The computer programs written by the programmers are often
known as software. Various software exist today, among them are desktop operating system, Internet
browsers, spreadsheet, word processing software, accounting software, photo and video editing
software, gaming software, mobile apps, robotic software and more.
After installing the vb6 compiler, the icon will appear on your desktop or in your program’s menu. Click
on the icon to launch the VB6 compiler. On start-up, Visual Basic 6.0 will display the following dialog
box as shown in Figure 1.1.
When you start a new Visual Basic 6 Standard EXE project, you will be presented with the Visual
Basic 6 Integrated Development Environment (IDE). The Visual Basic 6 Integrated Programming
Environment is shown in Figure 1.2. It consists of the toolbox, the form, the project explorer and the
properties window.
You can also use the + or the & operator to join two or more texts (string) together like in example
2.1.4 (a) and (b)
Example :
Private Sub
A = "Tom"
B = "likes"
C = "to"
End Sub
Example :
Private Sub
A = "Tom"
B = "likes"
C = "to"
D = "eat"
E = "burger"
Print A & B & C & D & E
End Sub
This example changes the background colour of the form using the BackColor property.
Form1.Show
Form1.BackColor = &H000000FF&
End Sub
This example is to change the control's Shape using the Shape property. This code will change the
shape to a circle at runtime.
Shape1.Shape = 3
End Sub
The TextBox
The text box is the standard control for accepting input from the user as well as to display the output.
It can handle string (text) and numeric data but not images or pictures. A string entered into a text box
can be converted to a numeric data by using the function Val(text). The following example illustrates a
simple program that processes the input from the user.
Example :
In this program, two text boxes are inserted into the form together with a few labels. The two text
boxes are used to accept inputs from the user and one of the labels will be used to display the sum of
two numbers that are entered into the two text boxes. Besides, a command button is also
programmed to calculate the sum of the two numbers using the plus operator. The program use
Label1.Caption = Sum
End Sub
The Label
The label is a very useful control for Visual Basic, as it is not only used to provide instructions and
guides to the users, it can also be used to display outputs. One of its most important properties
is Caption. Using the syntax Label.Caption, it can display text and numeric data . You can change its
caption in the properties window and also at runtime. Please refer to Example 3.1 and Figure 3.1 for
the usage of the label.
The command button is one of the most important controls as it is used to execute commands. It
displays an illusion that the button is pressed when the user click on it. The most common event
associated with the command button is the Click event, and the syntax for the procedure is
Statements
End Sub
The PictureBox
The Picture Box is one of the controls that is used to handle graphics. You can load a picture at
design phase by clicking on the picture item in the properties window and select the picture from the
selected folder. You can also load the picture at runtime using the LoadPicture method. For example,
the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
The Image Control is another control that handles images and pictures. It functions almost identically
to the pictureBox. However, there is one major difference, the image in an Image Box is stretchable,
which means it can be resized. This feature is not available in the PictureBox. Similar to the Picture
Box, it can also use the LoadPicture method to load the picture. For example, the statement loads the
picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
The function of the ListBox is to present a list of items where the user can click and select the items
from the list. In order to add items to the list, we can use the AddItem method. For example, if you
wish to add a number of items to list box 1, you can key in the following statements
Example 3.2
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The ComboBox
The function of the Combo Box is also to present a list of items where the user can click and select
the items from the list. However, the user needs to click on the small arrowhead on the right of the
combo box to see the items which are presented in a drop-down list. In order to add items to the list,
you can also use the AddItem method. For example, if you wish to add a number of items to Combo
box 1, you can key in the following statements
Example 3.3
Combo1.AddItem "Item1"
Combo1.AddItem "Item2"
Combo1.AddItem "Item3"
Combo1.AddItem "Item4"
End Sub
The CheckBox
The Check Box control lets the user selects or unselects an option. When the Check Box is checked,
its value is set to 1 and when it is unchecked, the value is set to 0. You can include the statements
Check1.Value=1 to mark the Check Box and Check1.Value=0 to unmark the Check Box, as well as
use them to initiate certain actions. For example, the program in Example 3.4 will show which items
are selected in a message box.
The OptionButton
The OptionButton control also lets the user selects one of the choices. However, two or more Option
buttons must work together because as one of the option buttons is selected, the other Option button
will be unselected. In fact, only one Option Box can be selected at one time. When an option box is
selected, its value is set to “True” and when it is unselected; its value is set to “False”.
In this example, we want to change the background color of the form according to the selected option.
We insert three option buttons and change their captions to "Red Background","Blue Background"
and "Green Background" respectively. Next, insert a command button and change its name to
cmd_SetColor and its caption to "Set Background Color". Now, click on the command button and
enter the following code in the code window:
Form1.BackColor = vbRed
Form1.BackColor = vbBlue
Else
Form1.BackColor = vbGreen
End If
End Sub
VB Statements
End Sub
You enter the codes in the space between Private Sub Command1_Click............. End Sub. The
keyword Sub actually stands for a sub procedure that made up a part of all the procedures in a
program or a module. The program code is made up of a number of VB statements that set certain
properties or trigger some actions. The syntax of the Visual Basic’s program code is almost like the
normal English language, though not exactly the same, so it is fairly easy to learn.
Object.Property
where Object and Property are separated by a period (or dot). For example, the
statement Form1.Show means to show the form with the name Form1, Iabel1.Visible=true means
label1 is set to be visible, Text1.text=”VB” is to assign the text VB to the text box with the name
Text1, Text2.text=100 is to pass a value of 100 to the text box with the name
text2, Timer1.Enabled=False is to disable the timer with the name Timer1 and so on.
In Visual Basic, it is a good practice to declare the variables before using them by assigning names
and data types. They are normally declared in the general section of the codes' windows using
the Dim statement. You can use any variable to hold any data, but different types of variables are
designed to work efficiently with different data types.
If you want to declare more variables, you can declare them in separate lines or you may also
combine more in one line , separating each variable with a comma, as follows:
Example 5.1
Unlike other programming languages, Visual Basic actually doesn't require you to specifically declare
a variable before it's used. If a variable isn't declared, VB willautomatically declare the variable as a
Variant. A variant is the data type that can hold any type of data.
For the string declaration, there are two possible types, one for the variable-length string and another
for the fixed-length string. For the variable-length string, just use the same format as example 5.1
above. However, for the fixed-length string, you have to use the syntax as shown below:
For example,
Scope of Declaration
Other than using the Dim keyword to declare the data, you can also use other keywords to declare
the data. Three other keywords are private ,static and public. The forms are as shown below:
The above keywords indicate the scope of the declaration. Private declares a local variable or a
variable that is local to a procedure or module. However, Private is rarely used, we normally use Dim
Constants
Constants are different from variables in the sense that their values do not change during the running
of the program.
Declaring a Constant
The Code
h = 40
r=h/2
rad = r * 0.001763889
a = Pi * rad ^ 2
area = Round(a, 2)
End Sub
After declaring various variables using the Dim statements, we can assign values to those variables.
The syntax of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The expression could be a
mathematical expression, a number, a string, a Boolean value (true or false) and more.
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
^ Exponential 2^4=16
* Multiplication 4*3=12,
/ Division 12/4=3
Mod Modulus (returns the remainder from an integer division) 15 Mod 4=3
Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically, they resemble
mathematical operators. Conditional operators are very powerful tools, they let the VB program
compare data values and then decide what action to take, whether to execute a program or terminate
the program and more. These operators are shown in Table 7.1.
Operator Meaning
= Equal to
Logical Operators
In addition to conditional operators, there are a few logical operators that offer added power to the VB
programs. They are shown in Table 7.2.
Operator Description
* You can also compare strings with the operators. However, there are certain rules to follow where
upper case letters are less than lowercase letters, and number are less than letters.
To effectively control the VB program flow, we shall use If...Then...Else statement together with the
conditional operators and logical operators.
If conditions Then
VB expressions
Else
VB expressions
End If
Example:
The Code
username = "John123"
password = "qwertyupi#@"
End If
End Sub
Select Case
In the previous lesson, we have learned how to control the program flow
using If...Then...ElseIf control structure. In this lesson, you shall examine another way to control the
program flow, that is, the Select Case control structure. The Select Case control structure is slightly
different from the If....ElseIf control structure .The difference is that the Select Case control structure
can handle conditions with multiple outcomes in an easier manner than the If...Then...ElseIf control
structure. The syntax of the Select Case control structure is shown below:
Case value1
Case value2
Case Else
End Select
Example :
grade=txtgrade.Text
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
End Sub
Example 8.2
'Examination Marks
mark = mrk.Text
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
Case Is >= 50
comment.Caption = "Average"
Case Else
End Select
End Sub
Looping
The Do Loop statements have four different forms, as shown below:
a)
Do While condition
Loop
b)
c)
Do Until condition
Loop
d)
Do
Example 9.1
Do while
counter <=1000
num.Text=counter
counter =counter+1
Loop
Next
The structure of a While….Wend Loop is very similar to the Do Loop. it takes the following form:
While condition
Statements
Wend
The above loop means that while the condition is not met, the loop will go on. The loop will end when
the condition is met. Let’s examine the program listed in example 9.4.
Example 9.5
n=n+1
Sum = Sum + n
Wend
End Sub
Built-in Functions
A function is similar to a procedure but the main purpose of the function is to accept an input from the
user and return a value which is passed on to the main program to finish the execution.There are two
types of functions in VB6, the built-in functions and the user-defined functions. The syntax of a
function is:
FunctionName (arguments)
The arguments are values that are passed on to the function. In this lesson, you will learn two very
basic but useful internal functions of Visual basic , i.e. the MsgBox( ) and InputBox ( ) functions.
MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box that prompt the user to click on a
command button before he /she can continues. The format is as follows:
The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, please refer Table 10.1 for
types of command button displayed. The Title argument will display the title of the message board.
0 vbOkOnly Ok button
An InputBox( ) function will display a message box where the user can enter a value or a message in
the form of text. The format is
myMessage 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:
default-text- The default text that appears in the input field where users can use it as his intended
input or he may change to the message he wish to key in.
x-position and y-position - the position or the coordinate of the input box.
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your messge here",
500, 700)
message.Caption = userMsg
Else
End If
End Sub
Mathematical Functions
Some of the common mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs, Exp, Log, Sin,
Cos, Tan , Atn, Fix, Round and more
Rnd is is very useful function for dealing with the concept of chance and probability. The Rnd function
returns a random value between 0 and 1. In Example 11.1. When you run the program, you will get an
output of 10 random numbers between 0 and 1. Randomize Timer is to randomize the process.
Dim x as integer
For x=1 to 10
Print Rnd
End Sub
The numeric functions are Int, Sqr, Abs, Exp, Fix, Round and Log.
a) Int is the function that converts a number into an integer by truncating its decimal part and the
resulting integer is the largest integer that is smaller than the number. For example, Int(2.4)=2,
Int(4.8)=4, Int(-4.6)= -5, Int(0.032)=0 and so on.
b) Sqr is the function that computes the square root of a number. For example, Sqr(4)=2, Sqr(9)=2
and etc.
c) Abs is the function that returns the absolute value of a number. So Abs(-8) = 8 and Abs(8)= 8.
e) Fix and Int are the same if the number is a positive number as both truncate the decimal part of the
number and return an integer. However, when the number is negative, it will return the smallest
integer that is larger than the number. For example, Fix(-6.34)= -6 while Int(-6.34)=-7.
f) Round is the function that rounds up a number to a certain number of decimal places. The Format
is Round (n, m) which means to round a number n to m decimal places. For example, Round (7.2567,
2) =7.26
g) Log is the function that returns the natural Logarithm of a number. For example,
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)
Len (VisualBasic) = 11
The Right function extracts a substring from a phrase, starting from the Right. The syntax is
Right (Phrase, n)
where n indicates the number of characters that you wish to extract starting from the right-most
character. For example,
The Left function extracts a substring from a phrase, starting from the left. The syntax is
Left(Phrase, n)
The Ltrim function trims the empty spaces of the left portion of the phrase. The syntax is
Ltrim(Phrase)
.For example,
The Rtrim function trims the empty spaces of the right portion of the phrase. The syntax is
Rtrim(Phrase)
.For example,
The Trim function trims the empty spaces on both side of the phrase. The syntax is
Trim(Phrase)
.For example,
The Mid function extracts a substring from the original phrase or string. The syntax is:
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,
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
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,
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.
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)
Asc(Character)
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")
Arrays
Introduction to Arrays
By definition, an array is a variable with a single name that represents many different items. When we
work with a single item, we only need to use one variable.
Example 16.3
For num = 1 To 10
If studentName(num)<>"" Then
Form1.Print studentName(num)
Else
End
End If
Next
End Sub