Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Chapter

1
Gettin g Starte d with
Visual Basic 6.0

his chapter concentrates on the programming aspect~ and fundamentals of Visual Basic
T and emphasizes on teaching the various Visual Basic software tools.

I Objeawu
0 Visual Basic 6.0 Programming Environment
0 Working with Forms
0 Developing an Application
0 Variables Data Types and Modules
0 Procedures and Control Structures
0 Arrays in Visual Basic
I A>
~.1 [ INTRODUCTIO N TO VISUAL BASIC
f
W-isual Basic is an ideal programming language for developing sophisticated professional
flpplications for Microsoft Window~ It makes use of Graphical User Interface for creating
11 Jbust and powerful applications. The Graphical User Interface as the name suggests, uses
illustrations for text, which enable users to interact with an application. This feature makes
lt easier to comprehend things in a quicker and easier way.
I t oding in GUI environment is quite a transition from the traditional, linear programming
methods where the user is guided through a linear path of execution and is limited to a small
~et of operations.) ln a GUI environment, the number of options open to the user are much
eater, allowing more freedom to the user and developer. Features such as easier compre-
ension, user-friendliness, faster application development and many other aspects such as
troduction to ActiveX technology and Internet features make Visual Basic an interesting
~ ol to work with.
I( Visual Basic was developed from the programming language-BASI C in the 1970s,
~icrosoft started developing ROM-based interpreted BASIC for the early microprocessor-
based computers. In 1982, Microsoft QuickBasic revolutionized BASIC and was legitimized
2 Visual Basic 6.0 Programming

as a serious development language fo r MS-DOS environmen t. La ter on, Microsoft C ,


· · C
tion cr eated the enha nced version of BASI ca e II d v· I B · fi ·
1sua as1c or Windows. orpora,
Visual Basic 6.0 for Windows_requires at least Microsoft ~indow~ 95 / Windows NT 3 _51
486 processor and a minimum of 16 MB of RAM. A complete mstallat10n of the most p f •
. d·t· . h ower u1
version of Visual Basic 6.0, the enterprise e 1 10n , reqmres more t an 250 MB of hard disk
space. ) }';,

1.2 VISUAL BASIC 6.0 PROGRAMMING ENVIRONMENT

Visual Basic is initiated by using the Programs Option ➔ Microsoft Visual Basic 6.0
Visual Basic 6.0. By clicking the Visual Basic 6.0 icon, we can view a copyright scr ~
enlisting details of the license holder of the copy of Visual Basic 6.0 . Then it opens inten
screen as shown in Fig 1 .1 with interface elements such as Menubar Toolbar and the No a
Project dialog box. These elements permit the user to build different types of Visual Bas1ce~
applications .
..., Projectl - Microsoft Visual Basic (design) '!I~ fJ
EiJe ~dit ~ f1oject FQrmat Qebug Bun Q!lery Diagram Iools ~-Ins ~ ttelP

11
j~ · 1:1 ·'ffl l~ liiil i? ~ e "' I<, , .. , ► u ■ J S~ c8 '~f~ 6l ~
xj
..,fl I IUl\,l...t

i
I
1~ ~A MriHII ActiveX EXE ActiveX Dll Act1veX
"'

~,-. ~,·.
Control

lab! □ ...J · .. Cancel

~ r- ~ #.
VB Application
#.
VB Wizard
~
Data Project
~
IIS Application
t!efp

~ .!Ill ~ Wizard Manager


0 g tJ
~t61'-- ~ Addin
~
ActiveX
~
Activex
~
DHTML
gi~ ~I Document DII Document Exe Application

~
VB Enterprise cl

4 Fig. 1.1

The Integrated Development Environment


I One of the most significant changes in Visual Basic 6.0 is the Integrated Development Envi-
ronment (IDE). IDE is a term commonly used in the programming world to describe the
interface and environment that we use to create our applications. It is called integrated •
because we ca n access virtually all of the development tools that we need from one screen
called an interface. The IDE is also commonly referred to as the design environment or the
program.
Getting Started with Visu al Basic 6.0 3

The Visual Basic IDE is made up of a number of components


• Menu bar
• Toolbar
• Project Explorer
• Properties Window
• Form Layout Window
• Toolbox
• Form Designer
• Object Browser
In previous versions of Visual Basic, IDE was designed as a Single Document Interface
(SDI). In a Single Document Interface, each window is a free-floating window that is con-
tained within a main window and can move anywhere on the screen as long as Visual Basic
is the current application. But in Visual Basic 6.0, the IDE is in a Multiple Document Inter-
face (MDI) format. In this format, the windows associated with the project will stay within a
single container known as the parent. Code and form-based windows will stay within the
main container form. The following sections give a brief description some of the components
found in the IDE.
Menu Bar
Menu bar displays the commands that are required to build an application. The main menu
items have sub menu ltems Qiat can be chosen when needed. The toolbars in the menu bar
provide quick acces/ to the commonly used commands and a button in the toolbar is clicked
once to carry out the action represented by it. The._, toolbars with their action and menu
equivalent are given in Table 1.1.

') T able 1.1

Toolbar button Menu equivalent


I

I ~ Adds a new Form Add Form command on the Project menu

~
I
Adds a new Module Add Module command on the Project menu

~ Opens an existing Project Open Project command on the File menu

~ Saves the current Project Save Project command on the File menu

,~,I Locks and unlocks the


command controls
Lock Controls command on the Controls on the Form
Format menu.
Displays the Properties Properties Window command on the View menu
~ window

~ Displays the Object


Browser
Object Browser command on the View menu

(Contd)
--
,4 VisuAI 1::las1c 6.ll Programming __
-

Table 1.1 tCP11tcil


Explore r command on the View rnenu
~I Displt\ys Uw Projret
Proiect
J

Explon~r
Start com mand on the Run menu
~ Sturt s Rn application in
dt'sign modl'
Break comman d on the Run menu
~ Used for debuggin g, stops
executio n of a program
while running
~ Stops· executio n of an
End comman d on the Run menu
application and returns
to the design mode
:: j Toggles breakpo int on Toggle Breakp oin' on the Debug menu
menu
i}, _j Displays the value of Quick Watch comman d on the Debug
the current selection
in the code window
j<.::111 Traces through each Step Into comman d on the Debug menu
line of code and steps
into procedur es
c~ I Executes one code Step Over comman d on Debug menu
procedur e or stateme nt
at a time in the Code window.
1!, I Displays the Menu Editor Menu Editor comman d on the Tools menu

j 6t ,I DataView window Contains data link and establish es data


connecti ons

~ Visual component Helps to access local database


Manage r

Toolbox
Toolbar is contains a set of controls that are used to place on a form at desi~ time ther~b(
creating the user interface area. Additional controls can be included in the toolbox by usin~
th e Compon ents menu item on the Project menu. A Toolbox is represen ted in Fiir t. 2.
• The I\iinter helps tu move and resize the controls and Form.s.
\
Getting Started with _Visual B~s 1c 6 0 5

\
, ~
\

.. Generol I
Pointer I ft u 1'1c1urcBox .,. I
I

Labe l A fatii TcxlBox J

FranJl'
\
r¥l LJ ( 'on1111u1idBut1011
p r. Ort1on Button
Check box
\
~ ~ Lisi Box
"
l'0111huBux
I IScrojq U:1r. jJ .ti
.cl
\ ~ VScrollB ar
\ ' '
'J:iincr
0 ' D DrivcLi st Box
\ .
DirL1stBox
'

□ ~ FileListB ox
.-
Shape it>)
' Line .......
Image
\
'1)]~ \ D\ta
•1···1·..
f11i11!i=
OLE .,"tmi

~ Fig. 1.2

• Label displa ys a text that the user canno t modify or intera ct with.
• Frame control serves as a visual and functional contai ner for controls.
• CheckBox dis~lays a True/F alse or Yes/No option .
• TextBox is a control used to display messa ge and enter text.
• The ListBox displays a list of items from which a user can select one.
an item
• ComboBox contai ns a TextBox and a ListBox. This allows the user to select
from the dropdown ListBox or to type a selection in the TextBox.
specified
• HScro llBar and VScrollBar controls allow the user to select a value within the
range of values.
• Timer control execut es timer events at specified interv als of time.
yed.
• DirListBox allows the user to select directories and paths, which are displa
• Shape control adds a shape (rectangle, square or circle) to a Form.
• Image control is used to displa y icons, bitma ps, metafi les, etc.
from other
• OLE control is used to link or embed an object , displa y and manip ulate data
Windows based applic ations .
as a visual
• Pictur eBox displa ys icons/ bitmap s and metafi les. It displa ys text or acts
contai ner for other controls.
• Comm andBu tton carrie s out the specified action when the user chooses it.
to select
• The Option Button control which is a part of an option~ ou£.!llows the user
one option even if it displa ys multip le choices.
~i~ng[J___ _ _ _ _ _ _ _ _~~-~~-- -~
6 v,~~~ !'·
Visual Basic:_16~0 P~ro'!lg"'.ra~mr,rm
. IJ__!'

. dis lays . disk drives and allows the user to select one f
the valid
The DriveL1stBox p 0

.
• them. . . la s a set of files from which a user can select the desired one.
• The FileL1stBox d1sp : ai ht line to the Form. . .
st
a theg user to connec t to an ex1stmg database and dispJ ay
control drawsbles
• L.me .
• Data control en~
information from. it.
d that can be cus tomized and controls, graphics and pictures can
Form serves as a wm ow
also be added to it.

Project Explorer t under the tool bar, is the Project Explorer


.
Docked on the right side of the scr::•i!u :he Fig. 1.3 serves as a quick reference to the
window. The Project Explorer as sho I ses and modul~ All of the objects that Diake
various elements of a proJect nameJtii, ;m,~ al
simple project typically contains one fonn,
f
up the application ar!U'acked m a pro~c the program's interface. It is possible to develop
which is a window that is designed as 1i~
oh a program may consist of a single form also in
any number of forms in a _p rogram , a o~gdow also lists code modules and classes.
addition to forms, the P:r:oJect Exp1orer wm

' ' Proiecl - Proiecll BliJ


~ ~ ,~
l=::.l l::E.I 111...J
-
El . Project 1- (Project 1)
EJ ·t'1 Forms
= ti.. Form 1 (Form 1)

4 Fig. 1.3

Properties Window

[ The Properties window is docked under the Project Explorer window. The Prop~rties
Window exposes the various characteri stics of selected objects. Each and every Form m an
application is considered an object. Now, each object in Visual Basic has character istics SUCh
as colour and size. Other characteristics affect not just the appearan ce of the object but the
way it behaves too. All t~~ chg_ract_e ristics of an object are calle,d its properties . Thus, a
Form has properties and any controls placed on it will have propertie s too. All of these prop-
are displayed in the Properties window. Figure 1.4 shows the Propertie s window of a
erties object.
Form
Getting Started with Visual Basic 6.0 7

~perhes • Feirr~1 1:1


jForm1 Form ;J
Alphabetic I
Categoriz~d )

(Name) Form 1 •
r
Appearance 1 - 3D
AutoRedraw False
BackColor ' D &H80000C
· BorderStyle 2 - Sizable
Caption Bl
· ClipControls True
. ControlBox True
DrawMode 13 - Copy Pel
· DrawStyle 0 - Solid
DrawWidth 1
.Enabled True
FillColor I &HO000OC
__ - 1'). FillSty'le 1 - TransparE

~~ Fnni- M~ Sao-; SP.rif~


,r jf
Captio n
-- Qph 1rndc1P~<: ~J-,p h:•v~ rlicnl.:::1-,prt

e 8 4 Fig. 1.4

. .
Object Brows er
and.m ethods
\ The Object Brows er allows us to browse throug h the VArio11s proper ties, e~ents
the View menu
~ hat are made avJ!.ill;!_ble to U §. It is accessed by selecting Object Brows er from
s and classe s
oroy pressi ng the key F2.fVrhe leftc olumn of the object brows er lists the object
been refere nced
that are availa ble in the ,projects ~hat are opened and the controls that have
or class that we
in them. It is possible for us to scroll throug h the list and select the object
wish to inspect. After an object is picked from the Classe s'list, we can see its
members (prop-
erties, metho ds and events ) in the right column.
I A proper ty is repres ented by a small icon that has a hand holdin g a piece of paper. Meth-
lightn ing bolt
ods are denote d by little green blocks, while events are denote d by the yellow
icon. ) ) f>1l
Properties, Methods and Events
These object s
All the controls in the Toclbox except the Pointe r are objects in Visua l Basic.
have associ ated proper ties, metho ds and events .
with certai n
Real world objects are loaded with proper ties. For examp le, a flower is loaded
prope rties.
colour, shape and fragrance. Simila rly, progra mmin g objects are loaded with
6 0 programm~
3 v,sual J 85tc - ·. _:,_.:;---
... ::- -- . b·ect. Pro per ties def ine the charact-ft
"b te of a pro gra-mmmg. O es ~ 4'11'. h.
w ic h I·t be h ave s ~r.
·
tne wa y m
. rty is a narne d attn u som et1m F'
.
A p1ope b·ec t such as size, colortie ur, etc. or E ble d Fon t, M u It·1 1-m ·
e,
T . . . or
ext , V1sibl
s such as na
1st1c of an J ° accepts prope _
example a TextB~xe discuss ed below:
'
.
e,
.
ena ble d or dis abl ed at run tim e depend
Wl·dth' etc. These ar tv the TextBox to be in
allows
• Enabled pr~p_e r ., t to True or False. g
h d1t1 t B x
on t eco n 0n tse particular font in · the Tex O ·
• Font property se s a t and dis pla y mu ltip le lines at run
the TextBox to accep
Multi Line property allows
• .
time. rtic ula r tex t in the control.
extBox control set s a pa .
• Text property of the T . the object at run tim e.
• Visible property is used to hide t the . .
desired wid th at des ign tim e.
Width property sets the TextBox o
• d . tim e pro per ties tha t can be set
Th ·
perties tha t are d1sc d bove are esig n at the
usse a . d Bu t cer tain pro per ties · tb
. e ~;; e by selecting the Properties w1dnCo can no e set at de-
des1gn w. t y pro per ties of a For m can not
. t· example, t he Curr e nt X an urr be set at
sign ·ime . For .
en
X Cu rre nt y prope rt·1es are dis cus sed in eta1 m
d ·1 . Ch te 3
ap r .)
the design time. [Current ' . .
d b·e cts For exa mp le, a cat 1s an obJect. It.s
A method is an act1.0n t h a t can be performe on o J . . h
. . l d 1 . bl thr ee pou nds we ig t, etc. A complete
rop erti es mig ht me u e ong wh ite hai r ue eye s, .
P ' ·t oks but sho uld also inc . 1d
definition of cat mus t ~~ t only encc ompass on 1 s 1o ' .
u e a complete
1
itemization of its actiV1t1es. There1ore , a t' methods mig ht be move, JUID
ca s P, p ay, breathe,
etc. . . . a method is a con nec ted or bui lt-i n pro
Similarly, in obJect-onen~d p:o r:~ mm cedure,
~ some action on a par ticu lar object.
a blo_ck of cod~ tha t can A method
reqmres an obJect to prov~ed
1
I~~o e wi; h1: ~:n tex t. For exa mp le, the
wo rd Move has no mean-
ing in Visual Basic, but theefollem
owing sta tem ent, performs a ver y pre . t"
cise ac 10n.
Textl.Move 700, 400
The TextBox control has other associated
methods suc h as Ref res h, Set Foc us, etc
• The Refresh method enforces a comple .
te rep ain t of the con trol or a For m. For
Textl .Refresh refreshes the Text Box. example,
• The SetFocus method moves the focus
to the control. For exa mp le, Tex tl .Se tFo
the focus to TextBox control Tex tl. cus sets
Eve nt Driven Pro gra mm ing
Visual Basic programs are bui lt around eve
nts. Eve nts are var iou s thi ngs tha t can
a program. This will become clearer when happen in
( stu die d in con tras t to pro ced ura l pro gra
procedural languages , a written applica mm ing. In
l tion is executed by che cki ng for the
I cally through the program statements, one pro gra m logi-
afte r ano the r. For a tem por ary pha se,
may be transferred to some other point the control
in a program. While in an eve nt dri ven
the program stat em ent s are executed onl application ,
y when a par ticu lar eve nt cal ls a specifi
code tha t is assigned to the event. c par t of the
Let us consider a T,extBox control and
a few of its ass oci ate d eve nts to und
concept of event driven programming. The ers tan d the
TextBox control sup por ts var iou s eve
nts such as
Getting Started with Visual Basic 6.0 9

n
Change, Clic k, Mou seM ove and man y more
that will be liste d in the Prop erties drop -dow
list in the code window for the TextBox cont
rol. Few of them are give n below.
when ther e is a chan ge in the con tent s of
• The code ente red in the Change even t fires
the TextBox.
rol is clicked.
• The Click eve nt fires whe n the TextBox cont
is moved over the TextBox .
• The MouseMove eve nt fires whe n the mouse
ed with diff eren t controls and forms, som e
As exp lain ed above, seve ral even ts are asso ciat
a few bein g specific to each con~
of the even ts bein g common to mos t of them and _.,/

I. Points to ,Ponder

Sta te Tru e or Fal se


selected from mul tiple choices.
1. One or mor e Opt ionB utto n controls can be
controls in the Form .
2. Men u bar con tain s a set of tools to provide
Fill in the bla nks
be enforced by ___ __ met hod .
1. A com_i;lete repa int of a form or control can
in the con tent s of the TextBox .
2. y,ot ~ve nt is fired whe n ther e is a change
" ' is used to link or emb ed obje ct, display and man ipul ate data from othe r
3.
Windows base d applications.

I
1 1.3 WO RK ING WIT H FORMS
I

cts. A Form is one of the mos t basi c obje cts in


I

· ~-Vi-su-al Bas ic has seve ral diff eren t type s of obje


a window that con tain s an app lica tion code
which the app lica tion is developed. A Form is.
user interface. A Form may fill the enti re
and has othe r objects placed on it to crea te the
it or it may be a cust om dialog box.
scre en or hav e othe r Form s con tain ed with in
, For ml file in each new project. You can
Visu al Basic initi ally includes a defa ult form
the purp ose of the Form . Eve ry For m object
chan ge the form's nam e and capt ion to iden tify
ciat ed with it.
has its own prop ertie s, even ts and met hod s asso

Setting Form Properties < '


Form to gath er inpu t from the use r and to
Any Visu al Basic app lica tion prog ram uses the
the user 's poin t of view, the form window is
disp lay the outp ut info rma tion to the user . From
tify this window as clea rly and definitively
the prog ram . Oonsequently, it is nece ssar y to iden
s to it.
as possible, by assi gnin g app ropr iate prop ertie
to the For m alon e and a brie f description- is
The re are a few special prop ertie s indi geno us
give n in the following sections.

Border Styl e
r
Some of the avai labl e sett ings can cau se othe
For ms can hav e a vari ety of type s of borders.
are avai labl e are liste d in Tab le 1.2:
For m prop ertie s to be ignored. Th_e bord ers that
10 Visual Basic~ -~ ~rog ra~- - - - - --
Table 1.2

---
-----:Jlf_~- -=- - =- - =- - =-~~~s;~;.~~~~~~~=----
Option
None
Purpose
No border is shown . In additio~, t h e Minimize
button , Maximize button, ~he title bar and Close
-----

buttons are hidden from view.


Fixed Single A single-pixel width border is shown around the fonn.

Sizeable This is the default setting. The border around the


window is left so that it can be resized by the user.
Fixed Double A double -pixel width border is shown around the
form.
Fixed ToolWindow This type of border is used for toolbars that might be
floating in the workspace. Only the title bar and Close
box are visible, but in a reduced size.
Sizeable ToolWindow Same as Fixed Tool Windo w , but borders are resizeable.

Caption
The title for the windo w is stored in the Captio n prope rty. The captio n
appea rs below the
form's icon when the form is minim ized.
Control Box
This proper ty determ ines wheth er the Contro l box, availa ble by clickin
g the upper left cor-
ner/ico n of a window, will be shown or not.
Icon
This prope rty specifies the icon for the windo w in the upper left corne r
of the window.
Mouse Pointe r
This proper ty sets the value that indica tes the type of mouse pointe r
displa yed when the
mouse pointe r appea rs over a partic ular area of the object at runtim e.
Max Button
This proper ty indica tes wheth er the Maxim ize button should be shown
and the Maximize
choice made availa ble in the Contro l Box menu.
MD/C hild
This prope rty specifies if this windo w must be shown within a multip le
docum ent interface
(MDI) windo w.

MinBu tton
This prope rty indica tes wheth er the Minim ize button should be shown
and the Minimize
choice made availa ble in the Contro l Box menu.
Getting Started with Visual Basi~ 6.0 ~
---- ----
Moveable
This is a property introduced in Visual Basic 5. By setting it to False , it is possible to
nd
preve~t the us~r fro~ moving the window manually. This is useful for splash screens a
other mformat10nal drnlog boxes that are shown and dismissed quickly.
StartUpPosition
This is a property introduced in Visual Basic 5 so that instead of writing code to position your
window, you can pick a starting position from this drop-down menu. The available choices
are given in Table 1.3:

Table 1.3

Option Purpose
Manual Any positioning must be done in the Layout window.
CenterOwner The forw should be shown in the center of the form
that owns it .
CenterScreen The form should be shown in the center of the
user's screen.
Windows Default It lets Windows decide where the form should be
shown

WindowState
V
This property indicates whether the window is shown normally, maximized or minimized. It
is possible to pick a starting state for your Form at design time so that when you show the
window, it comes up in that state.
0isplaY-i.ng Forms
The following sections give a brief description about displaying and loading a Form object.
Show Method
The Show method is used to display the Form object. For example, to display the form
frmCalculator, the following code is written.
FrmCalculator.Show
Using Load Statement
The Load statement is used to load a form or control into memory but does not display it. To
load the form frmCalculator, the following code should be entered.
Load frmCalculator
Hiding and Unloading Forms
--- ~- - -- --- - _,,.,,,A

The following sections discuss briefly the steps required to hide and unload forms.
12 Visual Basic 6.0 Programming

Using the Hide Method . .


'd
The hide method h1 es a F or m
··
For exampl e, the followmg code hides the Form b·
0 Ject
frm Calcula tor.
f rmCal culator.Hide
Using the Unload Statement
The Unload statem ent removes the form from the display and release s its memory
, The
following code should be entered to unload frmCal culator from memor y.
Un l oad frmCalculator
Using the Unload Event
The Unload event procedure is used to verify that the_ form should be unload ed or to
some
specific actions that have to take place when the form is unload ed. The Unload event occurs
when.
• The Form is unloaded using the Unload statem ent.
• The Form is closed by the user either clicking the Close comma nd on the application
menu or clicking the Close button on the applica tion title bar.
Setting Run Time and Design Time Properties
Many properties can be set at either design time or runtim e. At design time, the controls
are
added to a project , their propert ies set and the relevan t code is written . During runtime
, we
examine our program in action, just as the end user will eventu ally see it.
To set a property at design time, the following steps are followed.
• Select the control or object whose charact eristics are to be changed.
• Activate the Propert ies window.
• Scroll to the property you want to set and select its name.
• Enter a new setting.
At runtime, propert y settings can be changed by a program 's code. This is accomplished by
writing a special kind of assignm ent statem ent that gives a new value to a specific property
of a selected object.
Object.propertyName = value
The left side of this assignm ent statement, Object.propertyName is a compound name
identifying the object and the property that is to be reset. The value on the right side of
the
st atemen t gives the new setting. When a program resets a propert y at runtime, the
new
setting overide s the value assigned at design time. Design time setting s need not be perma-
nent during a program run.
Example 1.1 The following example illustra tes how the Caption , MouseP
ointer,
Window State, Height and Width properties for a form object are set at runtime.
Pr i vate Sub Fo rm_Load()
Forml .Mou sePoint er = vbHourglass
Getting Started ~1~ Visu al Basi c 6_0 _!!_
--- - --- - - - - - - - --

Forrn l. Ca pt ion = "Sample App l ication"


Form l.W i nd owStat e = vb Normal
Forml .Width = 5000
Fo rml .He i ght = 5000
End Sub ,)
Pon der
) - - - - - - - - - - - - 11. Poin ts to
Fill in the blan ks
.
1. The l ; even t occurs whe n the form is closed by the user
2. The ' · . , meth od is used to disp lay a form obje ct.
on code and ha s othe r obje cts plac ed
3. A J It 1 is a window that cont ains the appl icati
on it to crea te the user inter face.

1.4 DEVELOPING AN APP LIC ATI ON


proje ct is a collection of files t hat are used
An appl icati on can be crea ted with the project . A
ram invo lves t he follo "·ing t wo step s.
to build an appl icati on. Writ ing a Visual Basic prog
• Visu al prog ramm ing step
• Code prog ram min g step
icati on with vari ous tools that com e
Visu al prog ram ming step involves desi gnin g an appl
ram ming step invo lves writ ing prog ram s
along with the Visual Basic pack age. Code prog
first Visu al Basi c prog ram . Before writ -
usin g a text edito r. This section involves writ ing the
wed_ The prog ram wind ow rese mbl es
ing the prog ram, its specifications have to be revie
that perf orm specific act ions repr esen ted
Fig. 1.5 com prisi ng three Com man dBu tton cont rols
lay butt on disp lays specified mes sage and
by thei r capt ions and an emp ty TextBox . The Disp
Exit butt on term inat es the appl icati on.
Clea r butt on clea rs the mes sage in the TextBox . The

4 FiQ., 1,5
14
~ - -
\llsual Basic 6.0 _Pr o~ r~~
- -- - -- - - - -

CASESTUDY
. mmodities be lon gin g to dif fer en
M & Co is a famous sup en na rk t which se11 s co d d
t cate .
S · . e . t· tio ne ry t
rea yma e ga rm en s, etc. Th goli
. · appliances, s a
tha t include groceries. e1ectI0~ ' es
1c . . t·
ers of the supermarket are gomg ute riz ing the ir op era wn s. Durm . e OW}i
g thi s Pr .
m for ~dompd
. ·t
the following reqmsi es nee d to be cons1 ere . OCess
d f d t ·y lis t fro m the se t of
• To select the mo e O pa~m en t an ca egoi av ail ab le choice
• To update the category hs t as he n the new sto ck arr ive s. s.
and w d up da te it
• To maintain a database of reg
ular cuSt0mers an ·
• To enlist the availability of the
items. . .
• To give a lis t of choices for the t ha vin g dif fer en t siz es.
pro duc s
• To choose the mode of payment.
• To display messages on entry
and exit of the customers.
• To record the date and the day
of transaction.
• To choose the day of delivery of
goods to a customer.
• To maintain a record about the
sales made on various cat eg ori
• To access details of the transa es ov er a year.
ctions and all activities of the su
How Visual Basic can be used to pe rm ark et.
att ain these req uis ite s ha s be en
ples throughout the book. elu cid ate d using exam.
Example 1.2 Let us consider
a simple display program usi ng
example. the TextBox control in this
A New Standard EXE Project ite
m is selected from the File me
Project dialog box. The sta nd ard nu tha t displays a New
EXE is chosen for normal applic
sponds by displaying the Project ations. Vi sua l Basic re-
and Form windows as shown in
Fig. 1.6.
Iii Pm jec tl · Forml (Form)
• pil [ij £!

Iii Forml
. .. ... . . .. ... . .. . .
'

I · . ► A
4 Fig.1.6
Though no changes hav
stage of the design. When ea been made to the F . .
project is saved t or :, it
f~e. The project file ha s .VBP ext is be tte r to save the project at the
ens ion a~d early
for building the Project. The Fo ~; co es ~re ~aved, na ~e ly ProjeeHiie a n
rm file co t . 1,1-tams mformati ~
.FRM extension. The Save Projec on tha t Visual Basic uses
t comman~ ~ms {nformation ab
responds by displaying a Save Fil ou t the Form an d has the
e As dialog ~o:e a:cted fro ~ th~
File me . Visual Basic
shown m Fig. 1.7. A nu file na me called
Getting Started with Visual Basic 6.0 15
--
ed on. Visual 8 aH1c the n <.hsp iays a
Displ ay. fr~i is given and the Save butto n has to be click
File As dialog·box . The proje ct file
Save ProJec~ As dialo g box, whic h is simi lar to the Save
is saved as Disp lay .vbp.

~ combo ti menu
~ commond,alog tl Mousedown
~ conl4.,ra_~ ~ Mousemove
~ customd1alog ~ scrollbar
~ Dialog
t'.1.list

s~ :I
)4 '

.:] -~.. ]
H"' I
4 Fig. 1.7

Examining the Project Window


orde r to exam ine the Proje ct wind ow,
At this stage , our proje ct cons ists of a single Form. In
menu . It displ ays the Proje ct wind ow
Project Expl orer comm and is selec ted from the View
Object and Toggle Fold ers butto ns.
with the Form . Proje ct window featu res View Code, View
ow or to the Form or by togg ling the
Selec ting the desir ed ones leads eithe r to the code wind
object in proje ct window.
Ch~nging properties and Adding Controls
ertie s. The appl icati on is desig ned as
The next step is to add the controls and set their prop
per the specifications given in Tabl e 1.4.
Tabl e 1.4

Property Setting
Object
Caption The Display Prog ram
Form
Name FrmD ispla y

CommandButton Caption &Exi t


Name cmdE xit

CommandButton Caption &Cle ar


Nam e cmdC lear
CommandButton Caption &Display
Nam e cmdDisplay
Te:xtBox Name TxtDisplay
. progr~a~rn~rn~in~gL-..- - - - - - - - - - - - - - - - - -
16 Visual Ba~ 6 0--~ g
_::_--

Changing the Prope ,ties of Form h F m click anywhere on it · and press F4


ty of t e or ' C . or s
to chancre the proper We can change the apt1on and Name in th eleet
In operties
ordef O h V' ew menu.
window from t e 1 4 Th CommandButto n control is . ep
added by double 1· top.
Pr · · Table 1. . e It h c lcki
ertics window as give~ lil ces it in the centre of the Form. can t en be dragged Ilg
it in the Toolbox, which pla. Ith a caption Commandl. Now the properties ar and
. ed locat10n. as
. t th specifications given T a ble 1.4 . The same stepe setj
dropped at t he r~quir .
. n
the Properties wmdow acco rdmg 0t e_ndow displays the properties alphabetically a :.fol.
lowed for the other controls. Proper y w1
. d · t· pane at t h e bottom. n 111 a
categorized form with a escnp ion
Adding Code for the Program
The visual programming step is now comple~ed and selecting Sa~e Project_ command from
the File menu saves the work. The next step is the code _programming step. V1su~l Basic code
is written in the Code window that consists of an ObJe_ct box ~nd Procedure hst box. The
Object box dis_Qlays the_name of the selected object ~ssoc1ated w1~h the Form. The Procedure
listiYox l ists the procedures for an object such as chck, double-chck, etc. An event procedure
is written in the Code window that combines the control's name, which is listed in the
ListBox, an underscore and the event name. The Code window is viewed by selecting View
Code from the Project window or by selecting Code from the View menu or pressing F7.
Figure 1.8 represents a Code window.
~ode editor window includes List Properties/Meth ods which presents a list of properties
availa?le for controls. Procedure View and Full Module View buttons are available. The
followmg code is entered for the Click events of the respective controls in the Code window.

,,ii Project1 - Form1 (Code) Bl!l £!


!(General) _:::] fcmddisplay_click . _ J·
Private Sub cmddisp lay_c ick () -- - - -- -- ---- -
1
~::d~: lay. Text = "visual basic- 61 for windows 95,,

Private Sub cmdexit_click ()


End
End Sub
•r·1 ... _
_
~ .... ..i.,;,,.

~--~
....
,, ' ? ·~ , _ ,,

... ·
,, ·-

4 Fig. 1.8
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdDisplay_Click()
S.O 17
Getting Started with Visual Basic

for Windows 95"


tx tDi splay . Text =" Visual Basic-6
End Sub
Pr ivate Sub CmdClear_Click()
txtD i splay.Text = " "
End Sub ssi ~g ~~­
n is run by clic kin g Sta rt com mand from the Ru n me nu or pre 18
The applicatio nd ow s 95 di~-
pla y but ton is clicked the message Vis ua l Ba sic 6 for Wi
When the Dis
cki ng the Cle ar but ton cle ars the message, while clicking the Ex it
played in the TextBox. Cli
button ter mi nat es the application.
Creating an Executable File ma n~ from
an exe cut abl e file in Vis ual Ba sic by choosing Make EXE Fil e com
We can cre ate ear s. Now the file is saved as Dis pla y.e xe m the
the File menu. A Make EX E dia log box app t·
. ion 18
11ca · converte d
the OK but ton is clicked . As the app
required directory or har d-d isk and m.
run it on any oth er Windows progra
into an executable file the use r can
Ending an Application
d to ter mi nat e the exe cut ion of the application. It unl oad s all the
The En d sta tem ent is use
forms from memory.
Ill. Points to Po nder
-----------
Sta te Tr ue or Fa lse
1. Debug window is the same as
Code Window. "
box and procedure listbox. 1 ,.
dow con sis ts of an obj ect i
2. Code win
r r-
, 'f+"'f-'

-. , \, : 1
Fil l in the bla nk s
saved wit h an extension ' ..v ~ : ~ •
1
1. Visual basic project files are
ension ..!' {.2 I A . \
2. Form files are saved with an ext the Fo rm .
j et.k nam e of the selected object ass oci ate d wit h
3. The Ob box dis pla ys the

-------
1 - 1.5 VARIABLES, DATATYPES AN Q.. MOD.UL_E.S.-

Visual Basic uses buildi


Control Str uct ure s in
ng
its
blo
pro
cks
gra
suc
mm
h
ing
as Va
env
ria
iro
ble
nm
s, Da ta Types, Pro ced ure s, Fu nct ion s and
ent. This section con cen tra tes on
ve.
the pro-
Basic with the blocks specified abo
gra mm ing fundamentals of Visual

ME 2ules .tw7JfCYL- are Form


Ba sic is sto red in the form of mo dules. Th e thr ee kin ds of modules
( cod e in Visual es. A sim ple application ma y con tai
n~ sin gle
nda rd mo ~ule~ an d Cla ss mo dul
c.;,;,dules , Sta
s m tha t For m mo dul e itse lf. ~ the app lica tio n grows, add itio nal
Form and the code ~es1de cod e to be executed in sev era l Forll\S. To avo
id
the re ma y be a com mo n
Forms are ~dded and
18 Visual Basic 6.0 Programmin~ -- _______ ---- - -
.............., _ - - --- -- -
. • g 8 procedure is created that im I
duplication of Code, a separate module contarnm c: P ernent8
the common code. This is a Standard module.
e extension) are the foundation of o~ject oriented Pro
Class modules (.CLS fiJena~ d b riting code m class mod I gram.
ming in Visual Basic. New obJects can be create Y w u es. Each
module can contain :
Declarations
. . bl d DLL procedure declarations .
May mclude constant, type, vana e an
Procedures
th
A sub function or property procedure that contains pieces of code at can _be executed as a
unit.

( Data Types ' .

By default Visual Basic variables are of the variant data type. The variant data tYPe can
store numeric, date/time or string data. When a variable is declared, a data type is supplied
for it that determines the kind of data it can store. The fundamenta l data types in Visual
Basic including variant are integer, long, single, double, string, currency, byte and
boolean~Visual Basic supports a vast array of data types. Each data type has limits to the
kind of information and the minimum and maximum values it can hold. In addition, sowe
types can interchange with some other types. A list of Visual Basie's simple data types are
given in Table 1.5.
Table 1.5
Type Name Value Range
Byte 0 to 255
Boolean True or False
Integer -32, 768 to 32,767
Long
, -2,147,483,648 to 2,147,483,647
Single 3 45
-3.402823 * 10 to -1.401298 * 10 for negative values.
1.401298 * 10· to 3.402823 * 10 38 for positive values.
45

-1.79 * 10 to-4.94 * 10-324 for negative values


~
308
Double
4.94 * 10- to 1. 79 * 10 308 for positive values
324

Date January 1, 100 to December 31, 9999


String 0 to approximately 2 billion characters ))
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807 _

Variables

Variables are used for storing values temporarily. A defined na mmg· t t h to be fol-
·1 · • bl A s ra egy as
lowed wh 1 e nammg a var1a e. variable name must begin with an alphabet letter and
should not exceed 255 characters. It must be unique within the s ame scope. It should not
. . h t er l'k _ & , 1. , #,@or$.
{]/70,
contam any spec1a1 c arac 1e
-
Getting Started with Visual Basic 6.0
---· - --- - - - ---
19

. Depe nding on wher e the


'I_'here are many ways of decla ring variables in VisuaJ Basic
mine how they can be used by
variable~ ar~ decl~red ?~dh ow they are decJared, we can deter
Visual Basic are listed below
our appl~catwn: 'I he_ different ways of decla ring variables in
and eluci dated m this section.
• Explicit Decl aratio n
• Usin g Optio n Explicit state ment
• Scope of Varia bles
Explicit Declaration
ory. It is not a must that a
Declaring a varia ble tells Visual Basic to reserve space in mem
ever Visual Basic enco unter s
variable shou ld be declared before using it. Automatically when
. This is called impli cit declara-
a new varia ble, it assig ns the defau lt :variable type anq value
to have morE\ contro! over t~e
tio~. Thou gh this type of decla ratio ; is easie r for the user,
bles are declared with a Dim
varia bles, it is advisable to declare them explicitly. The varia
e in the Dim state ment allows
state ment to name the varia ble and its type. The As type claus
called explicit decla ratio n.
to define the data type or object type of the variable. This is
\,
Synta x
Dim varia ble [As type]
For example,
Dim strname As String
Dim intCounter As Integer
Using Option Explicit Statement
It may be convenient to declare variables implicitly, but it
can lead to error s that may not be
recognized at run time. Say, e.g. a variable by name intcount is used impli citly and is as-
1 by the following state ment .
signed to a value. In the next step, this field is incre ment ed by
Intcount = intcont + 1
as intcont would have been
This calculation will resul t in intcount yielding a value of 1
misty ped as intco nt in the
initialized to zero. This is because the intco unt variable has been
not view this as a mista ke and
right hand side of the second variable. But Visual Basic does
t.
considers it to be a new variable and hence gives a wrong resul
addin g the following state -
To preve nt error s of this natur e, we can declare a varia ble by
ment to the gene ral declaration section of the Form.
Option Explicit
Explicit state ment checks in
This forces the user to declare all the varia bles. The Option
an error to the user. The user
the module for usage of any undeclared varia bles and repor ts
can thus rectify the error on seeing this error message.
gene ral decla ration section
The Option Explicit state ment can be explicitly placed in the
of each module using the following steps .
20 Visual Basic 6.0 Programming

• Click Options item in the Tools menu.


• Click the Editor tab in the Options dialog box.
• Check Require Variable declaration option and then click the OK button.
Scope of Variables
A variable is scoped to a procedure-level (local) or module-level vartable depending on ho"•.
. d . h.
is declared. The scope of a variable, procedure or obJect etermmes w ich parts of the cod .., •It
our application are aware of the variable's existence. A variable is declared in general de;)~~
ration section of a Form and hence is available to all the procedures. Local variables
are
recognized only in the procedure in which they are d_eclared. They can be declared with Dim
and Static keywords. If we want a variable to be available to a!l of t ~e procedures within th
same module or to all the procedures in an application, a variable is declared with broade;
scope.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to
the code inside the procedure and can be declared using the Dim statement as given below.
Dim intTemp As Integer
The local variables exist as long as the procedure in which they are declared, is executing.
Once a procedure is executed, the values of its local variables are lost and the memory used
by these variables is freed and can be reclaimed. Variables that are declared with keyword
Dim exist only as long as the procedure is being executed.
Sla!frY'Variables
S(atic variables are not re-initialized each time Visual Basic invokes a procedure and thus
retains or preserves value even when a procedure ends. In case we need to keep track of the
number of times a CommandButton in an application is clicked, a static counter variable has
to be declared. These static variables are also ideal for making controls alternately visible or
invisible. A static variable is declared as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in module-level and public vari-
ables are preserved for the lifetime of an application whereas local variables declared with
Dim exist only while the procedure in which they are declared is still being executed. The
value of a local variable can be preserved using the Static keyword. The following procedure
calculates the running total by adding new values to the previous values stored in the static
variable value. ·
Function RunningTotal( )
Static Accumulate
Accumulate= Accumulate+ num
Runn i ngTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of Static, the previously accu-
mulated values would not be preserved across calls to the procedure and the procedure would
J

ure static,
return t~e same val~e with which it was called. To make all variables in a proced
given in the
the Static keyword 18 placed at the beginning of the procedure headin g as
statem ent below.
Static Function Runni ngTota l ( )
andBu tton that
Example 1·3 . The following is an example of an event procedure for a Comm
counts and displays the numbe r of clicks made.
Private Sub Commandl Click()
Static Counter As Integer
Counter= Counter+ 1
Print Counter
End Sub
t value of zero.
The first time we click the CommandButton ' the counter starts with its defaul
Visual Basic then adds 1 to it and prints the result.
Module-Leve/ Variables
are declar ed
A module-level variable is available to all the procedures in the module. They
using the Public or the Private keyword.
Public intPermanent As Integer
Private intTemp As Integer
the applica-
Declaring a variable using the Public keyword makes it available throug hout
en Dim and
tion even for the other modules. At the module-level there is no difference betwe
variab les
Private, but Privat e is preferred because it makes the code easier to read. Public
es can share
should not be declared within a procedure. Public variables in different modul
public intege r
the same name and they can be differentiated in code. For example, if the
be referre d as
variable intY is declared in both Forml and Modulel of a project it can
Forml .intY and Modulel.intY.
Public vs Local Variables A variable can have the same name and differe
nt scope. For ex-
declar e a local
ample, we can have a public variable named R and within a procedure we can
local variab le
variable R. References to the name R within the procedure would access the
and references to R outside the procedure would access the public variable.)
/J)
1--- ---- - - - - - - IV. Points to Ponder
State True or False
1. String is a data type that can be used to declar e a text of
maxim um 10 million
characters.
2. A module-level variable is available to all the procedures in the module.
ure and
3. Static variables are not re-initialized each time Visual Basic invokes a proced
thus retains or preseryes value even when a procedure ends.
les and
4. The Dim statem ent checks in the module for usage of any undeclared variab
reports an error to the user.

You might also like