Visual Basic - Unit 4
Visual Basic - Unit 4
Visual Basic - Unit 4
0 VISUAL BASIC
One of the primary reasons for immense popularity of computer is the advent of programming
tools that enable common people to become programmers and develop applications. One of such
tools is the Microsoft Visual Basic (VB).
VISUAL BASIC is a high level programming language which was evolved from the earlier DOS
version called BASIC. BASIC means Beginners' All purpose Symbolic Instruction Code. It is a
very easy programming language to learn. The code looks a lot like English Language. Now,
there are many versions of VB exist in the market, the most popular one and still widely used by
many VB programmers is none other than Visual Basic 6.
4.1 Introduction to VB
On the other hand, because the user may click on certain object randomly, so each object has to
be programmed independently to be able to response to those actions (events). Therefore, a VB
Program is made up of many subprograms, each has its own program code, and each can be
executed independently and at the same time each can be linked together in one way or another.
With VB 6, you can create any program depending on your objective. For example, if you are a
college or university lecturer, you can create educational programs to teach business, economics,
engineering, computer science, accountancy, financial management, information system and
more to make teaching more effective and interesting. If you are in business, you can also create
business programs such as inventory management system , point-of-sale system, payroll system,
financial program as well as accounting program to help manage your business and increase
productivity. For those of you who like games and working as games programmer, you can create
those programs as well. Indeed, there is no limit to what program you can create ! .
You can invoke Visual Basic 6.0 Enterprise Edition from the Start Menu as follows
Click Start Program Microsoft Visual Studio Microsoft Visual Basic.
You can see a main screen upon which a small pop up window is displayed. This window
appears each time you invoke Visual Basic. This window has option for opening a new
project or an existing project.
Since you will be creating a new project, choose the Standard EXE option and click
Open. This is shown in Figure 4.1.
Once you open a Standard EXE file a default form with the name Form1 will open for you to start
your new project as shown in Figure 4.2. Now, double click on Form1, the source code window
for Form1 as shown in Figure 4.4 will appear.
Figure 4.2 Visual Basic Main Windows
Before starting to write any programs there are few tools and bar with components needs to be
known as shown in Figure 4.2 the topmost bar is the ‘Title Bar‘, it displays the name of the
current project. The second bar from the top is the ‘Menu Bar’ followed by the third that is the
‘Standard Toolbar’.
Below you can see in Figure 4.4 a Toolbox which generally appears on the left side of the
window. You can see in Figure 4.3 the various Controls of Toolbox such as Text Box, labels, List
Box etc. We shall see the Controls in detail a little later.
The next important concepts we see on top of the source code window are list of objects and
their associated events or procedures which we will see in detail under the Section 4.15. In Figure
4.4, the object displayed is Form and the associated procedure is Load.
Figure 4.4 Visual Basic Code Editor and Procedures
For this we see an example for an object being selected in Figure 4.5 and the respective
procedure for that object being selected is in Figure 4.6.
Once the object and procedure is selected in source code window we can start writing the code.
This code is written between the beginning and the end statements (i.e. Private Sub
Form_Load.......End Sub.). Just key in the lines in between the above two statements exactly as
are shown here below in Example 4.1
Example 4.1
Form1.show
End Sub
When complete the coding you just press F5 to run the program you get the result for Example
4.1 is shown in Figure 4.7. The command Print does not mean printing using a printer but it
means displaying the output on the computer screen.
You can also perform arithmetic calculations as shown in Example 4.2. VB uses * to denote the
multiplication operator and / to denote the division operator. The output is shown in figure 4.8,
where the results are arranged vertically.
Example 4.2
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub
Just like Arithmetic Operations you can also use the ‘+’ or the ‘&’ operator to join two or
more texts (string) together like in Example 4.3 (a) and (b) and the output you get is shown in
Figure 4.9.
Private Sub
A = “Tom”
B = “likes"
C = “to"
D = “eat"
E = “burger"
Print A + B + C + D + E
End Sub
Private Sub
A = “Tom”
B = “likes"
C = “to"
D = “eat"
E = “burger"
Print A & B & C & D & E
End Sub
Till now we saw the various procedures to start a VB Project, we will summarize them in the
steps below
Before writing an event procedure for the control to response to a user's input, you have to set
certain properties for the control to determine its appearance and how it will work with the event
procedure. You can set the properties of the controls in the properties window or at runtime.
Below we can see in Figure 4.10 you see all the properties of a Form listed in a Property Window
for a form. You can rename the form caption to any name that you like best. In the properties
window, the item appears at the top part is the object currently selected (in Figure 4.10, the object
selected is Form1). At the bottom part, the items listed in the left column represent the names of
various properties associated with the selected object while the items listed in the right column
represent the states of the properties. Properties can be set by highlighting the items in the right
column then change them by typing or selecting the options available
You can also change the properties at runtime to give special effects such as change of color,
shape, animation effect and so on. For example the following code will change the form color to
red every time the form is loaded. VB uses hexadecimal system to represent the color. You can
check the color codes in the properties windows which are showed up under ForeColor and
BackColor. In Example 4.4 given below we can change the Form1 back color by giving the
correct color code during the form load option at runtime.
Example 4.4
Form1.Show
Form1.BackColor = &H000000FF&
End Sub
Another example is to change the control Shape to a particular shape at runtime by writing the
following code in Example 4.5. This code will change the shape to a circle at runtime.
Example 4.5
Shape1.Shape = 3
End Sub
4.16 Handling some of the Common Controls
Now we are going to see a few important controls available in VB and see examples of
these controls working below.
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. String in 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 4.6
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
creates a variable sum to accept the summation of values from text box 1 and text box 2.The
procedure to calculate and to display the output on the label is shown below. The output is shown
in Figure 4.11
Example 4.6
Label1.Caption = Sum
End Sub
Figure 4.11
The output
of example
4.6
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 label1.Caption, it can display text and numeric data . You can change its
caption in the properties window and also at runtime. Refer to Example 4.6 in which we change
the caption of Label1 to Sum using the following command “Label1.Caption = Sum” and
Figure 4.11 shows the result for the usage of label.
The command button is one of the most important controls as it is used to execute commands in
any program. It creates 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 to develop
the command button is shown in Example 4.7. Its output is shown in Figure 4.12.
Example 4.7
Statements
End Sub
Statements
End Sub
Figure 4.12 Command Button Sample
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 as shown in Figure
4.13.
The Image Box is another control that handles images and pictures. It functions almost identically
to the picture box. 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 Picture Box.
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.
The function of the List Box 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 4.8
List1.AddItem “Rectangle”
List1.AddItem “Square”
List1.AddItem “Oval”
List1.AddItem “Circle”
List1.AddItem “Rounded Rectangle”
List1.AddItem “Rounded Square”
End Sub
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 4.9
Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub
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 will change the
background color of the form to red when the check box is unchecked and it will change to blue
when the check box is checked. This is shown in Figure 4.15 and the example is given in 4.10.
You will learn about the conditional statement If….Then….Elesif in later lesson. VbRed and
vbBlue are color constants and BackColor is the background color property of the form.
Figure 4.15 Check Box Sample
Example 4.10
End Sub
The Option Box control also lets the user selects one of the choices. However, two or more
Option Boxes must work together because as one of the Option Boxes is selected, the other
Option Boxes 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 the following example, the shape control is placed in the form together with six
Option Boxes. When the user clicks on different option boxes, different shapes will appear. The
values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square,
an oval shape, a rounded rectangle and a rounded square respectively. The sample option box is
shown in Figure 4.16. The syntax to create option box is given in Example 4.11
Figure 4.16 Option Box Sample
Example 4.11
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
The Drive ListBox is for displaying a list of drives available in your computer. When you place
this control into the form and run the program, you will be able to select different drives from
your computer as shown in Figure 4.17
The Directory List Box is for displaying the list of directories or folders in a selected drive. When
you place this control into the form and run the program, you will be able to select different
directories from a selected drive in your computer as shown in Figure 4.18
Figure 4.18 The Directory List Box
The File List Box is for displaying the list of files in a selected directory or folder. When you
place this control into the form and run the program.
Each control or object in VB can usually run many kinds of events or procedures; these events are
listed in the dropdown list in the code window that is displayed when you double-click on an
object and click on the procedures’ box (refer to Figure 4.35). Among the events are loading
a form, clicking of a command button, pressing a key on the keyboard or dragging an object and
more. For each event, you need to write an event procedure so that it can perform an action or a
series of actions
To start writing an event procedure, you need to double-click an object. For example, if you want
to write an event procedure when a user clicks a command button, you double-click on the
command button and an event procedure will appear as shown in Figure 4.33. It takes the
following format:
Example 4.12
Private Sub Command1_Click
End Sub
You then need to key-in the procedure in the space between “Private Sub
Command1_Click............. End Sub”. Sub actually stands for sub procedure that made up a part
of all the procedures in a program. The program code is made up of a number of statements that
set certain properties or trigger some actions. The syntax of Visual Basic’s program code is
almost like the normal English language though not exactly the same, so it is very easy to learn.
Object.Property
where Object and Property is separated by a period (or dot). For example, the
statement Form1.Show means to show the form with the name
Form1, Label1.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.
Example 4.13
Label1.Visible=False
Label2.Visible=True
End sub
Example 4.14
Label1.Caption=” Welcome”
Image1.visible=True
End sub
Example 4.15
Pictuire1.Show=True
Timer1.Enabled=True
Lable1.Caption=”Start Counting”
End sub
In Example 4.13, clicking on the command button will make label1 become invisible and label2
become visible; and the text”. You are correct” will appear in TextBox1. In example 4.12,
clicking on the command button will make the caption label1 change to “Welcome” and Image1
will become visible. In example 4.15, clicking on the command button will make Picture1 show
up, timer starts running and the caption of label1 change to “Start Counting”.
Syntaxes that do not involve setting of properties are also English-like, some of the commands
are Print,
If
<statements>
Then
<statements>
Else
<statements>
End If
For
<statements>
Next
Select Case
<statements>
End Select
And also the End and Exit Sub. For example, Print “Visual Basic” is to display the text Visual
Basic on screen and End is to end the program. Other commands will be explained in details in
the coming lessons.
Program code that involve calculations is very easy to write, you need to write them almost like
you do in mathematics. However, in order to write an event procedure that involves calculations,
you need to know the basic arithmetic operators in VB as they are not exactly the same as the
normal operators we use, except for + and - . For multiplication, we use *, for division we use /,
for raising a number x to the power of n, we use x ^n and for square root, we use Sqr(x). VB
offers many more advanced mathematical functions such as Sin, Cos, Tan and Log. There are
also two important functions that are related to arithmetic operations, i.e. the
functions Val and Str$ where Val is to convert text entered into a textbox to numerical value and
Str$ is to display a numerical value in a textbox as a string (text). While the function Str$ is as
important as VB can display a numeric values as string implicitly, failure to use Val will results
in wrong calculation. Let’s see this with example 4.16 and example 4.17.
Example 4.16 Example 4.17
Text3.text=text1.text+text2.text Text3.text=val(text1.text)+val(text2.text)
When you run the program in example 4.16 and enter 12 in textbox1 and 3 in textbox2 will give
you a result of 123, which is wrong. It is because VB treat the numbers as string and so it just
joins up the two strings. On the other hand, the execution of Example 4.17 will give you the
correct result, i.e., 15.
There are many types of data that we come across in our daily life. For example, we need to
handle data such as names, addresses, money, date, stock quotes, statistics and more everyday.
Similarly in Visual Basic, we have to deal with all sorts of of data, some can be mathematically
calculated while some are in the form of text or other forms. VB divides data into different types
so that it is easier to manage when we need to write the code involving those data.
Visual Basic classifies the information mentioned above into two major data types, they are the
numeric data types and the non-numeric data types.
Numeric data types are types of data that consist of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide and more.
Examples of numeric data types are examination marks, height, weight, the number of students in
a class, share values, price of goods, monthly bills, fees and others. In Visual Basic, numeric data
are divided into 7 types, depending on the range of values they can store. Calculations that only
involve round figures or data that does not need precision can use Integer or Long integer in the
computation. Programs that require high precision calculation need to use Single and Double
decision data types, they are also called floating point numbers. For currency calculation , you
can use the currency data types. Lastly, if even more precision is required to perform calculations
that involve a many decimal points, we can use the decimal data types. These data types are
summarized in Table 4.1
Nonnumeric data types are data that cannot be manipulated mathematically using standard
arithmetic operators. The non-numeric data comprises text or string data types, the Date data
types, the Boolean data types that store only two values (true or false), Object data type and
Variant data type .They are summarized in Table 4.2
Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal
so that VB can handle the calculation more accurately. For example, we can use num=1.3089#
for a Double Type data. Some of the suffixes are displayed in Table 5.3.
In addition, we need to enclose string literals within two quotations and date and time literals
within two # sign. Strings can contain any characters, including numbers. The following are few
examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
Managing Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now
and then, just like the mail boxes. In term of VB, variables are areas allocated by the computer
memory to hold data. Like the mail boxes, each variable must be given a name. To name a
variable in Visual Basic, you have to follow a set of rules.
Variable Names
The following are the rules when naming the variables in Visual Basic
Examples of valid and invalid variable names are displayed in Table 4.4
Table 4.4
Declaring Variables
In Visual Basic, one needs 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.
The format is as follows:
Example 4.18
If data type is not specified, VB will automatically declare the variable as a Variant.
For string declaration, there are two possible formats, 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 4.18 above. However, for the fixed-length string, you have to use the format as shown
below:
Dim VariableName as String * n, where n defines the number of characters the string can hold.
Example 4.19:
Constants
Constants are different from variables in the sense that their values do not change during the
execution of the program.
Declaring a Constant
Example 4.20
Const Pi As Single=3.142
Exercises
1. Odd man out
a) Queries b) Table c) Data d) Font
ANSWERS:
1)b 2)c 3)b 4)b 5)a 6)a
SUMMARY