INTRODUCTION
1.1 What is Visual Basic?
Visual Basic is a tool that allows you to develop Windows (Graphic User
Interface - GUI) applications. The applications have a familiar appearance
to the user. As you develop as a Visual Basic programmer, you will begin
to look at Windows applications in a different light. You will recognize
and understand how various elements of Word, Excel, Access and other
applications work. You will develop a new vocabulary to describe the
elements of Windows applications.
Visual Basic is an event-driven, meaning code remains idle until called
upon to respond to some event (button pressing, menu selection,). Visual
Basic is governed by an event processor. Nothing happens until an event is
detected. Once an event is detected, the code corresponding to that event
(event procedure) is executed. Program control is then returned to the
event processor, see figure 1.
Event? Event processor
Basic Basic Basic Figure 1
Event Procedures
Code Code Code
1
All Windows applications are event-driven. For example, nothing happens in
Word until you click on a button, select a menu option, or type some text.
Each of these actions is an event.
The event-driven nature of Visual Basic makes it very easy to work
with. As you develop a Visual Basic application, event procedures can
be built and tested individually, saving development time. And, often
event procedures are similar in their coding, allowing re-use (and lots of
copy and paste).
Some Features of Visual Basic
Full set of controls - you 'draw' the application
Lots of icons and pictures for your use
Response to mouse and keyboard actions
Clipboard and printer access
Full array of mathematical, string handling, and graphics functions
Can handle fixed and dynamic variable and control arrays
Sequential and random access file support
Useful debugger and error-handling facilities
Powerful database access tools
ActiveX support
1.2 Visual Basic 6 versus Other Versions of Visual Basic
The original Visual Basic for DOS and Visual Basic For Windows were
introduced in 1991.
Visual Basic 3 (a vast improvement over previous versions) was released in
1993.
Visual Basic 4 released in late 1995 (added 32 bit application support).
Visual Basic 5 released in late 1996. New environment, supported creation
of ActiveX controls, deleted 16 bit application support.
And, now Visual Basic 6 - some identified new features of Visual Basic 6:
Faster compiler
New ActiveX data control object
Allows database integration with wide variety of applications
New data report designer
New Package & Deployment Wizard
Additional internet capabilities
Applications built using Visual Basic 6 will run with Windows 95,
Windows 98, Windows 2000, or Windows NT.
1.3 Basic Programming Constructs
2
Statements
Statements are special keywords in a programming language that do something
when executed. For example, the Print statement in VB prints an expression on
the screen.
Print "Hello world"
Variables and Data in Visual Basic
Programs use data in writing the program code, these data are specified as
variables, where variables are memory locations storing the values of these
variables.
Declaring Variables
Syntax
Dim VarName As DataType
in this syntax,
Dim is a keyword which means Dimension that tells Visual
Basic that you want to declare a variable.
VarName is the name of the variable you want to create.
As is a keyword that tells Visual Basic that you are
defining the data type for that variable.
DataType is the data type of the variable.(we will discuss later)
The following are examples to create variables of a specified data type.
Dim j as Integer
Declaring the variable j of type Integer.
Dim I as Single
Declaring the variable I of type Single (Decimal Number).
Dim K as String
Declaring the variable K of type String (Text Information).
3
Naming Variables
While you declaring a variable you should be give it a name, but this name
should follow some rules to be valid, also we can say that variable names can
be simple such as I, j, k, l and can be more specific and or more descriptive
such as Total, sum, average, result.
The name can be a sequence of letters, numbers and some of characters.
Naming restrictions
The name must start with a letter and NOT a number or other character.
The name cannot contain a full stop (period).
The name must be unique within the current procedure or module
(variable scope).
The name cannot be longer than 255 characters.
So some examples of invalid variable names are:
2month
stud.avg
the result
And the following are perfectly acceptable (valid).
Mycourse$
Cc%
sum
avgGrade
Your variable names should be short and descriptive, which makes them easy
to type and easy to remember and your programs more understandable.
4
Variable Types
As we mention previously, variables are memory locations that stores the data
of different data types integer numbers, decimal numbers, characters, strings
and also logical data. The important thing is that the declaration of the variable
must match the type of data that you will later allocate to the variable. If you
decide to assign an integer value to an string variable an error will occur, see
table 1.1.
Table 1.1 Data Types
Data Type Memory Comments
Requirement
Integer 2 bytes Whole numbers
Long 4 bytes Whole numbers
Single 4 bytes Decimal numbers
Double 8 bytes Decimal numbers
Currency 8 bytes Decimal numbers
String 1 byte per character Text information
Byte 1 byte Whole numbers
Boolean 2 bytes Logical values
Date 8 bytes Date and time
Object 4 bytes pictures / objects
Variant 16 bytes + 1 byte per any of the preceding
character data type
As we see in the above examples Visual Basic does NOT force the
programmer to declare a variable before using it (optional) in another word you
can use the variable and assign it a value without declaring it. In this case, It is
allocated the data type known as variant. A variant can hold any type of data.
But as a good programming practice, it's useful to declare variables before
using it, other programming language such as C++, Java requires declaring
variables before using it, otherwise a syntax error will occurs.
5
Explicit Declaration of Variables
Explicit declaration is the practice of defining variables in advance of their use
with appropriate data types; else it will be an implicit declaration.
In addition to using the Dim statement, variables can also be defined as the
following Syntaxes:
Dim VarName1 [As VarType1][, Varname2 [As VarType2]]
Private VarName1 [As VarType1][, Varname2 [As VarType2]]
Static VarName1 [As VarType1][, Varname2 [As VarType2]]
Public VarName1 [As VarType1][, Varname2 [As VarType2]]
Dim, Private, Static and Public are Visual Basic keywords that define how and
when the variables may be used. VarName1 and VarName2 are the names of
the variables you want to declare. The syntax above shows that you may define
a number of variables in the same statement but you should be separate
between them with a comma, you may define any number of variables .
VarType1 and VarType2 are the data type of variable.
Here are some examples of variable declaration:
Dim Count As Integer
Private sum As Integer, avg as Double
Public Average As Single
As you can see, You don't HAVE to use Dim, Private, Static or Public and
You don't HAVE to use As DataType, If you just use a variable in the course of
coding for example.
GradeNumber = 4
Total = 18
Avg = Total / GradeNumber
6
Note: If you misspell the variable at some point in the program this means that
a new variable will be defined so an error will be occurring and it will be
difficult to debug.
Using Type Suffixes with Variables
There is a shorthand method of assigning data types "Data Type Suffixes" to
the variables instead of using the explicit data types mentioned above. With
this method of declaration a special character is used at the end of the variable
name to assign type to it. Using this method there is no need to use the As Data
Type, the following table 1.2 shows these suffixes.
Table 1.2 Type suffixes
Type Suffix
Integer %
Long &
Single !
Double #
Currency @
String $
Byte None
Boolean None
Date None
Object None
Variant None
By using these suffixes you could write variable declaration as the following
format.
Dim sum%
Private sum%, avg#
Public Avg!
7
Using Strings and String Variables
A string is a collection of any characters enclosed by quotation marks ("").
"Good Morning"
"Hello There"
"A"
"Street 125, building 5G"
"1234321"
The above written are examples of the string, where it can be any sequence of
characters that must be enclosed with a "" mark, it is from usual to see
characters, but from unusual to you to see numbers as a string values, although
you know that numbers have a numeric values and used in mathematical
notations, but also it can be used as a string values, but they have no
mathematical meaning can't be used in mathematical expressions.
Strings Declaration
There are two types of string declaration Variable-Length and Fixed-Length,
by default strings declaration are of type variable-length. The size of the
variable varies according to the text storing in it and up to 64,000 characters
may be held.
But the second type of string is the fixed-length, although these must be
explicitly defined, this kind of data type remains the same all the time. If the
data assigned to it does not fill the field (data size is smaller than variable size)
the remainder of the variable is filled using a space character. If the expression
assigned to the variable is longer than the variable (data size is greater than
variable size) then the remainder is discarded (ignored).
Fixed length string syntax:
Dim VarName As String * strLength
Example
Dim streetAddress1 As String * 40, streetAddress2 As String * 50
8
Variable Scope
The scope of the variables is an important to take care of it when you declare
variables, the scope means when and where to use variables.
Variables can be local and global, where local variables are used only locally
within the procedure it is declared, and can't be used, accessed by, modified
from outside that procedure, and the Private keyword is used within a Form or
Module's Declaration section to make the variable available only to the form or
module within which it is created. Where global variable are declared outside
any procedure, and be declared before any variable in the program, and can be
accessed from any point in the program, these are Public variables or global
variables.
Example
Public counter As Integer
Note, may be you think that you have to declare all the variables as global and
accessed from any point in the program, but as a good programming practice
you should limit the use of variables, so the program should be will structured
and the use of local variable is important, it facilitate the program reading and
reducing the errors.
Static Variables
Local variables used within a procedure are discarded and there values are
become unknown when that procedure is terminated. But sometimes you want
to keep these values for altar use, though, when you wish to call the procedure
multiple times and have the variables used with the procedure available for a
second or third run through, you have to declare variables as static to keep its
previous values.
Example
Static Counter as Integer
9
Constants
Variables are decaled constant when their values will not be needed to be
changed during the program execution, and if you want to change a constant
value a compiler error will occur.
Example
Pi = 3.14
ErrorMessage = "This program perform an illegal operation and shut down"
Also you can Create your own Constant by writing the keyword const before
variable declaration.
Example
Const x as integer=1
Const mystring as string ="welcome to Visual Basic"
Using the Assignment Statement
The assignment statement is to assign, give and specify values to the variables;
you assign the right hand side to left hand side. Place an equal sign after the
variable name and follow this with the expression which represents the value
you want to store in the variable. And you must take care that the variable
name and its assigned value should be of the same type, so an error will occur
when you run that part of the program.
Example
Dim i As Integer
i = "Visual Basic" ' an error will occur
size% = 12
Error$ = "An error has occurred."
txtTotal.text = Str(total)
value% = Int(txtvalue.text)
The above are examples of valid assignment statements.
10
1.4 Steps in Developing Application
The Visual Basic development environment makes building an application a
straightforward process. There are three primary steps involved in building a
Visual Basic application:
1. Draw the user interface by placing controls on the form
2. Assign properties to controls
3. Attach code to control events (and perhaps write other procedures)
These same steps are followed whether you are building a very simple
application or one involving many controls and many lines of code.
The event-driven nature of Visual Basic allows you to build your application in
stages and test it at each stage. You can build one procedure, or part of a
procedure, at a time and try it until it works as desired. This minimizes errors
and gives you, the programmer, confidence as your application takes shape.
As you progress in your programming skills, always remember to take this
sequential approach to building a Visual Basic application. Build a little, test a
little, modify a little and test again. You’ll quickly have a completed
application. This ability to quickly build something and try it makes working
with Visual Basic fun – not a quality found in some programming
environments! Now, we’ll start Visual Basic and look at each step in the
application development process.
Icon picture Name Function
Pointer To select any control tool.
Picture A container that can contain a
picture. User can also draw on it.
Label Place for static text on a Form.
Text box An input or edit field (it can be tied
to a DB field via a Data Control)
Group frame Provides a method to logically
group controls (e.g. several radio
buttons or checkboxes)
Command button Standard command button with
click event.
Check box Browse many check box
11
alternatives and to select one or
more of these alternatives.
Option button Browse many alternatives to users
and to select only one of these
alternatives.
Combo box Control (typically drop down) that
lets the user either select an item
from a list or just type in a value.
Events include change, click, etc.
List box Selectable (but not enterable) list
that displays a number of entries.
The list is displayed without having
to click a dropdown arrow.
Horizontal scroll To select a value from a range of
bar values like color in horizontal way.
Vertical scroll To select a value from a range of
bar values like color in vertical way.
Timer System timer that enables to make
specific tasks on organized intervals
of time.
Table 1.3 controls continued
Drive list box Browse disk drives.
Directory list box Lets user specify a windows file
location.
File list box Lets user specify the files location
inside the Directory.
Shape Lines, squares, ovals, etc. These are
just visual – they don’t hold
controls.
line To draw a line on the form.
Image Control to show bitmaps. Similar to
picture but user cannot draw on it
(so requires less memory)
Data Control Browse the stored data in a given
Database.
OLE Any OLE compliant object can be
placed on a Form (e.g. Word 6 to
enter data, Excel spreadsheet, etc.).
Placing another control on a VB
Form makes VB an "OLE client".
A VB App can also be made into an
object and act as an OLE Server to
12
other Apps.
1.5 Interface
Form
It is a window. A Form includes its own variables, events and functions as well
as its controls (along with events for those controls). It is stored as with
".FRM" extension or ".FRX" when in binary format, see figure 1.5.
Figure 1.5 Form Window
It’s the work area that you design your projects and applications on it, all the
controls of the tool box can be added to it.
The most common applications of Visual Basic use at least one form, also you
Can use more than one form this is called the MDI(Multiple Document
Interface), and you can move to any of these forms using methods like show
and hide, but at the same time you can only show one form.
As a good programming practice programmers use the first three letters of each
tool name to be used in the programming code, the following table show all
these apprevitation.
Table 1.3 Tool Appreviations
Tool Prefix used
Picture pic
Label lbl
Text box txt
Group frame fra
Command button cmd
Check box opt
Option button chk
Combo box cbo
13
List box lst
Horizontal scroll bar hsb
Vertical scroll bar vsb
Timer tmr
Drive list box drv
Directory list box dir
File list box fil
Shape shp
line lin
Image img
OLE ole
Project Explorer
Figure 1.6 Project Explorer
This figure is responsible for viewing all the forms, modules and its code in the
project (a project is a collection of files you use to build an application). For an
example to show the form click on its name or on view object icon , to
show the code click on view code icon and the toggle folder icon is
used to work with files.
Form Layout Window
Figure 1.7 Form Layout Window
14
Used to position forms in application on the screen, and it can be changed by
moving the small form using the mouse.
Properties Window
List the property settings for the selected form or control tool, a property is a
characteristic of an object, such as size, caption, or color. Properties describe
the characteristics of a control, these can be physical characteristics such as
height, width and color or its current state such as enabled, or links
definitions to other applications.
Note the name and caption properties of a control have the same default values
but are actually different. The name is what code uses to reference the control,
whereas the caption is purely what is written on the control so the user can
identify it. Good idea to rename controls to meaningful names as we mention
previously. Properties can be setting either at design time or at run time
Setting Properties at Design Time, use figure 1.8.
1. By selecting the properties window properties can be set to values at
design time.
2. A drop down list of the controls currently on the form, allows the
selection of a control so its properties can be edited
3. All the properties of that control are shown below, where they can be
selected for editing.
4. The currently selected property of the selected control is shown in the
edit window where it can be modified
1
2
15
Figure 1.8 Properties Window
Setting Properties at Run Time
You can also set or modify properties while your application is running. To do
this, you must write some code. The code format is:
ObjectName.Property = NewValue
Such a format is referred to as dot notation. For example, to change the
BackColor property of a form name frmForm1, we'd type:
frmForm1.BackColor = vbBlue
To access a control on another form you should use the form name to prefix the
property name:
frmForm2.Command2.Caption = “Visual Basic”
In the following table 1.4 we mention the most usable properties that can be
sharable between many objects (controls).
16
Table 1.4 Control Properties
Control Icon Its function
Property
Name Give a name to the
tool.
Caption Give an explicit
address to the tool
Backcolor Change the
background color.
ForeColor Change text color
Font You can determine
When you click on … the following text kind, style, and
figure will appear to you. size.
17
Height, Determine the
Width, Left, length, width, tool
and Top. left coordinate and
tool upper
coordinate
respectively.
Visible It has two values true
or false.
True the control is
shown on the form.
False the control is
disappeared.
Save the project
1. On the File menu, click Save Project, see figure 1.9.
Figure 1.9 saving project
Then the following figure 1.10 will appear to you to save the form first.
Figure 1.10 save as dialogue box
18
Then after clicking on save, the following figure 1.11 will appear to you to
save project name.
Figure 1.11 saving project
Events
An event occurs in response to an action, such as the user clicking the
mouse or pressing a key in the application or clicking on a form it self, we can
say that visual Basic provide two kind of events mouse and Keyboard as we
will see later. An event handler is a routine that responds to the event.
Types of events
Events can be classified as: 1) User generated (command button click)
1) Computer generated (specific time elapsed, from a timer control)
19
2) Program generated (program explicitly generates an event from
within the code)
Keyboard Events
The following table 5 lists the common visual Basic keyboard events
Table 1.5 Keyboard Events
Event Name Function
keydown Fires when a key is pressed (Enter key).
keypress Fires when a user's keyboard input is translated to
a character (any key character on the keyboard).
Keyup Fires when a user releases a key.
The altKey, ctrlKey, and shiftKey properties specify the state of the ALT,
CTRL, and SHIFT keys. You can change which key is associated with the
event by either changing the value of the keycode property or returning an
integer value. You can cancel the event by returning zero or false.
The following example will show to you how keydown Key and keyup key
work.
Example 1.2
Design the following form.
1) Build a new project.
2) Add a label button to the form.
3) From properties window set
20
Type Object Property Setting
Form frmForm1 Caption ""
Backcolor Pink
4) Now the form will look like the above form.
5) Double click on the Form, and write the code as seen in figure 1.15:
Figure 1.15 The Compete Code for Example 1.2
After writing the code click on button and now click on start from
tool bar, the following form will appear to
you in run time.
Now when you press the Enter Key, hello
word will be printed on the form with red
foreground color, font size 12, and as we
see from the code (print "Hello",), hello is
printed on the form horizontally because of
(,), without (,) it will be printed vertically.
And the following code represents the
event (load) on the form, which means when the form is loaded at run time, the
statement "Press Enter to write on the form" will appear on the label.
21
Private Sub Form_Load()
lblTest.Caption = " Press Enter to write on the form"
End Sub
Mouse Events
The following table lists the common Visual Basic mouse events.
Table 7: Mouse Events
Event Name Function
Click In addition to occurring when a user clicks on an
element, this event also fires when the user presses
ENTER on an element that can receive focus, such
as a button.
DoubleClick This event works similarly to its Visual Basic
counterpart.
MouseDown, When moving between elements, the MouseUp event
MouseUp, fires first to indicate that the mouse has left the
MouseMove original element. Next the MouseMove event fires,
indicating that the mouse has moved. Finally,
MouseDown fires to indicate that the mouse has
entered the new element.
Drag and Drop This event can drag an object from place to another
and leave it.
When a mouse event occurs, the button property of the event objects identifies
which mouse button (if any) is down. The x and y properties specify the
location of the mouse at the time of the event.
The following example will
show to you some of mouse
events.
Example 1.3
22
23