Visual Programming Notes-2
Visual Programming Notes-2
Visual Programming Notes-2
3.PROGRAM STRUCTURE
FormatofVi sualProgram
Datatypes
Operators
Arithmet ic
Logi cal
Compar ison
Other s
Vari
ables
4.PROGRAM WRI TING
Creati
nganappl i
cati
on
Compi l
ation
Debuggin
gTesting
Executi
on
5.CONTROLSTRUCTURES
Typesofcont rolstr
uctur
es
Defi
niti
on
Types:
Sequence
Select i
on
I
terat i
on/r epeti
ti
on
I
mpl ement at i
onofdatastruct
ures
6.ERRORHANDLI NG
Typesofer rors
- Sy nt ax
- Runt ime
- Semant i
cs
- Logical
Err
orhandl ing
t
echniques.
Wr i
ti
nger rorhandl
ers
Oner rorresume
Oner rortogo
Errorobject
Debuggi ngt ool
s
7. SUB- PROGRAM
Meani ng of sub-
program Ty pesofsub-
programs
Privat esubpr ogram
Publ icsub- program
Scopeof
vari
ablesLocal
vari
ablesGl obal
vari
ables
8.Dat ast ructures
Dat ast ructures
Typesofdat a
struct ur es
- Ar ray s
- Recor ds
- Poi nt er
- St acksandqueues
- Set s
- Fi les
Sor tTechni ques
- Bubbl eshel l
- Sel ect ion
Sear chTechni ques
- Bi nar ysear ch
- Li nearsear ch
9.Li nki ngt odat abases
- Dat abasecont r
ols
- Dat acont rol
- Msdat aboundcont rol
s
- Act ivedat aobj ect(ADO)
Repor ts
Dat ar epor ts
10.Emer gingTr endsI nVisualBasi
c.
Emer gingt rendsi nv i
sualprogr
amming
Chal lengesofemer gi
ngtrendsinVi
sualBasi
c
Copi
ngwi
thchal
l
engesofemer
gingt
rendsi
nvi
sual
progr
ammi
ng.
Cont ent
1.I ntroduct iont ov isual Basic6. 0
VisualBasi c
I
ti sapr ogrami ngl anguageanddev elopmentenv ironmentt hatal lowsy out ocreate
progr amst hatr ununderwi ndowsOs.Wi thVBy oucancr eatepr ogramst hatinteract
witht heDat abases, inter actwi t
hi nternetandev enwi t
hhar dwar e.
Ev entDr ivenPr ogr ami ng
V.Bi sev entdr iven, meani ngt hecoder emai nsidleunt ilcal l
edupont or espondt o
someev ent .Anev entcanbeamousecl ick,akeypr ess, menusel ectione. t.
c.V. B
i
sgov ernedbyanev entpr ocessor .Not hinghappensunt ilanev entisdet ect ed.Once
anev enti sdet ect edt hecodecor respondi ngt othatev ent( ev entpr ocedur e)is
execut ed.
Ter mi nol ogi e
sa) For ms
Arewi ndowst haty oucr eat ef oruseri nterface.Af orm gener allyhasmanydi f
ferent
cont rols
placeduponi t.
b)Cont rols
Aregr aphi calf eat uresdr awnonf ormst oal lowuseri nteract ion,exampl esar e
text boxesl abel s,scr oll
bar scommandbut tonse. t.c.For msandcont rolsar e
somet imescol l
ect ivelyknownasobj ects.
c)Pr oper ti
es
Ever ychar act eristicofaf orm orcont rolisspeci fi
edbyapr oper ty
,exampl esof
proper ti
esi ncl udename, capt i
on,si ze,colour,positionandcont ent.
d)Met hods
I
sabui lt-i
npr ocedur et hatcanbei nvokedt oi mpar tsomeact iont oapar ticular
obj ecte. gpr i
ntmet hod.Exampl e: Me.printsum ‘ displ aysv al uehel dbyt he
var i
abl esum i nt hecur rentf orm.
e)Ev entPr ocedur e
I
sacoder elat edt osomeobj ect.Thi sisthecodet hati sexecut edwhenacer tai
n
eventoccur s.
f)Gener alPr ocedur e
I
scodenotr elatedt oobj ect s.Thiscodemustbei nv okedbyt heappl ication.
g)Modul e
I
ti sacol l
ect ionofgener al procedur es, v
ar i
abledecl arat i
onandconst antdef i
nit
ions
usedbyt heappl i
cat i
on.
h)Appl ication
I
sacol lectionofobj ectst hatwor kt ogethert oaccompl ishsomet hingusef ul.
I
nVbt heappl icat i
oni scal l
edapr oj ect.Apr ojectcoul dbet hemanagementof
av ideost or e, cal culat i
onofmor tgagese. t.
c
2.VI
SUALOBJECTS
i
)Obj
ect
I
sapieceofs/
wthathaspr
oper
ti
esandf
unct
ionst
hatcanbemani
pul
ated.
2.VI
SUALOBJECTS
VisualBasi cI nt egrat edDev elopmentEnv ironment( I.D.E)
I
.D.Ei saVBscr eeni nwhi chonecandev elop, run,testanddebugappl ications.It
containst heel ement swi t
hwhi chy oucandev eloptheuseri nt erf
aceofy our
applicat ion.El ement s/ component s/ partsofI DE( VisualObj ect s)
1.Menubar
I
tdispl ay st hecommandsy ouneedt owor kwi thVB.Menusar epr ovided f or
standar dact ionsl i
ke: fi
le, edit,v i
ew, windowandhel pandt oaccess
functionsspeci fict opr ogr ammi ngsuchas: project,formatanddebug
2.Standar dTool bar
Thest andar dt ool barhast hest andar di const hatar eshor t
cutcommandt ot he
menubarcommands.Theypr ovidequi ckaccesst ocommonl yused
commandsi nt hepr ogr ami ngenv i
r onment .
3.Tool box
I
tcont ainsasetoft ool st hatcanbeusedatdesi gnt i
met opl acecont rolsonaf orm
4.ProjectWi ndow
Thiswi ndowl istst hef ormsandmodul esi ny ourcur rentpr oject .
5.Pr oper tieswi ndow
Thiswi ndowl istst hepr oper tyset tingsf ort hesel ectedf orm orcont rol.The
proper tiesar echar act er i
sticsofanobj ectsuchasname, size, colour ,capt i
on
e.t
.c
6.For ml ay out swi ndow
I
tshowswher e( uponpr ogram execut ion)y ourf orm wi llbedi splayedr elativeto
your
moni tor ’
sscr een.
7.Codeedi torwi ndow
Thecodeedi torwi ndowi susedf orent eringandedi t
ingt hepr ogr ami ngcodef or
theappl icat ion.Eachf or m hasi tsowncodeedi torwi ndow. Bydoubl ecl ickingon
anobj ectt hecor respondi ngcodeedi torwi ndowwi l
l open.
8.Immedi at e, l
ocalandwat chwi ndows
Thiswi ndowsar eincludedi ntheI DEf orusei ndebuggi ngy ourappl icat i
on.
Theyar eav ailabl eonl ywheny ouar er unni ngy ourappl i
cation.
Cont rols
Aregr aphi cal feat uresdr awnonf or mst oal lowuseri nteraction. itisat ool used
todispl ayi nf or mat ionorr et ri
evei nf ormat ionf rom theuser .
Cont rolt y pes
1.St andar dcont rols
Arecont rolsal way spr esenti nthet oolbox
2.Cust om
cont rols
Arebr oughti nt ot heVBenv ironmentwhenneededandt heyext endonet ool box.
Descr
ipt
ionoft
her
olesofv
ari
ouscont
rol
s
Pict
ure
box
Poi
nter
I
satoolusedt
osel
ectanobj
ectt
obewor
kedon
Pict
ure
box
I
susedt odi splaygr aphi cal objectsort extandt oi ni ti
ateeventact ions.Iti
s
similart oani mageboxbuthasmor epr oper t
ies, redrawsl owerandcannotbe
stretched.
Label
Display sat extonaf orm.Thet extcannotber eassi gneddur i
ngpr ogram executi
on
thoughi tsappear ancecanbeal t
er eddur ingt hepr ogram execut i
ont houghi ts
appear ancecanbeal teredTextbox
Prov i
desameansofent er i
ngordi splay i
ngt ext.Thet extmaybeal r
eadyav ai
lableor
canbe
entereddur ingt hepr ogr am execut i
on.
Frame
Usedasacont ainerofagr oupofcont rols
Commandbut t
on
Usedt oact i
v ateanev entdr ivenpr ocedur e.
Checkbox
Usedi fmor et hanonesel ecti
onar et obemade.
Opt i
onbut ton
Areusedwhenonesel ect ionmustbemadebef or eanact i
oni scar ri
edout.
Combobox
I
saspeci altypeofl istboxt hatcombi nest hecapabi li
tiesofat extboxandal istbox.
I
tpr ov idesal istoft exti tem f orsel ect i
onbyt heuserdur ingprogr am execution.
I
temscanal sobeaddeddur ingpr ogr am execut ion.
Listbox
Prov i
desal istoft exti temsf ort hesel ectionbyt heuser .
Hor i
zont alscr oll
I
susedf ordr awi nghor izont al scroll
bar sonaf orm.
Ver t
icalscr ollbar
I
susedf ordr awi ngv erti
calscr oll
baronaf orm.
Timer
Allowst imedev entst ooccurr epeat edlyataspeci f i
ct imeinterval
Drivel istbox
Prov i
desawayofsel ect i
ngadr ivef rom al istofexi stingdriv
ers
Direct oryl i
stbox
Prov i
desawayofsel ect i
ngadi rector yfrom al ist
Fil
el istbox
Prov i
desawayofsel ect i
ngf i
leswi t
hi nagr oupoff iles.
Shapet ool
I
susedt odr aw; circles, ecl i
pses, squar esandr ect angleswithinfor ms
Linet ool
I
susedwhendr awingst raightl i
neswi thinforms.
Imagebox
I
susedt odi splaygr aphi cal objects
Dat acont rol
I
tpr ov idesameansofdi spl ayingi nformat i
onf rom exi sti
ngdat abase.
N/B:Thenumberoft
ool
sav
ail
abl
eont
het
ool
boxdependsonedi
ti
onandr
eleaseof
VB
youareusi
ng.
Sav i
ngaVBpr oject
Sav i
ngaVBpr ojecti sdif
ferentfrom otherappl i
cat i
onsbecauseVBoper ation
i
nv olvessav ingmul t
ipl
ef i
les
a) Tosav eaVBpr ojectforthef i
rstt i
me,sel ectthesavepr ojectascommand
fr
om t hef ilemenu.Thesav efil
easdi alogueboxappear .Youwi llhav eto
enteraf orm nameandt hencl i
ckt hesamebut t
on,theformi ssavedwi than
extension. fr
m
b)Af terthist hesav eprojectAsdi alogueboxappear s.Typet henameoft he
projectandi twillbesav edasf il
ewi thextension. vbp
Openi nganexi st ingproject
Youcanopenapr ojectwhenVBst art
sorf rom thef i
lemenu.Toopenapr oject
duringst artupf r
om t henewpr ojectdial
ogueboxt hatappearswhenVBi sstarti
ng,
cli
ckt heexi sti
ngt ab.Al i
stofexi sti
ngpr oject
swi llbedisplay
ed.IfVBi salready
runningcl oseal l otherprojectsthencl i
ckopenpr oj
ectcommandont hefil
emenu.
Theopenpr ojectdi alogueboxappear sf rom whichy oucansel ecttheexisti
ngt ab
3.PROGRAM STRUCTURE
VB FUNDAMENTALCONCEPTS
Dat atypes
Dat atypes Descri
ption
I
nt eger Awhol enumberwi thnofracti
onpart.Integerrangefrom -32768t o
Long 32 767
Number swhi char eintegersbuthavebi ggervaluesandrange.They
i
nt eger ran ge
Single fr
om
As i-
ng2
l,
e14
p7
r
e ,
4
c8
i
s3
i,
o648t
nr o2
ealco,
1
ns4
t7
a,
4
n8
t3
i
n,
6
c4
l
u7desaf racti
onalpart
.Thelargest
valueis
38
Doubl e 3
I
t.4x1
i ud0
ncl esaf racti
onal partbuthasfarmuchl argermagnit
udet hanthe
single
String r
Ce
haal
n
rau
cmb
terer
s c
eo
ncn
l
os
stadi
ent.Ho
nq w
uoe
tv
ae
t
iri
tma
oncanrn
ko
stbelargerthan1.2x10308
Bool
ean Dat
aty
pest
hathav
eonl
ytwol
ogi
cal
stat
esi
.et
rueorf
alse
Constants
Aconst antisav aluethatremai nsthesame.I tdoesnotchangeduri
ngprogr
am
execution.Therear et
hreet ypesofconst ant
s; str
ing,numeri
candnamed
constants.
Str
ingconst ants
I
sasequenceofchar actersencl osedinquotationmar ks.
Theyareusedtowri
te
non-numer i
cv aluesli
ketelephonenumber s,
addr essesandnames
Numericconst ants
Areeitherwhol enumber s(integer),doubl
eorsi ngle
Namedconst
ant
s
I
sidenti
fi
edbynamer at
hert
hani
tsact
ual
val
ues,
constkey
wor
disuseddecl
are
t
histypeofconst
ant
s
VARIABLES
Av ari
ableisamemor ylocati
onreferredtobynameusedt ohol dav aluethati
s
subjecttochangedur i
ngpr ogram executi
on.InVBt hef ol
l
owi ngrulesshoul dbe
fol
lowedwhennami ngvari
ables:
1.Thev ar i
ablenamemustnothav emor et han255char acter
s
2.Thev ar i
ablenamemustst artwithaletter.
3.Thel ettercaseisnotimpor tantwhendecl ari
ngvariables
4.Av ariablenamemustnotbear eser
vedwor d
5.Var iablenamesshoul dnothav espaces.
Av ari
ableisdecl aredusingthereservedwor dDI Mtheshor tform ofthewor d
dimension( size).I
tisusedt oassociateavariablewithaspeci fi
cdat atypee.g
Dim Fir
st_NameasSt ri
ngmeanst hatthevari
abl efi
rst
_namei softhet ypestr
ing.
VARI ANTS
I
sav ariablewhosedat atypeshasnotbeenexpl i
citlydeclaredbyt heprogram.
Theyar ecal ledvar iant sbecauset heirdat at y
peskeepsonchangi ngwi t
ht he
valuest heyhol d
Scope
Refert ot hel eveloft hepr ogr am t hatav ari
able,aconst antorapr ocedureis
recognized.Thescopeofav ar i
abl econst antissai dtobegl obalorlocal.Thescope
ofthepr ocedur e,v ariableorconst antissetbydecl ari
ngitasei t
herpr i
vateorpubli
c.
Thef ollowi ngt ermsar eusedi nt hisregar d:
1.Pr i
vat esub- pr ocedur e
2.Publ ic
3.Gl obal vari
abl es/const ant s
4.Local vari
abl es
Apubl i
cpr ocedur ecanbeaccessedf r
om anymodul eorf ormint heprogram
whi l
epr ivatepr ocedur eisaccessedi nt hemodul eorf orm wi t
hinwhi chiti
s
declared.
Av ariableorconst antt hatisdecl aredout sidethest andardmodul ebutwi thi
n
thesamepr ojectissai dtobegl obal .
Userdef i
neddat at ypes.
I
sadat at y
pewhosei ndi
vidual component sarest andarddat ait
ems
Usingsuf fi
xest odecl arev ari
abl esandconst ants.
Suffixesar especi al sy mbolsappendedt otheendofav ariabl
econst antname
i
nor dert oassoci at et hem wi thapar ti
culardat atype
Examples
Suff
ix Dat atype LongDecl
ar ati
on Shor
tdecl
arat
ion
% I
nt eger Dim Aasinteger A%
! Single Dim Xassingle X!
$ String Dim Aasstring Q$
& Longi nteger Dim CaslongintegerC&
# Doubl
e Di
m Pasdoubl
e P#
Oper ators
Theyi nclude;
i
.
Ari
thmet i
c i i
.
Relational i i
i
.
Logical
Ari
thmet
icoperat
ors
Ar
especi
alsymbol
sthatareusedt
owr
it
ear
it
hmet
icexpr
essi
ons.
N/
B:Thelastt
wor owscanbeexpl ai
nedasf ol
l
ows
1.Inanint
egerdivi
sion,eachofthenumber sbei
ngdi v
idesi
sfir
stroundedt
o
becomeanintegerthent hequoti
entistr
uncatedtoanint
eger.
2.TheMODoper at
orreturnstheremainderofanint
egerdiv
isi
on.
Oper
atorsPrecedence/Hier
achy
Arit
hmeticoperator
shavet hefol
lowingor
derofprecedencewhenusedina
program Exponenti
ati
on,Multi
pli
cat
ionandDivi
sion,int
egerdi
vi
sion,i
nteger
remainder,addi
ti
onandsubt r
acti
on.
i
. Rel
ati
onalOper
ator
s
Isusedinanexpr
essi
onthatr
etur
nsatrueorf al
sev al
uewheneval
uated.The
operat
orscancomparenumeri
cvari
abl
es,constantsorexpr
essi
ons.
Operat
or Name
= Equalto
<> Notequal t
o
> Great
erthan
< Lessthan
<= Lessthanorequalt
o
>= Great
erthanorequalt
o
Logi
caloper
ator
s
oper
ator Oper
ati
on
And Result
sinacondit
iont
hati
strueifbothexpressi
onsaretr
ue
Or Result
sinacondit
iont
hati
struei foneofthecondi
ti
onistrueorbot
h
Xor aretr
Resulu
te
sinacondit
iont
hati
strueifoneofthecondit
ionistr
ueandthe
otheri
s
Not f
Na
el
se
gat
esthev
alueofalogi
cexpression
TheAssi gnmentSt at
ement
Anassi gnmentst at
ementi sanexecut abl
est at
ementthatassi gnswhat ev eri
son
ther i
ghtoft heassignmentoper atortothev ar i
abl
e.
ThePr intSt at
ement
Thepr intstatementdi splaysdat aontheact iveform ofyourVBpr oject
.I tcanbe
usedt odi splayprocessingr esult
sofapr ogr am.Thest r
uct ureofthepr int
statementi s:
Printvariablename( thispr i
ntsoutthev aluehel di
nav ariable).Theuseofcomma
tosepar atethev ari
ousel ement stobeout putbytheprintst at
ementmakest hem
tobewi delyspacedont hescr eentohav eacompactdi splaywi ththev arious
outputscl oset oeachot her,thenuseasemi colontosepar atethev ari
ous
element s.
Libraryfunctions/ I
n-builtfunctions
Aremodul esthathav ebeenpr e-writ
tenandi ncludedi nthev i
sual BasicLanguage.
Af unctionperformssi ngletaskl i
kecal culatingMat hemat i
cal expressi
onst hen
returnsav alue.Af unct i
onwi llusuall
yhav eanameandcanbecal l
edwhenneeded
toper form apar t
iculartask.
Al i
braryfunctionisaccessedbyst atingi t
snamef oll
owedbyt hei nfor
mat i
onthat
mustbesuppl i
edt ot hefunctionencl osedi npar enthesis.Thisprocessi scall
ed
calli
ngaf unction. Thev alueshel dinthepar ent hesisarecal l
edar gument s.Whena
functioniscalled,itusest he
suppl i
edar gument st oper f
orm anoper at i
onandr eturnav al
ue.
Funct i
on Cal l Descripti
on
Dat e Z=Dat e( ) Returnthecur rentdat e
w
Exp Z=Exp( W) Ret urnsthev al ueofe
Sqr Z=Sqr( w) Returnsthesquar erootofw
Log Z=Log( w) Ret urnsthenat ural l
ogar i
thm ofw
Str Z=St r(w) Returnsast ringwhosechar actersarewe. gstr
Cos Z=Cos( w) Ret (6.
80
ur)=”
6
nst.80 ”
hecosi neofw
Abs Z=Abs( w) Ret urnabsol utev alueofwe. gAbs( .8)
Ucase Z=Ucase( w) Ret urnsupper caseequi val
entofw
I
nt Z=I nt(w) Returnsthel argesti ntegert hatisalgebraical
lylessthanw
e.gInt
Time Z=Ti me (
R2
e.
2
t)
ur=
n2t
hecur rentsy stem time
For
mat Z=For
mat For
mat
stheout
putt
oappearasst
atement
s
Usingthef
ormatfuncti
on
Thef
ormatf
uncti
onshel
pstheprogrammert
odi
spl
aydat
ainmanydi
ff
erent
f
ormat
s.Expr
essi
on
Printformat(
16.778994,“##.##” ) 16.78(not i
cethe
rounding)Pri
ntformat(Now, “
mm- dd-y
yy”
) 1-20-
20105
PrintFormat(15678;“
##,###. 00”) 15,678.00
Label 1.Capt
ion=Format$( sprice,“
#####.##”
) 10,630.75
Convert
ingnumer icst
ringtoav al
ue
I
fy ouenteranumber ,
inat extbox,t
hebestwayt
oconver
titi
ntoaval
ueistouse
theValfunction.Thi
si sbecausethecomputert
reat
sanythi
ngtypedi
nt het
ext
boxasast r
ing.Thev alfunct
ionoperat
esonthestr
ingandret
urnsanumerical
val
ue.
Convert
ingav aluetoastring
Assumingapar ti
cularv
ariabl
ehasanumer i
calvalueandyouwishtodispl
ayt he
val
ueinat extbox, t
henyouhavet oconvertt
hev aluetoast
ringf
ir
st.Supposethe
nameoft hetextboxistxtAreaadntheintegervariabl
eisXthen;t
xtArea.text=
str
(X)di
splaythev al
ueinXasst r
inginthetxtAr
ea.
4.PROGRAM WRI TI NG
Project
Createapr ogram t hatcanbeusedt ocalculatet hear eaofar ect
angl e.Thepr ogram
should
promptt heusert oent ert helengthandt hewi dthoft her ect
angle.Tocr eate
thepr ojectproceedasf oll
ows;
1.Openv i
sual basi candsel ectstandard.EXEf r
om thenewpr ojectdialogbox.A
blank
form wi l
l be
display ed.
2.Pl acet hreet extboxesandt wocommandbut tons.Doubleclickt hetextbox
toolont het ool boxthencommandbut ton.Addanot hercommandbut t
on
.Uset heshapet ooltoplacear ectangleont hef or
m.Dr agthecont r
olstot he
desiredl ocationont hef orm andrepeatt hepr ocessunt i
lyouhav ethe
i
nt er
facebel ow.
3.Thenextst epi st odefinethesetofpr oper ti
esf oreachcont rol.Todot his,
ri
ghtclickont hecont rolthenclickpropert i
es.Seteachcont rol inthe
propertieswi ndow.
N/B: Theconv ent i
onal wayofset t
ingthenamepr oper t
yofanyobj ecti nVBi stouse
object
prefi
xes.Suchast xtf ortextorboxes, lblforl
abel scmdf orcommandbut t
onset c.
4.Aft
ersetti
ngthepr oper
ti
es,wecannowwr i
tetheeventprocedur
esthat
cal
culat
esthear eaoft herect
angl
eonceval
uesar eenter
edinthetxtl
engt
h
andtxtWidt
htext boxes.Towritet
hecodedoublecli
ckcalcul
atebutt
onand
wri
tethecodelistingbelow.
Pr
ivat
esubcmdcal
cul
ate_
cli
ck(
)
Dim Lassi ngle,W assingle,Aassingl
e
L=v al(
txtl
engt h.
text)
W =v al
(txtWidth.t
ext)
A=L*W
TxtArea=St r(A)
Endsub
Pri
vatesubcmdExi t
_Cli
ck()
‘exi
tfrom thepr ogram
End
Endsub.
5.Runt hepr oj
ect.Enteraval
ueinthelengt
handanotheri
nthet
xtWidt
htext
boxest henclickthecalcul
atebut
ton.Thear
eaoftherect
angl
eis
displ
ay ed.
Decl
arat
ionofv
ari
abl
es
Therearetwoway sofdecl ari
ngv ari
abl es
i
. Expli
citdeclarat i
on
Thev ar
iableisdeclaredi nthedecl arationsecti
onoftheprogram oratt
he
begi
nningofapr ocedur ee.g
Dim AAsi nteger‘explicitdeclar
at i
on’
Dim nameasst r
ing‘expl ici
tdeclaration.
i
i. I mpl i
citdeclarat i
on
Thev ar
iableisdeclaredont hefly.It
sdat aty
peisdeducedfrom t
hedeclar
ati
on
ofothervariabl
ese.g
Dim Aasi nteger‘explicit
Dim BAsi nteger‘explicit
C=A + B ‘ I
mplicitdecl ar
ati
on.
Pr
ojectExampl
es
Exampl e
Calcul
ationofar
eaofar
ect
angl
e,l
engt
handWi
dthent
eredbyt
heuser
.
a).
UserInterf
ace/UI
Frmarea
Calculati
onofarea
Ent
er Txt
len
l
ength
Enter Txt
wid
width
TxtA
Ar
eai
s
Exi
t cac
l
cu
al
l
ca
ut
e
lat
e
cmdexi
t cmdcal
cul
ate
b).
Code
Pri
vat
esub
cmdexit
_cl
i
ck(
)End
Endsub
Pri
vatesub
cmdcalculat
e_ cli
ck()Di
m Las
i
nteger
Dim W asinteger
Dim Aasinteger
L=v al
(t
xtl
en.text)
W =v al
(t
xtwid.text)
A =L*W
TxtA.t
ext=st r( A)
Endsub
Example
A Vbprogram t
oacceptt
her
adi
usofaci
rcl
e,cal
cul
ateanddi
spl
ay
i
tsareaa).
UI
FrmArea
Area
calcul
ati
on Txt
R
Ent
err
adi
us Txt
A
Ar
eai
s
Comput
e
Cmdcomput
e
b).
Code
Pri
vat e sub
cmdcomput e_cli
ck() Dim R
as si ngle,Area as si ngl
e
Constpi eassingle=3. 142
R=v al(t
xtR.
text)
Area=pi e*R*R
TxtA.text=Str(Area)
Endsub
Exampl e
Projectoncalculationofsum oft
wonumber
s
Frmsum n Sum i
s
E u
Summationof
n m
numbers
t 2
Ent
ernum 1 e
r
Txt
nu
m1
T
x
cmd t
sum u
ADD
m
2
l
b
l
r
e
s
u
l
t
Code
Pri
vatesub
cmdsum_ cl
ick()Dim aas
i
nteger ,
basi ntegerDims
asinteger
a=
val
(txtnum1.text)
b=val(t
xtnum2.text)
s=a+b
l
blr
esul t
.capti
on=s
EndSub
Exer ci
se
Wr i
teaVBt hatacceptt heheightandr adi
usofaclosedcy
li
nder,
comput
eand
displayitssur facearea.At t
achy ourcodet oacommandclickevent
.
Privatesub
cmdsur facear ea_ cl
i
ck()Const
pieassi ngl e=3. 142
Dim heightasi nteger,r
adiusasi nteger
Dim sur f
aceAr eaas
singlehei ght=
val(t
xth.t
ext )radius=
val(txtr
.text)
Sur faceAr ea=2*pi e*r adi
us*r adius+(pie*2*
radi
us*
height)Lbl area.capti
on=sur faceAr ea
Endsub
Frmsar
ea
Surf
acear
ea
Txt
r
Ent
err
adi
us
Txt
h
Ent
erhei
ght
Lbl
area
Sur
facear
ea
i
s
CALCULATE Cmdsur
face
CONTROLSTRUCTURES
a.Sel
ecti
oncontrolstr
uctures
i. I
f….
.el
seconst r
uct
Usedtowri
teprogr
amst hatrequir
ebr
anchi
ngdependi
ngonat
estonsome
condi
ti
on
-
Syntaxis:
If(condit
ion)t
hen
Stat
ement(
s)Else
St
atement(s)
EndI F
Example
Apr ogr
am 2acceptt
wonumber
sanddet
ermi
net
hegr
eat
est
a).Useri
nterf
ace
b)
Fr
mcompare
Compar
ison
Ent
erf
ir
stnum Txt
num
Ent
ersecond 1
num
t
xtnum2
pi
cresul
t
cmdcompar
e
Cl
ear
cmdcl
ea Compar
e
r
privatesubcmdcompar e-cl
ick(
)
dim num1as
i
nt egerdi m num2
asi nteger
num1 = v
al
(txtnum1. text)num2 =
val ( txtnum2. text
) if
(num1>num2) THEN
picresul t
.pri
nt“ num1isthegreatest”
else
picResul t.pr
int“ num2isthegreatest”
Endi f
end
sub
privatesub
cmdcl ear_cl
ick()
txtnum1. text=
““t xtnum2. text=””
Endsub.
Ifwit
hEl seIf
Usedinsituat
ionswher
ewehav
emor
ethanonecondi
ti
ont
otesti
nthepr
ogr
am.
-
ItsSyntaxis:
I
f(condi
tion1)Then
Statement1
Elseif(condit
ion2)
Then
Statement2
El
sei f(conditi
on3)
Statement 3
:
.
El
se
StatementN
Endi f
Example
Aprogram t
oacceptst
udentposi
ti
oni
ncl
assanddisplaycat
egor
yaspert
het
abl
e
bel
ow
Posi
ti
on Categor
y
1-
3 Top3student
4-
5 Top5student
6-
10 Top10st udent
a) User
i
nterf
ace
Fr
mcategor
ies t
xtPos
Cat
egori
ze
Ent
erposi
ti
on
pi
cResul
tcmdcat
egor
ize
cat
egor
iz
e
privatesubcmdcat egorize_cl
i
ck()
dim posi ti
onasi nteger
posi ti
on=
val(txtpos.text)
i
f( posi t
ion>=1)and( positi
on
<=3) Thenpi cr esul t
.pri
nt” t
op3
student ”
Elsei f(position>=4)and( positi
on<=5) Then
PicResul t.print“top5st udent”
Elsei f(position>=6)and(posi ti
on<=10)Then
Picresul t
.print“ top10st udent”
Else
Picresul t
.print” Youar enotcat egori
zed”
Endi f
Endsub
Exer ci
se
WriteaVBpr ogr
am t
oacceptst
udentmar
ksi
nclassanddi
spl
aygr
adeas per
thet abl
ebel
ow.
Mar ks Grade
70-100 A
60-69 B
50-59 C
40-49 D
<40 F
a)
.Useri
nter
face
Fr
mgrade
Gr
ade
marks t
xtmar
k
Ent
er
mar
ks
spi
cresul
t
GRADE cmdgr
ade
priv
atesubcmdgr ade
–Click()Dim mar ksas
i
nteger
Mar ks=v al(t
xtmarks.t
ext)
I
f( marks>=70)and( marks<=100)Then
Picresult
.print“A”
El
sei f(mar ks>=60)and( marks<=69)Then
Picresult
.print”
B”
El
sei f(mar ks>=50)and( marks<=59)Then
Picresult
.print“C”
El
sei f(mar ks>=40)and( marks<=49)Then
Picresult
.print“D”
El
sei f(mar ks<40)Then
Picresult
.print“F”
El
se
Picresult
.print“I
nvali
dentry”
Endi f
Endsub
USI
NGOPTI
ONANDCHECKBOXWITHIFCONSTRUCTSELECTI
ON
CONTROLSTRUCTURE
OPTI
ONBUTTON
-
Cont
rol
usedt
omakeasi
ngl
esel
ect
ionoutofsev
eral
opt
ionsav
ail
abl
e.
VALUEPROPERTY
Thevaluepropert
yisusedt
oindi
cat
ewhethert
heopti
onbutt
oni
ssel
ectedornot
.
Avaluepropert
yofTRUEmeanstheopt
ionbutt
onissel
ect
edandaval
uepropert
yof
FALSEmeansnosel ecti
onmade.
PROGRAM EXAMPLE:
Program t
opromptusertoenterpr
inci
palamount,cal
cul
ateanddi
spl
ayi
nterest
basedont hegendersel
ect
ed.Thecrit
eri
afori
nter
estrat
esaregi
veni
nthetable
below.
GENDER I
NTERESTRATE
Male Awar
d20%ofPri
nci
palamount
Female Awar
d15%ofpri
nci
palamount
a)
.UserI
nter
faceandpr
oper
ti
es
t
xtA
opt
mal
e
opt
femal Pi
cResul
e t
cmdComput
e
b)
.Code
Pri
vateSubcmdcomput e_Cl
ick()
Dim AmountAsDoubl e,int
erestAsDouble
Amount=Val (t
xta.Text)
Pi
cresult.
Cls
I
f(Optmal e.
Value=Tr ue)And( Optf
emale.
Value=Fal
se)
Theninterest=20/100*Amount
Pi
cresult.
Print"
Interest=" ,i
nter
est
El
seIf(Optfemale.Value=Tr ue)And( Opt
male.Val
ue=Fal
se)
Theninterest=15/100*Amount
Pi
cresult.
Print"
Interest=" ,i
nter
est
El
se
MsgBox"Pl
easesel
ect
Gender
"EndIf
EndSub
CHECKBOX
-
Cont
rol
usedt
omakemor
ethanonesel
ect
ionoutofsev
eral
opt
ionsav
ail
abl
e.
VALUEPROPERTY
Thevaluepropertyi
susedt
oindicat
ewhethert
hecheckboxi
sselectedornot
.
Avaluepropertyof1meansthecheckboxi
sselect
edandavalueproper
tyof0
meansnosel ecti
onmade.
PROGRAM EXAMPLE:
Progr
am topr
omptusertoentersal
aryearned,
cal
cul
ateanddi
splayt
axbasedon
thest
atussel
ect
ed.Thecri
ter
iafort
axratesaregi
veni
nthetabl
ebelow.
STATUS TAXRATE
Marri
edonly 20%ofsal
ary
Study
ingonl
y 15%ofsal
ary
Marri
edandStudy
ing 10%ofsal
ary
a)
.UserI
nter
faceandpr
oper
ti
es
t
xts
chkM
chkS
Pi
cResul
t
cmdComput
e
b)
.Code
Pri
vat
eSubCMDCOMPUTE_ Cl
i
ck(
)
Di
m SALARYAsDoubl e,
taxAsDoubl
e
SALARY=Val(TXTS.
Text)
Pi
cResul
t.
Cls
I
f(Chkm.
Value=1)And( chkS.
Val
ue=0)Then
tax=20/100*SALARY
PicResult
.Pri
nt"Tax=",
tax
ElseIf(
chkS.Value=1)And( Chkm.Val
ue=0)
Thent ax=15/100*SALARY
PicResult
.Pri
nt"Tax=",tax
ElseIf(
Chkm. Value=1)And( chkS.
Val
ue=1)
Thent ax=10/100*SALARY
PicResult
.Pri
nt"Tax=",tax
Else
MsgBox" Pl
easeselect
status"EndIf
EndSub
i
i. CASECONTRUCT
Pr
ogramsaremoresimpletor
eadandunderst
andwhenacaseconstr
uct
i
nsteadofi
fconst
ructi
susedtowr
it
eprogramswhichi
nvol
vedeci
sions.
I
tsSyntaxi
s:
SelectCaseexpressi
on
Caseexpression1
St
at ement
1
Caseexpression2
St
at ement
2
⁞
Case
else St atementN
Endsel
ect
Example
Aprogram toacceptt
heposi
ti
onofast
udenti
naclassanddispl
ayhi
scat
egor
y
asperthetabl
ebelow.
Posi
ti
on Cat
egor
y
1-
3 Top3students
4-
5 Top5students
6-
10 Top10students
a)
.Useri
nter
face
Fr
mposi
ti
on
Det
ermi
nat
ionofcat
egor
y
Keyposi
ti
on pi
cresul
t
Cat
egor
iz
e
y
o
r
b)
.Code
Priv
at esubcmdcat egory–Click()
dim positi
onasinteger
positi
on=v al
(t
xtpos.text
)SELECT
CASEposi ti
onCase1
to3
Picresult
.pr
int“
top3st udent”
Case4t o5
Picresult
.pr
int“
top5st udent”
Case6t o10
Picresult
.pr
int“
top10st udent”
Caseel se
Picresult
.pr
int”
Youent eredvali
dposi
ti
on”
Endsel ect
Endsub
Exerci
se
1.Rewr i
teapr
ogr am togrademarksusingthecaseconstr
uct
2.Wr i
teavbprogr am t
hataccept
stheinital
softhecol
oranddispl
ayi
tsname
i
nful
laspertable.
I
nit
ials Col ournameinful
l
R Red
B Bl ue
G Gr een
a)
.User
i
nter
face
Fr
mcategor
ize
t
xtmar
ks
Cat
egori
ze
Ent
ermar
ks
pi
cresul
t
Det
ermi
ne
cmddet
ermi
ne
b)
.Code
pr
ivat
esubcmddeter
mine_
cli
ck(
)
di
m marksasi
nteger
marks
=val
(t
xtmark.
text)
SELECTCASEmar ks
Case70t o100
Pi
cresul
t.
pri
nt” A”
Case60t o69
Picr
esult.
pri
nt“B”
Case50t o59
Picr
esult.
pri
nt“C”
Case40t o49
Picr
esult.
pri
nt”D”
Case0t o39
Picr
esult.pr
int“F”
Caseelse
Picr
esult.
pri
nt”Youent
eredi
nval
i
dmar
ks”
Endselect
Endsub
b).
Repet i
tion/i terati
oncont r
ol str
ucture
i
. TheFor .
..
Nextloop
Usedt oexecut eoneormor estatement sf
orpredeter
minednumberoft
imes.
-Syntaxis:
Forcont rol_vari
abl e=ini
tial
_val
uet ofinal
_val
ue
Statement (
s)
Nextcont rol_
v ariabl
e‘incrementv al
ueofcont r
ol_v
ari
able
-
Youcanal somaket heforloopt oski
psome
i
terati
onse. ga)ForI=1t o10st ep2
Picresult.pri
nti
Nexti
b)Fori =10t o1step- 2
Picresult.pri
nti
Nexti
Exampl e
Apr ogram t
odi
spl
aynumber
s1
to5
a).UI
Frmdi spl
ay
Display pi
cdi
spl
ay
number s
cmddi
spl
a
b).
Code
Pri
vatesub
cmddispl
ay_cl
i
ck(
)Di
mIas
i
nteger
ForI=1t o5
Pi
cdi
spl
ay.
pri
nti
Nexti
Endsub
Exampl
e2
Aprogr
am t
ofi
ndsum oft
hreenumber
sent
eredbyt
heuser
.
Frmsum
Add
numbers pi
cresul
cmdsu
b).Code
Privatesub
cmdsum_ cli
ck(
)DimIas
i
nteger
Dim sum as
i
ntegerDi m num
asi ntegerSum =
0
ForI=1t o
3
num = i nput
box (“ Key in number
”,
“addition”)
sum = sum +
num
NextI
Picresultpr i
nt“sum ofnumber
s=”,
sum
End
sub
i
i) do and whi l
e
l
oops
Usedtoexecuteoneormor est
atemetsbasedonat
estonsome
condi
tion
a)Do
loops
1.Dounti
l(condi
ti
on) 2.Dowhil
e
(
condi
ti
on)Statement
s(s)
Stat
ement
s(s)
Loop Loop
3.Do 4.Do
Statements(s)
Statements(
s)Unti
l(condit
ion)
While(condi
ti
on)
-Wit
hloops1and2thecondit
ioni
stest
edbeforet
hest at
ementsi
nsidethe
l
oopar eexecut
ed
-Wit
hloops3and4thestat
ementsareexecut
edatleastoncebef
orethe
condit
ionis
test
ed.
b).
Whilel
oop
-I
tsynt
axis:
Whil
e(condi
ti
on)
St
atement(
s)
Wend
-
Exactl
ythesameastheDowhile.
.Loop,andaswit
ht heDowhil
e..
loop,t
he
Whil
e..
Wendloopexecut
esst
atementsinsidei
taslongasthecondit
ionseti
s
t
rue.
Exampl e
Program usi
ngwhi
l
e..
wendl
oopt
hatdi
spl
ayst
henumberser
ies:
3,
7,11,15
a).
UI
Fr
mdispl
ayser
ie
s
Di
spl
ayseri
es pi
cdi
spl
ay
cmddi
spl
a
b).
Code
Privatesub
cmddi splay_cli
ck(
)Di
m num
asinteger
num=3
Whi l
e( num<=15)
Picdisplay.
print
num num=num+4
Wend
Endsub
Example:
Apr ogr
am thaaccept
sandcal
cul
atest
hesum oft
wonumber
susi
ngasub
procedure.
a)
.Useri
nter
face
fr
mProcedureadd
Addi
ti
onpr ocedur
e
Ent
ernum1 Txt
n1
Txt
n2
Ent
er
num2
Txt
s
Sum i
s
Add cmdadd
b).Code
Privatesubcmdadd-
cli
ckDi m xassingle,
y
assi ngl
eX=
val(t
xtn1.t
ext)
Y=v al
(t
xtn2.Text)
Calladd(x,
y)
Endsub
Privatesubadd( n1assingl
e,n2as
single)Dim Sassingle
S=n1+n2
Txt
s.text=
st
r(S)Endsub
-
Subproceduresmakeapr
ogram easytoread,
modi
fyanddebug.Sub
pr
ocedurescanal
sobecal
ledseveral
timesduri
ngt
heexecut
ionofthe
pr
ogram.
Passing(transmi t
ti
ngv aluestoasubpr ocedur
e)
Thev ari
ablesn1andn2appear inginthesubprocedurearecalled
parameters.Theyar eplacehol dersforval
uespassedt otheprocedure.
Exercise
Wr i
teaVbpr ogram usingt wopr ocedures.Thefi
rstprocedur
edi spl
aysa
messageshowi ngwhatt hepr ogram does.Thesecondaccept st he
di
mensi onsofat r
apezi
um, cal
culatesanddispl
ay si
tsarea.Bot h
proceduresdisplayinf
ormat ioninthesamepi ct
urebox.
a)
.UI
fr
mt r
apezi
aArea
Trapezi
aArea
Ent
ersi
deA Txt
a
Ent
ersi
deB Txt
b
txt
h
Ent
er
rH
Hei
ght
pi
cresul
ts
Comput
e cmdcomput
e
b).Code
pri
v atesub
cmdcomput e()Dim
areaassi ngle
a=v al(
txta.Text
)
b=v al(
txtb.Text)
h=v al(
txth.t
ext)
callprocdispl
ay()
callCalcArea(a,
b,h)
Endsub
pri
vatesubpr
ocdi
splay
()
pi
cresul
ts.
Pri
nt”
Thisprogr
am cal
cul
atesar
eaofTr
apezi
um”
Endsub
pr
ivatesubCalcArea(
asingl
e,bassi
ngl
e,hassi
ngl
e)
di
m areaassingle
ar
ea=0. 5*(a+b)*h
pi
cresul
ts.
Pri
nt“areais“
,
ar
eaEndsub
PARAMETERPASSI NG
PASSINGAVARI ABLEBYREFERENCETOASUBPROCEDURESupposea
var
iabl
ecalli
targappearsasanar gumenti
nacallstat
ementandits
corr
espondi
ngpar amet
erinthesubstatementi
spar.Aft
ert
hesubpr ocedur
e
i
sexecuted,ar
gwi ll
havewhateverval
ueparhadinthesubprocedur
ehence
notonl
yisthevalueofargpassedtoparbuttheval
ueofparispassedback
toarg.
Exampl e
Priv
atesubcmddi spl
ay -
cli
ck()Dim amtassi ngle
picr
esult
.cl
s
amt=2
picr
esult
s.pr i
nt
amt ;
callt
riple
(amt)
picr
esult
.printamt;
Endsub
Priv
atesubt r
ipl
e(byrefnum assi
ngl
e)
picr
esult
.Print
num; num =3
*num
picr
esult
.printnum;
Endsub
Output
2266
-I
tprov
idesavehicleforpassingvaluesf
orm asubpr
ocedur
ebacktothe
placef
rom whi
cht hesubpr ocedurewascall
ed.Thevar
iabl
eamtissai
dto
bepassedbyreference.
Scopeof
vari
ablesa)Local
vari
ables
whent hesamev ar
iabl
enameappearsi
ntwodi
ff
erentsubpr
ocedur
esorsub
procdure
andanev entprocedur
e,vi
sual
basi
cgivest
hev
ari
ablesepar
atei
denti
ti
esand
treat
sthem astwodif
ferentv
ari
abl
es.Aval
ueassi
gnedt
oavari
abl
einone
partoftheprogr
am wil
lnotaff
ectt
heval
ueoft
heotherl
i
kenamedvari
abl
ein
theotherpartt
he
progr
am, unl
essofcourset heval
uesarepassedbyacal l
stat
ement.Al
so
eachti
measubpr ocedureiscall
ed,
alldecl
aredvari
ablesthatar
enot
parametersassumetheirdefaul
tval
ues(numeri
cv ar
iableshavedef
aul
tval
ue
0andstringvari
abl
esdef aulti
sempty).
Exampl e
Priv
at esubcmddi spl
ay–
cl
ick()Di m xassi ngle
‘
Demonst ratethelocalv
alueofv
ari
abl
es
Picresults.cls
X=2
Picresults.pri
ntx
Calltri
vial
PicResul ts.Print
xCal ltr
ivial
PicResul ts.Print
xCal ltr
ivial
PicResul ts,Pri
nt
x;Endsub
Priv
atesubt ri
vi
al()
Dim xassi ngl
e
‘
Dosomet hingtr
ivi
al
PicResul
ts.Pri
nt
x,x=3
PicResul
ts.Pri
ntx,
Endsub
Output
2032032
PicResult
s.Pri
nt“num1=”
,num1
PickResult
s.Pri
nt“num2=“,
num2
Endsub
Priv
atesubaddandincr
ement(
)
‘
Displaynumbersandthei
rsum
PicResul
ts.
pri
nt”
sum of“;
num1;“
and”
;num2;
‘i
s”;
num1+num2
Num1=num1+1
Num2=num2+1
Endsub
Out
put
Sum of2and3i
s5
Num1=3
Num2=4
FUNCTI ONSPROCEDURES
Af unctioni
ssi mplyagener alprocedur ethatr
eturnsonev al
uetothefunti
onc
thatcal l
sit
.Althought heinputcaninv olv
eseveralvalues,t
heoutputal
way s
consi stofasinglevalue.Theitemsi nsidetheparenthesiscanbeconstants,
variablesorexpressions.Funct i
onpr oceduresaredef i
nedbyfuncti
onblocksof
thef orm:
Priv
at efuncti
onf
unct
ionname(
var
last
ype1,
var
2ast
ype2)asdat
aty
pe
Statement (
s)
Functionname=expressi
on
Endf uncti
on
Thev ari
ablesinthetopli
nearecal l
edparametersandv ariabl
esinthef uncti
onblock
thatar enotpar ameter
shav elocalscope.Functionnamesshoul dbesuggest iv
eof
ther oleperformedandmostconf or
mt otherulesfornami ngvari
ables.
Exampl eoff unct
ionprocedur
es
Privatefunct i
onFtoC(tassingle)assingl
e‘convertFahrenhei
ttemper atureto
Celcius
FtoC=5/ 9* (t–32
)Endf unction
Example
Thefoll
owingprogram usest
hef
unct
ionFt
oC t
oconv
ertaFahr
enhei
ttemper
atur
e
to
Celci
ustemperatur
e.
a)
.UI
Fr
mconv
ert
Conv
ertFt
oCel
cius
Enter Txt
f
Fahrenhei
t
Temper at
ure
pi
ccel
cius
CONVERT cmdconv
ert
b).
Code
Pri
v atesubcmconv ert–
cl
ick()Dim Cel ci
usAssi ngle
Di
m fassi ngle
f=v al(t
xtf
.text)
Celcius=FtoC( f
)‘cal
lthefuncti
onFt
oC
Pi
ccel ci
us.print“cel
ciustempis“,
CelciusEndsub
Privat
eFunctionFtoC(tassi
ngl
e)assingl
e
FtoC=( 5/9)*(t–
32)Endf unct
ion
Exampl e
Apr ogam tocalcul
atethehy
potenuseofari
ghtangl
etr
iangl
egi
veni
tsbaseand
height.
f
rmhy
p
Hy
pot
enusecal
cul
ati
on
Ent
erHei
ght Txt
h
Ent
erBase Txt
b
Ent
erHei
ght
pi
cHy
p
Comput
e cmdcomput
e
Code
Pri
vatesubandcomput eand
cl
ick()Dim aassi ngle,
Hy pas
si
ngle
Di
m bassi ngle
a=v al(
txt
h.Text )
b=v al(
txtb.Text)
Hyp=Hy pot enuse(a,b)
Pi
chy p.
Pri
nt“ Hypotenuseis“,
HypEndsub
Pri
vatefuncti
onhy pot
enuse(heightassi
ngl
e,baseassi
ngl
e)
assingl
ehy potenuse=sqr(
height^2+base^
2)
Endfuncti
on.
Exerci
se
WriteaVBprogr
am usingafunct
iont
hataccept
st hedimensi
onsofacl
osed
cyl
inder
,cal
cul
atesandret
urnsit
ssur
faceareafordispl
ay.
DATASTRUCTURES
Array
s
Isadatast
ructur
ethatst
oresseveral
dat
aitemsoft
hesametype.Thef
igur
ebel
ow
shows
howdataoftypeint
egeri
sstoredinanar
ray.
20 30 80 120 200 250
i
ndex 0 1 2 3 4 5
Thearrayhascel
ls.Thenumber
s0to5arecal
l
edar
rayi
ndi
cesorsubscr
ipt
s.
I
nV. B
anarraystar
tsfr
om cell0asshowni
nthe
tabl
e.
One di
mensi
onal
ar
ray
Decl
ari
ng an
ar
ray
Todeclar
eanarrayusethest
atementDi
m ArrayName(n)AsDat at
ype,
wherenstandsfort
henumberofelementsi
nt hear
raye.g
Dim scor
es(4)asint
egerisanarr
aythatwil
lholdfi
veinteger
val
ues
Assi
gni
ng val
ues t
o an
ar
ray
Example
Toassignanumer icval
uetolocati
on4ofthear
rayscor
esweusethe
stat
ementscor es(
4)=90
Todisplayavaluehel
dinlocati
on3ofthearr
ayscoresweuset
he
stat
ementpicresul
t.
pri
ntscores(3)
NB:ifthear rayisverylar
geandy ouwi shtoreadorent
ervaluesinit
,it
couldbe
verytediousenteri
ngav al
uecellbycelli
.escor
e(0)=10score(1)=2..scor
e
(n)=xToav oi
dt hi
s,theforl
oopcanbeused.Remembert hisloopisused
wheret henumberofi ter
ati
onsarepredeter
minedhencei
tssuitabi
li
tyf
oruse
witharrays.
NB:Thearraydeclarati
oncanal sobeadj ust
edas
fol
lows:Dim A(
1t o5)asi nteger
I
nt hi
scasethearrayv ar
iableAi sdecl
aredtohol dfi
veel
ement
sbutwehav
e
for
cedthefir
stavailabl
elocationinthearraytobe1.
Example(ononedi mensi onar r
ay)
AV. Bpr
ogram t
opr ompttheuserf orf
iveintegerval
uest
obestor
edin
arr
aythendispl
ayt hem.
f
rmdi
spl
ay
Di
spl
ay
pi
cdi
spl
ay
DI
SPLAY
cmdDi
spl
ay
b).Code
PrivatesubcmdDi splay–
cl
ick()Di m A(4)asi nteger
Dimi asint
eger,jasi nteger
Fori =0t o4
A( i
)=i nputBox(“enterar r
ayval
ue”,
“ar
ray
s”)
Nexti
Forj =0t o4
Picdisplay.
Pri
ntA( j)
Nextj
Endsub
Example
AVBpr ogram topr
omptuserf
oranar
rayof3i
ntegerel
ement
s,comput
eand
di
splaytheirsum
a).
UI
f
rmsumar
ra
y
Sum ar
ray
Pi
csum
cmdcomput
COMPUTE
b).Code
Privat
esubcmdcomput e
_cli
ck()Di
m num (1to3)as
i
nteger
Dimi asinteger
,sum asint
eger
Sum =0
Fori =1t o3
Num (i)=InputBox(“
enterarr
ayval
ue,
”Ar
ray
”)
sum =sum +
num( i
)Nexti
Picsum.Pri
nt“sum ofval
uesis“,
sum
Endsub
Exerci
se
Rewr i
teexample1.Onarray
ssot hatelementsaredispl
ayedi
nrever
sei
n
whichtheyar ei
nput
ed.
2.Rewr i
teexample2sothattheaverageofthethreeinput
edarr
ay
val
uesi salsocomputedanddispl
ayed.
Dim A( 4)asint
erger
Privatesubci mddispl
ay–cl i
ck()
DimI asinteger
,jasintegerforI=0to4
A(i)=i nputbox(“
enterarrayv
alue”
,“ar
ray
s”)
Nexti
ForJ=4t o0
Picdisplay.Pri
ntA(j)
Nextj
Endsub
Code
Dim num ( 1to3)asi nter
gerpri
v at
esubcmdcal
cul
ate–cl
i
cki
)di
m Ias
i
nteger,sum asi nteger
Dim averageasi nteger
Sum=0
ForI=1t o3
Num (i)=i nputBox( “
enterarr
ayv al
ue”
,ar
ray
s”)
Sum =sum +
num( i
)Nexti
Average=sum/ 3
Picsum print“sum ofvalueis“,sum
Picsum, print“
averageofv al
ueis
“averageEndsub.
TWODI MENSIONALARRAYS
Atwodi mensi
onal arrayisadatastruct
urei
nwhi chelement
sar ear
ranged
i
nr owsandcolumns.Twosubscr i
ptsareusedtoidenti
fyanit
em e.
g
score(2,
4)
Means3rdrow 5thcolum thi
sisbecausethearraywasdeclaredasfr
om row0
as
fol
lows:
Dim score(
0to2, 0t o4)asintegerOR
Dim score(
2,4)asi nteger
0 1 2 3 4
0
1
2
3
4 Scor
e(2,
4)
Example
Apr ogr
am toacceptanarr
ayof4marksfr
om 5di f
fer
entst
udent
s,
calcul
ateanddispl
aytot
almarksf
oreachstudental
ongsi
dethemarkson
theformintheformat
shownbelow:
Mat
h Eng Ki
sw Sci
ence Tot
al
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
a)
.UI
f
rmmar
ks
Tot
almar
ks
cmdcomput
e
COMPUTE
b)
.Code
Pr
ivatesubcmdcomput e_
cli
ck()
Dim studmarks(1to5,1to4)asi
nteger
Di
m studentasinteger
,markasi
nteger
,col
Asi
nteger
Di
m sum (
1to5)asi
nteger
Col =1
Me. pr
int”mat h”,
Eng”,Kisw”,
“Science”,
“Total”
Forst udent=1t o
5sum ( student )=0
Formar k=1t o4
studmar ks( student,mark)=inputbox(“keyinstudentmar ks’,
“marks”)
sum (student )=sum( student)+studmar ks(
student,mar k)
Me. pr
inttab( col)
;st
udmar ks(
student,mark);‘
pri
ntinformationstart
ingf
rom
column1col =col +6
I
fcol >20Then
Me. pr
intt ab(col);
sum(student)‘pri
ntsum ofmar ksf orstudentandbegin
newl i
necol =1‘ r
esetcolumnt ostartpr
inti
ngnextinformat i
onf r
om
column1
Endi f
Nextmar k
Next
studentEnd
sub
Exerci
se
1.Wr it
eavbprogram t
oassi
gntheval
ue65toal
lthel
ocat
ionsofa4x4
arr
ayanddi
splayt
hem i
natableasshown
65 65 65 65
65 65 65 65
65 65 65 65
65 65 65 65
2.Rewr i
teourprevi
ousexampl
eontwodi
mensional
arraysot
hattheaverage
mar
k
foreachstudenti
salsocomput
edanddi
spl
ayedalongsi
deotherv
aluesas
shown.
Mat
h Eng Ki
sw Sci
ence TotalAv
erag
- - - - - e -
- - - - - -
- - - - - -
- - - - - -
- - - - - -
SORTI NGANDSEARCHI NG
SORTI NG
I
sanal gori
thm f
ororderinganarray.
a).bubblesort
I
sanal gori
thm t
hatcompar esadjacentel
ementsandswapsthosethatar
eoutof
order.Thisprocessi
sr epeatedenoughtimestheli
stwi
llbeor
dered.Thestepsf
or
eachpasst hroughthelistareasfoll
ows:
st nd
1.compar ethe1 and2 i tem i
ftheyareoutofor
derswapthem
2.
compar
ethe2ndandt
he3rdi
temsi
ftheyar
eoutofor
derswapt
hem
3.
repeatt
hispr
ocessforal
lther
emainingpai
rs,
t hefi
nal
compar
isonandt
he
nd
possi
bleswaparebet
weenthe2 l astandthelastel
ement
I
ll
ustr
ati
onofhowtheel
ementsli
stofnamesaresortedi
nascendi
ngor
der
usi
ngbubbl
esort
(I
ll
ust
rat
ionPage193-VBA begi
nnerhowto…)
Exampl
e
Aprogr
am t
osortal
i
stof5number
sassi
gnedt
oanar
rayi
nascendi
ngor
der
usi
ngbubbl
esor
t.
a).
UI
fr
mBubbl
eSor
t
Bubbl
eSor
t
pi
csor
ted
sor cmdsor
t
t
b)
.Code
‘
Gener aldecl arati
on
Dim num ( 1to5)asi nteger
Privat
esubcmdsor t
_cli
ck()
Dim passasi nteger,compar easinteger
,tempas
i
ntegerdi mi asi nteger,
forpass=1t o5
forcompar=1t o4
I
fnum( compar )>num( compar+1)
Thent emp=num( compar )
num( compar )=num( compar +1)
num (compar +1)=t emp
Endi f
Nextcompar
Nextpass
Picsorted.pr
int” sort
edel ementsare:“
Fori =1t o5
Picsorted.pri
nt
num( i
)Nexti
Endsub
Pri
vat
esub
for
m_load()Num (
1)
=60
Num (2)=3
Num (3)=90
Num (4)=7
Num (5)=14
Endsub
Exercise
Modi f
ysothattheabovepr
ogr
am pr
omptst
heusert
oent
ert
hev
aluest
obesor
ted
i
nsteadofbeingassignedt
oar
rayonfor
m_l
oad.
SHELLSORT
Thebubbl esortiseasyt ounder standandpr ogram.Howev eritistooslowf orlong
l
ist s.
Theshel lsortismuchmor eef
fici
enti nsuchcases.I tcompar esdist
antitemsf ir
st
andwor ksitswaydownt onear byitems.Thei ntervalsepar ati
ngt hecompar ed
i
t emsi scall
edt hegap.Thegapbegi nsatone-hal f(½)t helengt hofthelistanditis
successf ull
yhalv edunt ilevent
uallyeachi t
em iscompar edwithi t
sneighborasi n
thebubbl esort.Theal gorit
hm foral i
stofnitemsi sasf ol
l
ows: -
1.Begi nwithagapofg=i nt(n/ 2)
2.Compar ei tems1and1+g, 2and2+g, --
---n-gandn, swapanypai r
st hat
areoutofor der
3.Repeatst ept wount i
lnoswapsar emadef orgapg.
4.Hal vethev alueofg
5.Repeatst ep2, 3and4unt i
lthev al
ueofgi szer o.
Theshel lsortisillustratedbelow.Theel ement sar esortedinascendi ngor der
,
cr ossingar r
owsi ndicatet hataswapoccur r
ed.
El ement stobesor tedar enames: pebblesbar neyWi lli
am, Fred, Di
no
Initial
gap=i nt(num ofi t
ems/ 2)=i nt(5/
2)=2
Becauset
her
ewasaswap,
uset
hesamegapf
ort
hesecondpass.
Agai
n,t
her
ewasaswap,
sokeept
he
Ther
ewer
enoswapsf
ort
hecur
rentgapof2,
soNextGap=I
nt(
[Pr
evi
ousGap]
/2)=I
nt(
2/2)=1
Becauset
herewasaswap(actual
ly
twoswaps),
keepthesamegap.
Becauset
herewer
enoswapsfort
hecur
rentgap,
thenNextGap=I
nt(
[Pr
evi
ous
Gap]/2)=Int
(1/2)=0andt
heShell
sorti
scomplete.
NoticethattheShellsortrequi
red14compar isonst osorttheli
stwhereasthe
bubblesortrequir
edonly10compar i
sonsforthesamel i
st.Thi
sill
ust
ratest
he
factthatforveryshor
tlist
s,thebubblesor
tispreferabl
e;however
,forl
ist
sof30
i
temsormor e,t
heShellsortwil
lconsi
stent
lyoutperf
ormthebubblesort
.
Exampl
e
Pr
ogr
am t
hatsor
tsal
i
stoff
ivei
nteger
sinascendi
ngor
derusi
ngshel
lsor
t
a)
.UI
fr
mShell
Sor
t
Shel
lSor
t
pi
csor
ted
sor cmdsor
t
t
b).
code
‘
Gener aldecl
arat
ion
Dim num (1to5)as
i
ntegerconstnasi nteger
=5
Pri
vatesubf or
m_ load()
‘
Readt henumber sintoarray
num ( 1) =
60 num ( 2)
=90num( 3)
=40num( 4)
=30num( 5)
=80
Endsub
Pri
vatesubcmdsort–cl
ick()
‘sortanddispl
ayel
ements
call
sortdat
a()
call
showDat a(
)
Endsub
Pri
vatesubsor t
Data()
Dim gapasint eger,Donefl
agas
booleanDimi ndexasi nteger
,temp
asintegerGap=i nt(n/
2)
Dowhi legap>=1
Do
Doneflag=true
Forindex=1t on- gap
I
fnum( i
ndex)>num ( i
ndex+gap)t
hen
Temp=num ( index)
Num ( i
ndex)=num( index+
gap)Num ( i
ndex+gap)=
temp
Donef l
ag=f alse
Endi f
Nextindex
Loopunt i
l(donefl
ag=
true)Gap=i nt
(gap/2)
Loop
Endsub
Pri
vatesub
showdata()Dimias
i
nteger
Fori=1t o5
Picsort
ed.Pr
int
num(i)Nexti
Endsub
Sel
ecti
onsort
I
nselect
ionsortt
heit
em i he1stposi
nt tioni
scomparedwiththeother
el
ements.I
ftheelement
sbeingcomparedarenoti
nordertheyareswapped.
I
ll
ustr
ati
ononhowt heel
ements9,6,2,10aresor
tedinascendi
ngorder
9 6 2 2
6 9 9 9 1stpass
2 2 6 6
10 10 10 10
2 2 2 2 2
9 6 6 2ndpass 6 6 3rdpass
6 9 9 9 9
10 10 10 10 10
Exampl e
Aprogram t
osor
tal
i
stoff
ivenamesi
nascendi
ngor
derusi
ngsel
ect
ion
t
echnique.
a)
.UI
fr
mSel ect
ionSor
t
Select
ionSort
pi
csor
ted
sor cmdsor
t
t
‘
Gener aldeclarat
ion
Dim name( 1t o5)asst ri
ng
Pri
vatesubcmdsor t_cl
ick()
Dim passnum asi nteger,comparasint
eger
Forpassnum =1t o4
Forcompar=passnum +1t o5
I
fname( passnum)>name( compar)Then
Temp=name( passnum)
Name( passnum)=
name(compar e)Name( compar)
=temp
Endif
Nextcompar
Nextpassnum
Fori=1t o5
Picsor
ted.
pri
ntname
(i
)Nexti
Endsub
Privat
esubf orm
_load()Name
(1)=”mike”Name( 2)
=
“Zachary”Name( 3)=
“Abel”
Name( 4)=“James”
Name( 5)=“Wi l
l
iam”
End
sub
a)
.UI
fr
mLinear
Sear
ching
pi
cresul
t
sor cmdl
i
near
sear
ch
t
b)
.Code
Diml i
st(1t o5)asi nteger
Pr i
vatesub
cmdl i
near search_ Cli
ck()Dim key
asi nteger ,iasint eger
Key=I nput box( “keyinelementt osear
ch“
,“sear
ch”
)
‘
Initial
izef i
rstlocat i
ontosear ch
from i=1
Whi le(list(i
)<>key )AND( i<>6)
i=i +1‘ checkt henextl ocat
ion
Wend
I
f( l
ist(i)=key )Then
Picresul t.
print“element
found”El se
Picresul t.
print”elememtnotf ound”
Endi f
Endsub
Privatesub
form_ l
oad(
)Li
st(
1)=7
List(
2)=2
List(3)=4
Li
st(
4)=10
Li
st(
5)=3
Endsub
2.BinarySear ch
Wor ksonasor t edlist,
i
. Dividesanar raybyhalfbyfindingthemi ddl eel
ementi nthearrayi.
e
mi ddleel ement=f i
rst+last/2
i
i. I tt
hencompar est
hemi ddleelementwi tht hekey.
a.I fthemi ddleel ementisgreaterthanthekeyt henthel astlocationis
comput edbyl ast=middle-1andsear chpr oceedst ot hef ir
sthalfofarray
.
b.I fthemi ddleel ementislessthant hekeyt hent henewf irstlocati
onis
comput edbyf irst=middle+1andsear chpr oceedst ot hesecondhal fof
thearray .
c.I fthemi ddleel ementisequal tothekeyt hesear chisov erandt heprogram
reports
thattheel ementi sintheli
stotherwisepr ogram displayst hattheelement
wasnotf ound.
Exampl e
Apr ogram tosear chf oranelementf r
om anar ray
a).
UI
fr
mBinary
sear
ch
Sear
ching
pi
cresul
t
sor cmdsear
ch
t
b).
code
dimlist(
1to5)Asi nteger
pri
vatesubcmdsear ch_ (
Cli
ck)
dim keyasinteger,fl
agas
boolean
key=i nput
box( “
entervaluetosear
ch”,
”sear
ch”
)
dimf i
rstasinteger,middl
eas
i
ntegerdiml astasinteger
fl
ag=
fal
sef i
rst
=1
l
ast=5
Dowhi le(f
ir
st<=l ast)and(fl
ag=f al
se)
mi
ddl
e=i
nt(
(fi
rst+l
ast)
/2)
Selectcasel i
st(middl
e)
casei s=
keyf l
ag=
tr
uecasei s
>key
l
ast=mi ddle-
1casei s<
key
fi
rst=mi ddle+1
Endsel ect
Loop
I
f( f
lag=true)Then
picresult
.pri
nt
”found”el se
picresult
.pri
nt“notfound”
endi f
Endsub
pri
vatesubf
orm_
load(
)
l
ist(1)
=
10
l
ist(
2)=20
l
ist(
3)=30
l
ist(
4)=40
l
ist(
5)=60
Endsub
FI
LES
SEQUENTI
ALFI
LES
Cr
eat
ingsequent
ialf
il
es
1.Chooseaf il
enam. Af il
enamecont ainupt o255charactersconsi sti
ng
l
etter ,digitsandaf ewot herassor tedchar acter
sbutincludi
ngspacesand
periods
2.Chooseanumberf rom 1t hr
ough511t obet herefer
encenumberoft hefil
e,
whi
lethe
fi
leisi nusei twillbeident i
fi
edbyt hisnumber
3.Execut et hestatementopen“ fi
lespec”FOROUTPUTAS #n.wher eni s
ther eferencenumber .Thispr ocessi sref
er r
edtoasopeni ngaf i
lef or
output. Ital l
owsdat atobeout putfrom comput erandrecordedint he
speci f
iedf i
les.
4.Placedat aintothef il
ewi t
ht hewr ite#nstatementse.gifaisst r
ingt hent he
statementwr ite#n, awr i
testhest ringsurroundedbyquot at
ionmar ksi nt
o
thef i
le.
I
fci sanumbert hent hest atementwr i
te#n, cwrit
esthenumberc
withoutanyl eadingort r
aili
ngspacesi nthef i
lenumber.
5.Aftert hedat ahasbeenr ecor dedint hefi
le,execut
eclose#nwhenev ern
i
st her ef erencenumber .Thisst atementbr eaksthecommuni cati
onl ink
witht hef ileanddi ssociatest henumbernf r
om thefi
l
e
Exampl
e
Thefol
l
owingprogram i
ll
ustrat
est
hediff
erentst
atementsoft
hewrit
estat
ement.
Noti
cetheabsenceoftheleadi
ng&trai
l
ingspacesfornumbersandthepr
esence
ofquot
ati
onmar kssur
roundingst
ri
ngs
a)
.UI
Cr
eat Cmdcr
eat
efi
l
e
e
b).Code
Privat
esubcmdcr eatef
il
e_cli
ck()
Dim name1asst ri
ng,name2asst r i
ng
Dim num asi nteger
Num =80
Name1=“ Eni ac”
Name2=“ Maul di
ly”
Open“ C:\pioneer .
txt“f
oroutputas#1
Wr i
te#1, “Eniac”,1946,num
Wr i
te#1,1946, name1,name2
Wr i
te#1,14* 139, “
J.P”& name1, name2,
”j
oe”
Close#1
Endsub
N/B:I fanexi sti
ngsequentialfi
lei
sopenedforfi
l
emodeout
put
.Thecomput
erwi
l
l
erasetheexi sti
ngdat aandcr eat
eanewempt yfi
le.
Cmdcopy
fil
e cmdcr
eat
efi
l
e
sear
ch Di
spl
ay
Cr
eat
e
Copyt
ofi
l
e
b).
Code
Pri
vatesub
cmdcreatefi
le_Cli
ck()Dim
i
ntmsgasi nteger
Dim num asinteger, i
asi nt
eger
Open“ C:\number li
st.
txt
”forappendas#1
I
ntmsg=msgbox( “
number l
i
st.t
xtopenedsuccessf
ull
y”)
Fornum =1t o6
i=Inputbox(“enternumbert ostor
einfil
e“)
Writ
e#1, iNextnum
I
ntmsg=msgbox( “numberli
st.
txt
cl
osed”)Close#1
Endsub
Exampl e
Displayi
ngcontent
sofasequenti
alfil
e
(program)Notes:
Open“ number.
txt
”fori
nputi
s#1
I
nputmode-opensanexi sti
ngfi
l
ef orareadoper
ati
on
Priv
at esub
cmddi spl ay contents_ Click()Dim
num asi nt eger
Open“ c:\number li
st.txt”forinputas#1
Dowhi lenotEOF( 1)
I
nput#1, num
Me.pr i
nt ,num
Loop
Close#1
Msgbox“ cont entsdi play ed”
Endsub
Copy ingcont entsofnumber l
istfi
let
onumberl
ist
copy
fil
e
pri
vatesubcmdcopy fil
e_ cli
ck()
di
m num asi nteger
open“ C:\number l
ist.txt“forinputas#1
open“ C:\number l
istcopy .txt
”forappendas#2
Dount i
lEDF( 1)
i
nput #1, num
pri
nt#2, num
Loop
cl
ose#
1close
#2
msgbox”cont entscopi ed”
Endsub
Searchi
ngf orf i
l
econt ent
s
pri
vatesubcmdsear ch_cl
ick()
di
m num2sear chasinteger,num asi
nteger
open“C; \number l
ist.
txt
”forimputas#1
Dowhi l
e( num<>num2sear ch)andNOT
EOF(1)INPUT#1, num
Loop
I
fnum2sear ch=num Then
Me.pri
nt,
num2sear ch
Msgbox” cont ents
di
splayed”El se
Msgbox” nosuchr ecord”
Endif
Close#1
Endsub
RANDOM ACCESSFI
LES
Ar andom- accessf i
leisl i
keanar rayofrecordsst oredonadi sk.The
recordsar enumber ed1, 2,3,andsoon, andcanber eferredt obyt hei
r
number s.Therefore,ar andom- accessf il
eresembl esaboxofi ndex
cards,eachhav inganumber edt ab.Anycar dcanbesel ect edf rom
thboxwi thoutfir
streadi ngev eryi ndexcardpr ecedingit;simi l
ar l
y,any
recordofar andom- accessf i
lecanber eadwi t
houthav ingt or ead
everyrecordpr ecedingi t.
Onest atementsuf fi
cest oopenar andom-accessf il
ef oral lpurposes:
creati
ng, appending, writi
ng,andr eadi
ng.Supposear ecor dtypehas
beendef ined
withaTy pebl ockandar ecor dv ariabl
e,call
edr ecVar,hasbeen
declaredwi t
haDi m st atement .Thenaf terthestatement
Open“filespec”ForRandomAs#n
i
sexecut ed, r
ecordsmaybewr i
tt
en,read,added,andchanged.The
fi
leisreferr
edt obyt henumbern.Eachr ecor
dwi l
l haveasmany
charactersasallott
edt oeachvalueofrecVar.Supposeappropri
ate
Type,Dim, andOpenst at
ementshavebeenexecut ed.Thetwo-st
ep
proceduref orenter
ingar ecor
dintothefil
eisasf oll
ows.
1.Assi
gnav
aluet
oeachf
iel
dofar
ecor
dvar
iabl
e.
2.Pl
acet
hedat
aint
orecor
droff
il
e#nwi
tht
hest
atement
Put#n,r,recVarwhererecVari
sther
ecor
dvar
iabl
efr
om St
ep1.
Example
Thefol
l
owingprogr
am cr
eat
esandwr
it
esr
ecor
dst
other
andom accessf
il
e
knownascol
leges.
txt
Stat
e Txtcoll
ege
name txt
state
txt
yrfounde
dcmddone
abbr
evi
ati
o
n
Y.f
ounded
Add Done
cmdadd
‘
modul e.BAS
Publ icty
pe
collegeDatanam as
string*30
stat easstri
ng*20
yr
f oundedas
i
nt egerendt ype
‘
gener aldecl ar ati
on
Dimr ecor dnum as
i
nt egerPr i
v atesub
cmdadd_ click()dim
collegeascol legeData
college.nam=t xtcol
lege.
t
extcol lege. state=
txtstate.text
college. y
rf onded=v al(
txt
Yrf
ounded.
text
)
recordnum =
recordnum+1put#1
,recor dnum, college
txtcollege. text=” ”
txtyf ounded. text=“ ”
txtcollege. setfocus
Endsub
pri
vat
esubcmddone_
cli
ck(
)
cl
ose#
1end
sub
pri
vatesubfor
m_ l
oad()
Dim col
lege
col
legeData
Open”C:\coll
eges”forr
andom as#1
Recordnum =0
Endsub
Example
Di
spl
ayi
ngt
hecont
ent
sofar
andom f
il
e
cmddi
spl
ay
Di
spl
ay
pi
cout
pu
t
Privat
esub
cmddi splay_cl
ick()Dim
recordnum asi nteger
Dim collegeascol legedata
open“ C:\col l
eges. txt
”forrandom as#1
picoutput.cls
picoutput.pr
int”colleges”;t
ab(30);“
stat
e”;t
ab(45);
“yearf
ounded”
forrecordnum=1t o5
get#1, recordnum, coll
ege
picoutput.pr
intcollege.nam;tab(30)
;col
lege.st
ate;
tab(
45);
coll
ege.y r
foundednextr ecordnum
close
#1end
sub
APPLI CATI ONANDDATABASES
-Procedur eforl
inkingtodatabaseandgener
ationofr
eportsin:
a).Vbt utorRevised.pdf
-pg59-82-
ReadonLesson21:Creat
ingVBdat
abase
applicati
onsusingADOcont rol
b).Visual basi
cAVU. pdf-
pg344-360-
Readonreport
s
SAMPLEPROJECTEXAMPLEANDCODE
a)
.USERI
NTERFACE
t
xtR
t
xtN
Cbogender
cmdsav
e
adost
udent
cmdcl
ea
r
cmdaddne
w
cmddel
ete
cmdP cmdL
cmdN
b).
CODE
Pri
vateSubForm_Load(
)
cbogender
.AddI
tem
"MALE"
cbogender
.AddI
tem
"FEMALE"EndSub
Priv
ateSubcmdclear
_Cl
i
ck(
)
txt
R.Text=""
txt
N.Text=""
cbogender.
Text=
""EndSub
Pr
ivat
eSubcmdaddnew_
Cli
ck(
)
Adost
udent
.Recor
dset
.AddNew
EndSub
Pri
vateSubcmdsav e_Click()
Adostudent .
Recordset.Fields("Regno")=
Val(
txtR.Text)Adostudent .Recordset.Fiel
ds("
Name")
=txtN.TextAdost udent.Recor dset.
Fields(
"Gender
")=
cbogender .
TextAdost udent .Recordset.Updat
e
MsgBox" Record
saved"EndSub
Pri
vat
eSub
cmddelet
e_Cl
ick(
)
Adost
udent.
Recordset
.Del
et
eEndSub
Priv
ateSubcmdF_ Cl
ick()
Adostudent
.Recor
dset.MoveFi
rstEndSub
Pri
vateSubcmdL_ Cl
ick()
Adostudent
.Recor
dset.MoveL
astEndSub
Pri
vat
eSubcmdN_ Cli
ck(
)
Adost
udent.Recor
dset.
Mov eN
ext
I
fAdostudent.
Recordset
.BOF
Then
Adost
udent.Recor
dset.
Mov eFi
rs
tEndIf
EndSub
Pri
vateSubcmdP_ Cli
ck()
Adostudent
.Recor
dset.Mov ePrev
i
ousIfAdostudent
.Recordset.BOF
Then
Adostudent
.Recor
dset.Mov eLast
EndIf
EndSub
Codet
osel
ectanddi
spl
aydet
ail
sofar
ecor
dfr
om adat
abaseonal
istboxandor
/
usi
ngaCombobox
Li
st1
cbor
eg
t
xtn
t
xtg
Adoget
stud t
xtp
t
xtb
‘
Codet odi splayintendedinformati
ononcomboboxandl istbox
Priv
ateSubFor m_ Load()
List
1.AddItem ("NAME"&""&" GENDER" )
List
1.AddItem ("-
---
---
--
--
"&" "&" -
--
--
--
")
WhileNotAdoget stud.Recordset.
EOF
cboreg.
AddI tem
(Adogetstud.Recor dset!
regno)
List
1.AddItem (Adoget stud.
Recordset!
Name&" "&
Adogetstud.Recor dset!
Gender )Adogetst
ud.Recor
dset
.Mov eNext
Wend
Adogetstud.Recor dset.
Mov eFi
rstEndSub
‘
Codet osel ectanddi splayinf ormationusingcombobox
Pri
vateSubcbor eg_Click()
WhileNotAdoget stud.Recor dset.EOF
I
fcbor eg.Text=Adoget stud.Recor dset!
regno
Thentxt n.Text=Adoget stud. Recordset!Name
txt
g.Text=Adoget stud.Recor dset!Gender
Adoget stud.Recor
dset .
Mov eFirst
Exi
tSub
EndIf
Adoget
stud.
Recor
dset
.Mov
eNext
Wend
EndSub
Pri
vateSubt xt
p_ Key
Up(KeyCodeAsInteger
,Shi
ftAs
I
nteger)Constf eeRequi
redAsInteger=20000
txt
b.Text=feeRequired-
Val(
txtp.
Text)EndSub