You are on page 1of 54

1

Microsoft
Visual Basic
6.0
AppliedScience
Secondclass
2
1. Introduction
Visual Basic implements graphical user interfacethat allows theuseof
graphics for different applications. I t provides visual interactive windows
withuser, likeDialoguebox for (color, font ...), Input box, andOutput box.
Alsoit isabletocreatemenutosimplifyuser application.
Torunthisprogramonuser computer:
Start>programs>Microsoft Visual Studio6.0>Microsoft Visual Basic6.0.
It will appear onthecomputer screenasinthefollowingpicture.
Toexit fromVisual Basic andreturntoWindowsislikeexit frommost
Windows applications. There are three ways to close the Visual Basic as
statedbelow.
1- Clickonclosebuttoniconthat appearsintheupper-left corner of the
screen.
2- PressAlt+F4
3- Select File>Exit
1.2-TheI mportanceof Visual Basic Program
LanguageslikeBasicandPascal dependonvariablesandproceduresto
build the applications .This is why it is called procedural languages. The
newapproachis calledobject programmingfor visual programs likeVisual
Basic andVisual C++andothers. Inthisprogrammingapproacheverything
(form, commandbuttons, controls) isanobject.
Thereasonsfor of implementingVisual Basicprogramarelistedas
follows:
1- It uses integrated development environment (IDE) which is easier for
theuser tominimizecodewriting.
3
a
b
c
d
e
f
g
2- All visual programs follow the same concepts, therefore the user will
becomemorefamiliar withvisual approachfor other visual languages.
3- It provides Input box and Output box as an interactive windows with
user.
4- It isabletoconnect toInternet, andtocall Explorer.
1.3- Elements of theI ntegrated Development Environment (IDE)
The IDE environment consists of many elements. Some elements are
displayed when Visual Basic is started (By default) as in the following
figure. Other elements aredisplayed if theuser requires them. Wewill list
someof theseelements.
a- MenuBar: It containsastandardcommandlike: File, Edit, View,
Window, Helpmenus, andspecificcommandsuchas: Project, Format, or
Debugmenus.
b- Toolbar: it containsthemost commonlyusedcommands(button), if
clickedanactionrepresentedbythat buttoniscarriedout.
c- ToolBox: it contains a collection of tools that are needed for project
design.
4
d- formDesigner: it isawindowfor eachformtocustomizethedesigned
interfaceof theapplication. Usingtheformdesigner, theuser canadd
controls, graphics, andtext tocreatethedesiredformappearance.
e- PropertiesWindow: it isaList of propertiessettingsfor aselectedformor
acontrol. Thesepropertiesarecharacteristics(suchassize, visible, or color)
of theselectedobject it providesaneasywaytoset properties.
f- Project Explorer Window: it is a list of the forms and modules for the
current projects. lt is a hierarchical tree- branch structure, where the
project at top of treeand other parts likeforms ,modules) descend from
thistree.
g- FormLayout Window: TheFormLayout windowisasmall screen.
Whichisusedtorepositiontheformof theapplicationsothat it appears
inproper placewhenproject isrun.
h- CodeEditor Window: CodeEditor Windowis used to writeaVB code
for anapplication. For eachformthereisaseparatecodeeditor window.
It isdisplayedwhenuser clicksonformor object inform.
ToCreatean Application
Thetitleof programincludesthenameof project, andwhentheuser first
startstheprogramit takesadefaultedvalue(projectl).It alsoincludesresize
5
icons. ThefollowingstepsarerequiredtocreateanapplicationinVisual
Basic6.0:
1- Select typeof project Newor Exciting. A formautomaticallyappearsin
theformdesign.Thebasisfor anyapplication'si nterface isthe form
that user shouldcreate. User canaddother formstotheproject (toadd
another formselect project menu>addform).
2. Toaddobjects(controls) totheformusetheToolBox.
3. Set thepropertiesfor theobjectsthroughpropertieswindow.
4. Writecode. TheVisual BasicCodeconsistsof statements, and
declarations.
Thecodefor anapplicationcanbewrittenontheCodeEditor window.
Inthiswindowuser canviewandedit quicklyanyof thecode.
5. Run theApplication. Toruntheapplication, clicktheStart buttonon
thetoolbar, or pressF5.
6. Stop. Tostoprunningtheapplicationandreturntovisual basicprogram
clickonstopbuttonintool bar.
7. Checkif thereisanerror, returntostep3,otherwisecontinue.
8. Saveproject.
9. Exit.
Exercises
1-Definethefollowingparameters:
a-Toolbar.
b-ToolBox.
c-Formdesigner,
d-formlayout.
e-project window,
f-propertieswindow.
i- codeeditor window,.
2- Explaintheadvantageof theVisual Basicprogram.
6
Project
Project isaprogramdesignedtouser applicationthat maybesimple
(likecalculator program) or complex (like word program). Visual basic
programcancreatemany types of projects. Themost important or usual
project isthestandardproject (for windowapplications) andtheDHTML
project (for internet).
WorkingwithStandardProjects:
Thefollowingworkingsteps(create, save, add, openanddelete)
couldbedone:
a) Tocreateproject:
Whenprogramstarts, project boxappears-select StandardEXE >
Project windowappears.
OR: File>Newproject>Box(select StandardEXE)>Project window
appears
b) Toaddproject: Anynumber canbeadded.
Project icon>Select StandardEXE>Project windowappears.
Note: Usuallyfirst project runsfirst, but user canchangethat by:
Selectingproject fromproject window>mouselist >Set asstartup.
c) Toopenanexistingproject:
It ispreviouslydesignedandsavedondiscinafolder.
File>Openproject>Box(select existingandlookfor theproject) >
Project window
d) Todeleteaproject:
Select project inProject window>Mouselist >Removeproject.
7
e) Tosaveproject:
Thevisual basiccansavetheproject ondiscintwoways, asan
executabletypeor anon- executabletype.
I - for project innonexecutionstage:
Therearemanytypesof filessummarizedasfollows:
1- Project file: it consistsof all fileswhicharerelatedtospecificproject,
alsosomeother informationwithit. Thiscouldbesavedwithextension
(.VBP)
2- TheformFiles: thiscontainsformdescriptionandanyObject or
programrelatedtoit .Thisissavedwithextension(.frm).
Tosaveproject for first time:
File>Saveproject (group) as>Box(project name)>formssavedthen
projectsgroupsaved.
Toresaveproject: tosavepreviouslysavedproject insameplace
File>saveproject (group)
Note: If aformismodifiedit shouldbesaved. Tosaveaform:
Select aformfromProject window>File>Saveproject form1as>Save
box(select formname). OR: File>Saveproject forml.
I I - project for execution: Thisisthefinal stagesothat it couldbeopened
andrunbyWindowsandnoneedfor Visual Basicprogram. File>Make
project.exe.
I tem Actionsteps Remarks
Create
project
New File>Newproject Theuser canopenanynumber of
projects.
Exist File>Openproject Project wasalreadydesignedand
saved.
Recent File>Openproject Project wasrecentlydesignedand
saved.
Saveproject File>Saveproject group
as
Visual Basiccandeal withit (open
andmodify).
File>Makeprojectl.exe For executionbywindow.
Deleteproject File>Removeproject Select project beforeremove.
8
Forms
1) I ntroductiontoform
Theformisthemost important visibleobject,without it nocontrol canbe
displayed. It isawindowthat canbedesignedandmodifiedtofit user
applications. Inthestandardproject theformDesigner createsand
modifiesvisual forms.Whenuser startsvisual Basicprogramaformis
automaticallydisplayedinDesigner window. Thedesigner canaddany
number of formstotheproject of hisapplicationbypressing: addform
fromproject menu.
Therearetwomodes: designmodeandrunningmode. User can
interchangebetweenthem, bypressingonstart icon or stopicon
ontool bar.
Theformsalsohavepropertiesandevents.
2) Formproperties
Properties list has apredefined value(numeric or string) and could
be changed, some properties could be rewritten like caption, and some
couldbeselectedfromoptionlist bypressingondownarrowontheside.
Others could be rewritten or by browsing the computer files when
the user clicks on the dotted button on the right side a dialogue box
9
appears. The browsing button appears when the user clicks inside the
box.
Themost important propertiesof theformarelistedinthefollowing
table:
Property
name
Objective code Stageof
Changing
Name Usedtorepresent nameof form
incode
Design
Caption Stringappear intitleof form Form
no.
.caption="anyname" Designandrun
Backcolor Backgroundcolor for form. Form
no.
.Backcolor=Qbcolor(no.) Designandrun
Forecolor Color of text writtenonform. Form
no.
.forecolor=Qbcolor(no.) Designandrun
Font Font style, typeandsize. Size: Form
no.
.fontsize=no.
Style:

underline
bold
italic
font
Type: Form1.FontName="arial"
Designandrun
borderstyle 0-Noneborderlessand
captionless
1-FixedSingleanonresizable
form
2-Sizable(default), createsa
resizablewindow,
3-FixedDialog: nonresizable
formwithout Minimizeand
Maximizebuttons
4-FixedTool windowfor a
floatingtoolboxlikeform,
5-SizableTool window
Design
Enabled Thetoolsenableor disable. Form
no.
. Enabled=trueor false Designandrun
Minbutton
Maxbutton
=true. TheMinimizeand
Maximizebuttonsareenabled.
=false. TheMinimizeand
Maximizebuttonaredisabled.
Form1.MaxButton=Trueor
=false
Form1.MinButton=Trueor
=false
Run
Start up
position
0- Manual ,useformlayer
windowtopositionForm
1- Center owner
2- at Center Screen
3- Windowdefault.
Design
movable Trueor falsetomakeform
movableor unmovable
Design
Hide Tohidetheform Form
no.
.hide Run
show Toshowtheform Form
no.
.Show Run
icon Changetheiconontitlebar of form(theiconmust havetheextensionicoor cur)
10
3) Codeform
ThecodeiswrittenincodeFormandit will beeditedquicklyby
codeeditor .Thecodesareof twocategories:
1- Declarationiswrittenbeforeanyprocedureinthecode
2- Statements. Theuser selectstherequiredevent thencodestatements
arewritteninsidetheseevent procedures.
5) Events:
Events are like electrical switches. The electrical switches are of
manytypes, soaretheevents.
Theforms andcontrols support events (generation, interactionwith
mouse and keyboard). The most important events for the form are
describedinthefollowingtable.
Examples:
1- Designaformsuchthat: inevent load, whenproject runs, theform
backcolor propertychanged(choseanycolor).
sol:
code:
PrivateSubForm_Load()
Form1.BackColor =QBColor(12)
EndSub
2- Designaformsuchthat: inevent clickonform, whenproject runs, the
titleof theformchangedtoappliedscience.
Event Actiontakenwhen
Click Singleclickonobject.
DbClick Doubleclickonobject.
load Loadingtheobject




11
Exercises:
Q1/ Designastandardproject hasthreeformswithbackcolorsred, blue
andgreen.
Q2/ designastandardproject that hasoneformchangethenamefrom
form1to"students"
Q3/ Createastandardproject withoneformthenameof theproject
"market seals" andthenameof theform"stockmarkets" andsaveproject
ondesktopwithnamemarketing.exe
Q4/ Designastandardproject withfour formswhenrunningproject all
formsappear onscreenNote:usethiscodeinform1(form1.show,
form2.show, form3.show, form4.show)
12
Toolbox
It is a window box that contains tools which could be used in the
project. Toolsareobjectsthat couldbeselectedfromToolbox tobeplaced
onform. Toshowthetoolbox, Presstoolbox icon >thetoolbox appear
asinthefollowingdiagram.
Thetoolboxincludesmanytoolsandingeneral theyare:
1) Pointer (not control) : usedtoselect toolsalreadyonform
2) Picture box : Used to display images in any of the following
formats: BMP, DIB (bitmap), ICO (icon), CUR (cursor), WMF
(metafile), EMF (enhancedmetafile), GIF, andJ PEG.
3) Label : Fixedtext appearsonformfor remark.
4) Textbox : For text edit .Likenotepad.
5) Frame : Togrouptoolstogether (container).
6) Commandbutton : Usedasaswitch(suchasOK andCancel) buttons. Code
iswrittenintheClickevent procedureof thiscontrol
7) Checkbox : For ayes/ no(true/false) selection.
8) Option button : For selection as group. Many options are placed inside
container (grouped) (aFramecontrol). Onecontrol is selected fromthegroup all
othersof thegroupareautomaticallydeselected.
9) Combobox : consistsof (list andarrowwhenclickedasmall alist appears),
if user selects itemfromthelist, it will bedisplayed in TextBox. Vertical sizeis
fixed.
10) List box : For alist, user addstoanddeletesfromthislist. It takesanysize.
11) Horizontal Scrollbar : Createstand-aloneHorizontal scroll bars.
12) Vertical Scrollbar : Createstand-alonevertical scroll bars.
13) Timer : Usedtocontrol object movement.
14) DriveList Box : It isaspecial ListBox filledautomaticallywithnames, of the
filesinaspecifieddirectory. It isalist invariant.
15) Dir List Box : It isaspecial ListBox filledwithdrives(Harddisc, Flopy, CD)
inthesystem. It isaninvariant.
16) FileList Box : It isaspecial ListBox filledautomaticallywiththenamesof all
DirListBox. It isalist invariant.
17) Shape : Usedonlytodisplayrectangles, circles, andovalsontheforms. Never
raisesanyevents
18) Line :Usedonlytodisplaylinesontheforms. It never raisesanyevents.
19) Image : Used instead of PictureBox because it consumes fewer system
resources.
20) Data : usedfor database.
21) OLE : usedfor joiningwithanother programs.
13
Tool BoxandForm
Theuser can placethetool on formand then work with thetool. To placethe
tool onform:
Clickontool >Drawtool toForm>thetool appearsonForm.
Or: doubleclickonit.
Notes:
a) Each tool has a property window .To see this window: Click on tool on form>
Propertywindowappears.
b) Propertycanbechangedmanually or by codeandtheeffect of codeappears inthe
runtime(whenuser runsproject).
c) Toput codefor tool action:
Doubleclick on tool >codesheet of theFormappears (with codeof corresponding
tool is written) >User write the desired code inside tool event, or outside in Form
event.
WorkingWithTools
Theuser canworkwithtool inthedesignstage.
- To add tool: doubleclick ontool. Tool appears onformor drags it to design
part of pageanddrawit inthedesiredsize.
- Todelete: click onelement inpage>pressdeletekeyof thekeyboardor right
clickonobject for mouselist>choosedelete.
- To display tool properties window: click on element>properties window
appear.
- Todisplaycodeform: doubleclickontool codeformfor that element.
Label:
It isusedtodisplayfixedtext onform
Property
name
Objective Code Stageof Changing
Caption Stringappear onlabel label
no.
.caption="anyname" Designandrun
Autosize Toresizetool tofit text label
no.
.autosize=trueor false Designandrun
Backcolor Backgroundcolor for label label
no.
.Backcolor=Qbcolor(no.) Designandrun
Forecolor Color of text writtenonlabel label
no.
.forecolor=Qbcolor(no.) Designandrun
Font Font style, typeandsize Size: label
no.
.fontsize=no.
Style:

underline
bold
italic
font
Type: label.FontName="arial"
Designandrun
visible The label appear or
disappear
Label
no
.visible=trueor false Designandrun
Enabled Thelabel enableor disable. label
no.
. Enabled=trueor false Designandrun
Note: Theavailablecolor numbersthat usedwithQBcolor istheintegers0to15only.
14
Example: Designaformcontainslabel " " insize14.
Sol: thepropertiesare:
Label1
caption Appliedscience
fontsize 14
Runningstage:
Textbox
Thetextbox is a box for entering and displaying text (characters or values) in
user project. This tool is used frequently in most of theapplication. Thetextbox has
property window, with no caption, but with space for text. The most important
propertyof thistool isthetext content whichisdescribedinthefollowing:
Property
name
Objective Code
Stage of
Changing
Text Stringappear ontextbox text
no.
. text ="anyname" Designandrun
multiline Toenter morethanoneline trueor false Design
Backcolor Backgroundcolor for textbox. text
no.
.Backcolor=Qbcolor(no.) Designandrun
Forecolor Color of text writtenontextbox. text
no.
.forecolor=Qbcolor(no.) Designandrun
15
Font Font style, typeandsize. Size: text
no.
.fontsize=no.
Style:

underline
bold
italic
font
Type: label.FontName="arial"
Designandrun
visible Thetextboxappear or disappear text
no
.visible=trueor false Designandrun
Enabled Thetextboxenableor disable. text
no.
. Enabled=trueor false Designandrun
passwordchar A row of symbols appear
insteadof letters
Text
no
.passwordchar=(symbol) Designandrun
Setfocus Put the focus on the specified
textbox
Text
no
.setfocus Run
Change text manually: change text property from property window, click
insidetextboxandaddtext.
Changetext bycode:
1- Text1.text=" "
2- Text1.text=" "
3-Text1.text=text2.text
4- Text1.text=label1.caption
5- Text1.text =inputbox("")
Example: Design a formto enter username and password such that the title of the
formisVB.
Sol: designstage
Form1
caption V.B
Text1
text
Text2
Text
Label1
caption username
Label2
caption password
Label1
Label2
Text2
Text1
16
Example: Designaformwithonetextbox, set thetext propertiessothat thismassage
appearswhenproject runs(welcometovisual basicworld).
Sol: Therearetwomethods:
First method: changingpropertybycode:
PrivateSubForm_Load()
Text1.Text ="welcometovisual basicworld"
EndSub
Secondmethod: bypropertieswindow
Text1
text Welcometovisual basicworld
Runningstage
Commandbutton
It acts as a switch. To deal with tool property>click on command button>property
window appear> change setting of any desired property. Usually change set its
captionpropertytoasuitablestring.
To makethebutton functional, theuser should add somecode. To do this: click on
command tool>code formappears with click event procedure. Write code in this
event or other eventslikepresskeyevent.
Text1
Writecodehere
17
Themost familiar properties that areneededfor thecommandbuttonarestatedinthe
tablebelow.
Property
name
Objective Code Stageof Changing
Caption Stringappear oncommand command
no.
.caption="anyname" Designandrun
style Determine the style of
command
1-graphical
0-standard
Design
Backcolor Background color for
command
command
no.
.Backcolor=Qbcolor(
no.)
Designandrun
Forecolor Color of text written on
command
command
no.
.forecolor=Qbcolor(
no.)
Designandrun
Font Font style, typeandsize Size: command
no.
.fontsize=no.
Style:

underline
bold
italic
font
Type: command
no
.FontName =
"arial"
Designandrun
visible The command appear or
disappear
command
no
.visible=trueor false Designandrun
Enabled The command enable or
disable.
command
no.
. Enabled =true or
false
Designandrun
Example: Design a formwith label, such that when click on the command button
"name" your nameappearsonlabel (at runningstage).
sol:
Label1
caption
Command1
caption name
PrivateSubCommand1_Click()
Label1.Caption="Ahmad"
EndSub
Example: Designaformto appear your nameanddepartment intextbox, whenclick
oncommandbutton"name" and"department" respectivelysothat youcanclear these
informations when click on command "clear" and stop project when click on
command"exit".
Label1
Command1
18
Text1
text
Command1
caption name
Command2
caption department
Command3
caption Clear
Command4
caption exit
PrivateSubCommand1_Click()
Text1.text="Muna"
EndSub
PrivateSubCommand2_Click()
Text1.text="Science"
EndSub
PrivateSubCommand3_Click()
Text1.text=" "
EndSub
PrivateSubCommand4_Click()
end
EndSub
Example: Designaformcontainstwotextbox sothat whenclick oncommandbutton
"copy" thetext copiedfromfirst textboxtothesecondtextboxbut insize(28).
Sol:
Text1
text
Text2
Text
Command1
caption copy
Command3
Command1
Command4
Command2
Text1
19
PrivateSubCommand1_Click()
Text2.Text =Text1.Text
Text2.FontSize=28
EndSub
At runstagethiswindowappear
If the user enter by example the text (ABC) in first textbox and click on
command(copy) thesametext appear onthesecondtextboxbut insize28.
Exercise:
1- Designaformtodisplayyour nameinspecificcolor andsize.
2- Writethefollowingdesignstepswithdetails
20
Shape: Shapeisatool usedtodrawgeometricshape(circle, rectangle, square,etc). It
haspropertywindow. I t hasnoeventslikeother tools(suchasclick, dblclick, etc.).
Property
name
Objective Stageof Changing
shape Todetermineaspecificshape:
0-rectangle
1-square
2-oval
3-circle
4-roundedrectangle
5-roundedsquare
Designandrun
backstyle 0-trancsparence
1-opaque
Design
Backcolor colored the Background for shape, appear after
backstylechangedtovalue1-opaque
Designandrun
bordercolor ColoredtheBorder of shape Designandrun
Example: Designaformcontains aspecific shapethenwritethenameof this shape
onform.
Label1
caption circle
Shape1
shape 3- circle
List box: Theuser can't writedirectlyinListBox. HecanadditemtotheListBox
propertyor bycodeintheform.
Propertyname Objectiveandcode
sorted
True, tosort theelementsalphabetically
False, elementswithout sort.
Style Todeterminethestyleof list:
0-standard
1-checkbox
Clear list Toclear all elementsof thelist:
List
no
.Clear
Additemstolist:
a) Changepropertylist frompropertieswindow. Whenclickonarrow, write
items(elements).
Label1
Shape1
21
b) Addelementsbycodeusingthepropertyadditemasfollows::
List
no
.additem("first element ")
List
no
.additem("secondelement ")
.
.
.
List
no
.additem("last element")
Example: Designaformcontainslabel todisplayyour department andtwocommand
buttons "show" and "hide" such that when click on command1, form2 appears and
when click on command2, form2 disappears. In form2 design a list to contain the
name of departments branches which appears after click on command button
"display".
Form1
Label1: caption="appliedscience"
Command1: caption="show"
Command2: caption="hide"
Form2
Command1: caption="display"
List1: list=
Label1
Command
2
Command
1
List1
Comman
22
Example: Designaformcontainsasortedlist alphabeticallysuchthat theuser can
addtheitemfromtext tothelist after clickoncommandbutton"add".
Sol:
List1
list
sorted true
command1
caption add
Text1
text
PrivateSubCommand1_Click()
list1.AddItem(Text1.Text)
Text1.Text =" "
EndSub
Optionbutton: Usedonlyasagroupof buttons. Whentheuser selectsoneof them
theothersaredeselectedautomatically.
All other properties of this control are similar to those in formand command
buttonwherethey arefully discussedwhicharecaption, font, enabled, backcolor and
visiblebesideanimportant propertywhichisvaluethat takestrueor falseandit used
withif statement. Theoptionbuttonusuallytakesclickevent.
Example: Design a formwith three option buttons " red ", " green " and " blue "
such that when we click on options the color of the formcolored by red, green and
bluerespectively.
green option1:caption
blue option2: caption
red option3: caption
PrivateSubOption1_Click()
Form1.BackColor =vbGreen
EndSub
PrivateSubOption2_Click()
Form1.BackColor =vbBlue
EndSub
PrivateSubOption3_Click()
Form1.BackColor =vbRed
EndSub
23
Check box:
Any number of check boxes canbe usedonaform. They work independently.
Its Property valuecouldbechangedindesignstagemanually, or inrunningstageby
code.
Example: Designaformwithonetext boxandthreecheckboxessuchthat when
clickonboxesthefollowingisdone: changetypingtobold, italic, underline.
Sol:
Text1
Text
Check1
caption Bold
Check2
caption Italic
Check3
caption underline
PrivateSubCheck1_Click()
Text1.FontBold=Check1.Value
EndSub
PrivateSubCheck2_Click()
Text1.FontItalic=Check2.Value
EndSub
PrivateSubCheck3_Click()
Text1.FontUnderline=Check3.Value
EndSub
Runstage:
Text1
Check1
Check2
Check3
24
Timer
Timer returnsthetimeinmillisecond. It maybeusedtomeasureexecutiontimeof
code(programefficiency).
Propertyname Objectiveandcode
interval To repeat the code according to event. It takes an
integer values(0-65535) andmeasuredinmillisecond
enabled timer
no.
. Enabled=trueor false
Ex: designelectronicclocktodisplaythetimeinseconds.
sol:
Timer1
interval 1000
Label1
Caption
PrivateSubTimer1_Timer()
Label1.Caption=Time
EndSub
Example: Designaformtodisplay"appliedscience" suchthat whenclick on
commandbutton"start" thecolor of "appliedscience" changedrandomlyevery
second.
Sol:
Timer1
interval 1000
enabled false
Label1
Caption

Command1
caption
PrivateSubCommand1_Click()
Timer1.Enabled=True
EndSub
PrivateSubTimer1_Timer()
t =Rnd* 15
Label1.ForeColor =QBColor(CInt(t))
Label1
Timer1
Label1
Timer1
Command
25
EndSub
Runstage:
Whenclickoncommandbutton thecolor of thefont will bechangedeverysecond
randomlyininteger no. (0-15).
Note: thefunction(Cint) usedtoconvert tointeger no.
And(Rnd) usedtogeneratearandomno. inarange(0-1)
I nput - output boxes
Therearetwotypesof dialogboxeswhichareinputboxandmessagebox. Thefirst is
usedtoinput variableandthesecondtooutput variableor message. Bothneedscode
andappear at runtime.
a) Inputbox
Inputboxusedtoinput valueor charactersfor onevariablefromkeyboardat running
stage.
Thisboxneedsacodeincodesheet andcouldbewritteninanyevent or command
X=inputbox(" prompt or remark", "title")
Example: enter valueof xusinginputbox
Sol:
PrivateSubForm_Load()
X=Inputbox("enter valueof x", "calculation")
EndSub
26
Messagebox
It isusedtooutput amessagetotheuser (at runningstage) thecodeneededcouldbe
writtenincodesheet andinanyevent or command.
Theavailableiconsfor messagebox
icon value structure
16 vbcritical
32 vbquestion
48 vbexclamation
64 vbinformation
Theavailablecommandsfor messagebox
Commands value structure
Ok 0 Vbokonly
Ok, Cancel 1 Vbokcancel
Abort, Retry, Ignore 2 vbAbortRetryIgnor
Yes, No, Cancel 3 vbYesNoCancel
Yes, No 4 vbYesNo
Retry, Cancel 5 vbRetryCancel
For exampleif wewritethefollowingstatement thenamessageboxwill beappear as
shownbelow
MsgBox"pleasecloseyour program", 16, "Error"
or
MsgBox"pleasecloseyour program", vbcritical, "Error"
Example: showwhat appear after runningthefollowingstatement
MsgBox"areyousureyouwant todeletethisfile", 32+4, "delete"
or
MsgBox"areyousureyouwant todeletethisfile",vbQuestion+vbYesNo,"delete"
Sol:
27
Example: writeaprogramtomovethetext (excellent) fromtextboxtomessagebox
andchangethecolor of thetext after clickoncommandbutton(display).
Sol:
Text1: text="excellent"
Command1: caption=""
PrivateSubCommand1_Click()
MsgBox(Text1.Text)
Text1.BackColor =QBColor(9)
Text1.Text =" "
EndSub
Or wecanwritethefollowingcode:
PrivateSubCommand1_Click()
X=Text1.Text
MsgBox(X)
Text1.BackColor =QBColor(9)
Text1.Text =" "
EndSub
28
Exercises
Q1/designaformcontainsspecifictitlesuchthat whenweclickoncommand1the
color of thefont will changeandweclickoncommand2thesizeof thefont will be
change.
Q2\designaformcontainsshapeandcommandbuttons"what isthis" suchthat when
clickonthecommandbuttonthenameof thisshapeappearsinmessagebox.
Q3/enter atext inlabel1suchthat thistext copiedtolabel2after clickoncommand
button"copy" anddeletefromlabel2after clickoncommandbutton"delete".
Q4/ designaformcontaincommandbuttonsuchthat whenweclickoncommand,
form2will beappear andform1will bedisappear.
Q5/designaform"at runstage" thetitleof form1will bechangeto"visual basic" and
thebackcolor of form1will changetoo.
Q6/designaformwithtwoshapes, redandblue,writecodetoreplacethecolor every
betweentwoshapes.
Q7/ designaformcontainlist boxandtwocommandbuttons:
1- add: toaddtheelement tothelist frominput box
2- delete: todeletethelist elements
29
Visual basicstatements
Invisual basicprogram(code) therearefour basicparts, i.e. it iscontains
thefollowingstatements:
1- Declarationof variablesandconstants
2- Inputtingvariables
3- Operatorsfor variables
4- Outputtingvariables
1- Declarationof avariableandconstants
Thedeclarationmeansdefiningthedatatype(variableor constant).
Variables
A variableisaspaceinmemoryfilledwithdata(value, character, time
or date).
Notes:
- Variable name must start with character (not number or function) and
maximumlength256character, anddoesnot containpoint or symbol.
- Variablenamemust not repeat for other values.
Thevariablehastobedeclared. Variabletypeisdefinedbyitscontent .The
content maybedataasnumericor character or stringor Booleanor date, or
anytypeof data(calledvariant), thesetypesdeclaredas:
Dimvariablenameastype
Or
Global variablenameastype
Note: TheDimdeclarationwritteningeneral part of theformor inany
placeinformor subprocedurewhichusedfor oneform. WhileGlobal
declarationusedfor all forms
Thetypesof variablesthat areallowedinvisual basicarestatedinthetable
below.
Typesof variables
Type Valuerange Declaration
1-Integer -32768<x<32768 Dimxasinteger
2-Long -2.1e+009<x<2.1e+009 Dimxaslong
3-Single 1.4e-045<|x|<3.4e+038 Dimxassingle
4-Double 4.9e-324<x<1.79e+308 Dimxasdouble
30
5-String 65535characters Dimxasstring
6-Boolean Trueor false DimxasBoolean
7-Date Computer timeanddate
J an100<x<31Dec9999
Dimxasdate
Constants
It isaspaceinmemoryfilledwithfixedvaluethat will not bechanged.
Constant maybedeclaredas:
Const constant name=value
Example: Declarexasaconstant (P), thencomputetheareaof acircle. Put
suitabledesign.
Sol:
Form1
Areaof acircle caption
label1
radius Caption
Text1

text
Command1
compute caption
false Enabled
codestage:
Const p=3.14159
Dima, r AsSingle
PrivateSubText1_Change()
Command1.Enabled=True
EndSub
PrivateSubCommand1_Click()
r =Val (Text1.Text)
a=r ^2* p
MsgBox("area=" & a)
Text1.Text =" "
Text1.SetFocus
EndSub
31
2- I nputtingvariables
Therearemethodstoinput variablexasstatedinthefollowing:
Methodof input For all typeof variable
Intext tool X=text
no
.text
Ininput box X=inputbox("prompt","title")
Note: Toenter manyvariablesweusuallyusethesecondmethodwithloop.
3- Operatorsfor variables
Theoperatorsthat areusedfor variablearedescribedinthefollowing
table
Arithmeticoperators
+ addition
- subtraction
* multiplication
/ division
mod Modulusrest of division
^ exponent
Relational operators
= equal
< Lessthan
<= Lessor equal
> Greater than
>= Greater or equal
<> Not equal
Note: Theorder of operationswhenexecutingarithmeticoperationis:
Exponentiation- multiplicationdivisionandmod- finallyadditionand
subtraction.
Themathematical representationmust bewrittenasvisual basic
representationinthecodeasfollowingexamples:
Programmingrepresentation Mathematical representation
3*(x+4*y) 3(x+4y)
2 / 4 2 ^ X
2 4
2
X
3 ^ 2 2 ^ 3 / ) 4 * 5 ( 10 3 ^ 3 ) 4 / 1 ( ^ 16
3 2 3 4
2 3 4 5 10 3 16
(5*y)/(x^2-4)+x-1
1
4
5
2

x
x
y
Exp(2*x)/(cos(2*x)+sin(x))
) sin( ) 2 cos(
2
x x
e
x

32
Assignment statement
Therearemanystatementswaystofill avariableasfollows:
Variable=expression
Expressionmayincludevariables, operationsandfunctionsasfollows:
1- Numerical variable. For example: i=3
2- Mathematical relation. For example: x=a/b
3- Charactersvariable(string). For example: t="abc"
4- Booleanvariable(logical). For example: p=true
Functionsfor variables
Thenumericandstringvariablesarethemost commonusedvariables
inprogramming, thereforeV.B providestheuser withmanyfunctionstobe
usedwithavariabletoperformcertainoperationsor typeconvention. The
most commonfunctionsfor numerical variablex
Function Description
Abs(x) Absoluteof x
Sqr(x) Squareroot of x
Int(x) Integer of x
Exp(x) Exponential of x(e
x
)
Fix(x) Taketheinteger part
Sin(x), cos(x), tan(x) Trigonometricfunctions
Log(x) Natural logarithms
Len(x) Number of character of variablex
Lcase(x) Changethetext xtosmall letters
Ucase(x) Changethetext xtocapital letters
Cint(x) Convert xtointeger
Clong(x) Convert xtolonginteger
Cdbl(x) Convert xtodoubleprecision
Cstr(x) Convert variablextostring
Val(x) Convert stringxtonumerical variable
Note: thelast fivefunctionsarecalledconversionfunctions.
Thefollowingfunctionsfor different xaregivenfor comparison.
Function output
X=lcase("MY NAME IS") mynameis
X=ucase("mynameis") MY NAME IS
int(2.5) 2
Int(-2.5) -3
Fix(2.5) 2
Fix(-2.5) -2
33
4- Outputtingvariables
Therearemethodstooutput variablexasstatedinthefollowing:
Methodof output For all typeof variable
Onform Print x
Note: inloadevent wemust usethestatement:
(form1.show)
totext tool text
no
.text =X
tolabel tool Label
no
.caption=x
Bymessagebox msgbox(x)
Or msgbox("remark"& x)
Theinstructionprint couldbeveryhelpful todisplaydataandusedas
follows:
Code Description example
print Toleaveonelineand
print onnext
Print "a", "b", "c" Use(,) toprint adistance
betweenoutputs
a b c
Print "a"; "b"; "c" Use(;) toprint the
outputsadjacent
abc
Print "a","b";
Print "c"
Print a, bthenprint con
thesameline
abc
Example1: writeaprogramtoenter anytext andcomputeitslength. Put
suitabledesign.
Sol:
Designstage:
Form1
Caption Stringlength
Command1
caption Clickhere
Label1
Caption Length=
Text1
Text
34
Codestage:
DimsAsString
PrivateSubCommand1_Click()
s=InputBox("inter string")
L =Len(s)
Text1.Text =CStr(L)
EndSub
Runningstage:
Example2: writeaprogramtoaddandsubtract twointeger numbersafter
puttingasuitabledesign. Usemessageboxfor outputting.
Designstage:
form
calculator caption
Command1
+ caption
Command2
- Caption
Label1
Enter no.1 Caption
Label2
Enter no.2 Caption
text1, text2 text
35
Codestage:
Dimx, y, z asinteger
Privatesubcommand1_click()
X=val(text1.text)
Y=val(text2.text)
Z=x+y
Msgbox("additionresult="&z)
Endsub
Privatesubcommand2_click()
X=val(text1.text)
Y=val(text2.text)
Z=x- y
Msgbox("subtractionresult="&z)
Endsub
Runningstage
Enter twovaluesintext1andtext2. Whenclickoncommand(+) or (-) the
additionor subtractionresult appearsinmessagebox.
Example3: writeaprogramtoexecutethefour operationsaccordingtothe
followingdesign.
Codestage:
Dima,b, cassingle
Privatesubcommand1_click()
a=val(text1.text)
b=val(text2.text)
c=a+b
Endsub
Command6
Command1
Command5
Command2
Command3
Command4
Label3
Label2
Label1
36
Privatesubcommand2_click()
a=val(text1.text)
b=val(text2.text)
c=a- b
Endsub
Privatesubcommand3_click()
a=val(text1.text)
b=val(text2.text)
c=a* b
Endsub
Privatesubcommand4_click()
a=val(text1.text)
b=val(text2.text)
c=a/ b
Endsub
Privatesubcommand5_click()
Text3.text=cstr(c)
Endsub
Privatesubcommand6_click()
Text1.text=" "
Text2.text=" "
Text3.text=" "
Endsub
Example4: writeaprogramtocomputethefunctions: sine, cosine, integer
value, square, absolutevalue.
sol:
Designstage:
Dimx, yAsSingle
PrivateSubcommand1_click()
x=Val(Text1.Text)
y=Abs(x)
Text1.Text =CStr(y)
EndSub
PrivateSubCommand2_Click()
x=Val(Text1.Text)
y=Sqr(x)
Text1.Text =CStr(y)
EndSub
37
PrivateSubCommand3_Click()
x=Val(Text1.Text)
y=Int(x)
Text1.Text =CStr(y)
EndSub
PrivateSubCommand4_Click()
x=Val(Text1.Text)
y=Sin(x* 3.14159/ 180)
Text1.Text =CStr(y)
EndSub
PrivateSubCommand5_Click()
x=Val(Text1.Text)
y=Cos(x* 3.14159/ 180)
Text1.Text =CStr(y)
EndSub
Runningstage
38
Q1/ WriteaProgramtocomputetheareaof trianglewithdesign.
Q2/Writeaprogramtoenter thenameof astudent andtwomarksof any
subject byinput boxthencomputestheaverageanddisplaythenameand
averageintwolabels.
Q3/ Writeaprogramtoenter areal number thenfinditssquareafter putting
suitabledesign.
Q4/ Designaproject withthreeforms, suchthat form1containstwo
commandbuttons"Pethagorsequation" and"areaof triangle" suchthat
whenclickoncommand1"Pythagorasequation", form2will beappear soin
thisformthethirdsideof trianglewill becomputewithPythagorasequation
after enter thefirst andsecondside, andwhenclickon"areaof triangle" the
thirdformdisplayedsothat theareawill becomputeafter enteringthebase
andheight. Usesuitableoutput andinput methods.
Q5/ Writeaprogramtodisplaythemessagebelowafter clickoncommand
button"run".
Q6/Writeaprogramtodisplaythetimeandthedate, put asuitabledesign.
39
Menu
The menu is a bar at the top of the form. The standard formis
display without menu, but the user can add it. This menu could be
includedinformusingmenueditor. Innext sectionthemenueditor and
therequiredcodewill bediscussed.
MenuEditor
Tousemenutherearethreeways:
1- Pressmenuiconfromtoolbar .
2- press(ctrl+E) fromkeyboard.
3- clickon: tools>MenuEditor.
Menueditor boxappearsasshownbelow.
Thestepsof applyingmenueditor boxareasfollows:
Toadditem Usemenueditor asfollows
Toaddmanyitems UsethemenuEditor
Select
short cut
Remove
Add
Moveitemup
Moveitemdown
Movetonext iteminthelist
Delet item
40
CreatesubMenulist UsemenuEditor
CreateShortcut Use& withcaptionandselect shortcut
Codefor menuitems
Eachiteminmenuor submenuisconsideredasacommandwhich
takestheevent clickonly. Theuser canaddcodefor eachitem:
clickonitem>codefor that itemappearsoncodesheet. Alsocodecanbe
addedtoform: clickonitem>codefor that itemappearsoncodesheet.
Thisisdescribedinthefollowingfigure:
Example: Designaformwithmenuandalabel withaspecifictitle. The
menucontainsoneitemcolor withsubmenuitems: red, green, blueand
exit, tocolor thelabel inred, green, bluethenexit fromtheprogram.
Sol: put label1withanycaptionfor example(hello)
Caption: color
Name: command1
Createstandardmenu(color) frommenu
editor>next
Caption: red
Name:command2
Addsubmenuitemsbypressing thenenter
thecaptionandname>next.
Clickonitem
41
Caption: green
Name:command3
Dothesamethinksfor other items>ok
Caption: blue
Name:command4
Caption: exit
Name:command5
Shortcut: ctrl+E
Toprogrammingthesecommandsclickoneachonetoopenitscode
windowandwritethefollowingcode:
Privatesubcommand2_click()
Label1.backcolor=vbred
EndSub
Privatesubcommand3_click()
Label1.backcolor=vbgreen
EndSub
Privatesubcommand4_click()
Label1.backcolor=vbblue
EndSub
Privatesubcommand5_click()
End
EndSub
42
Conditional statements
Therearetwotypesof conditional statements:
1- If statement
2- Select case
1- I f statement: Thecomparisonoperationsareusedwithconditional
statements.
Thecomparisonoperationsare: (<, <=, >, >=, =, <>, and, or)
Therearefour structuresfor if statement.
a) SimplestructureI f.. then:
Usedfor runningoneprogrammingstatement onlyif therequired
conditionsatisfied.
Thegeneral formis: I f conditionthenstatement
Example1: writeaprogramtoenter amarkof astudent thenprint (pass) if
hesuccessful.
Sol:
Dimxasinteger
Privatesubcommand1_click()
X=cint(text1.text)
If x>=50thentext2.text="pass"
Endsub
b) I f block structure: Usedfor runningmanyprogrammingstatementsif
therequiredconditionsatisfied.
Thegeneral formis:
I f conditionthen
Statements
Endif
Example2: writeaprogramtoenter amarkof astudent thenprint (pass)
insize18if hesuccessful.
Sol:
Dimxasinteger
Privatesubcommand1_click()
X=cint(text1.text)
If x>=50then
text2.text="pass"
text2.fontsize=18
endif
Endsub
43
c) I f.. Then.. Elsestructure: Usedfor runningmanyprogramming
statementsif therequiredconditionsatisfied. Andrunninganother
programmingstatements(after else) if therequiredconditionnot satisfied.
Thegeneral formis:
I f conditionthen
Statements
Else
Statements
Endif
Example3: writeaprogramtoenter amarkof astudent thenprint (pass) if
hesuccessful andprint (fail) otherwise.
Sol:
DimxAsInteger
PrivateSubcommand1_click()
x=CInt(Text1.Text)
If x>=50Then
Text2.Text ="pass"
Else
Text2.Text ="fail"
EndIf
EndSub
d) I f.. Then.. Elseif.. Elsestructure:
Usedif wehavemanyconditionstobesatisfied
Example4: writeaprogramtoenter auser nameanddisplaythemessage
(hello) threetimes. Thefirst onefor (Muna), thesecondonefor (Maha) and
thethirdfor anyuser asaguest.
Sol:
DimxAsString
PrivateSubcommand1_click()
x=Text1.Text
If x="Muna" Then
MsgBox"hello, Muna"
ElseIf x="Maha" Then
MsgBox"hello,Maha"
Else
MsgBox"hello, guest"
EndIf
EndSub
44
Example5: Writeaprogramtoclassifyanyenterednumber accordingto
itssignanddisplaythephrase(negativenumber) whenthenumber is
negativeandthephrase(positivenumber) whenthenumber ispositive,
otherwisedisplaythephrase(neither positivenor negative).
Sol:
DimxAsSingle
PrivateSubcommand1_click()
x=Val(Text1.Text)
If x>0Then
MsgBox"positivenumber"
ElseIf x<0Then
MsgBox"negativenumber"
Else
MsgBox"neither positivenor negative"
EndIf
EndSub
NestedI f statement:
It canbetakesthefollowingstructure:
I f condition then
1 structure

I f conditionthen
2 structure

Statements
Endif
Endif
Note: Anystructureof if structurescanbeused insteadeof structure1
and2above.
Example6: Writeaprogramtoenter twonumbersand
computemultiplicationanddivisionoperationsusing
optionbuttonwithdisplaythephrase(illegal division
operation) whenthedenominator iszero.
Sol:
Dima, b, cAsSingle
PrivateSubcommand1_click()
a=Val(Text1.Text)
b=Val(Text2.Text)
If Option1.ValueThen
c=a* b
Text3.Text =CStr(c)
Else
45
If b<>0Then
c=a/ b
Text3.Text =CStr(c)
Else
Text3.Text ="illegal divisionoperation"
EndIf
EndIf
EndSub
Select statement
Usedfor applyingmanystatementsdependingononevariable. The
general formis:
Select casevariable
Casevalue1
statements
Casevalue2
Statements
.
.
.
Casevaluen
Statements
Caseelse
Statements
Endselect
Example7: writeaprogramtoprint thedaysof theweekwhenweenter
itsnumber
Sol:
DimxAsInteger
PrivateSubCommand1_Click()
x=CInt(Text1.Text)
Select Casex
Case1
MsgBox("Sunday")
Case2
MsgBox("Monday")
Case3
MsgBox("Tuesday")
Case4
MsgBox("Thursday")
Case5
MsgBox("Wednesday")
46
Case6
MsgBox("Friday")
Case7
MsgBox("Saturday")
EndSelect
EndSub
Example8: writeaprogramtogivetheevaluationfor different marks
asfollows:
evaluation mark
Excellent 90-100
Verygood 80-89
Good 70-79
Medium 60-69
Pass 50-59
Fail 0-49
DimxAsInteger
PrivateSubCommand1_Click()
x=CInt(Text1.Text)
Select Casex
Case90To100
MsgBox("excellent")
Case80To89
MsgBox("verygood")
Case70To79
MsgBox("good")
Case60To69
MsgBox("medium")
Case50To59
MsgBox("pass")
Case0To49
MsgBox("fail")
CaseElse
MsgBox"therangeis0-100", vbCritical, "error"
EndSelect
EndSub
47
Exercises
Q.1/ Designaformwiththreemenusandlabel withaspecifictitle.
Themenuscontainsubmenusasfollows: color: red, blue, green, style:
underline, bold, italic, size: 10, 20, 30thenwritethecodefor each
command.
Q.2/ Writeaprogramtoenter avalueof xandcomputethevalueof y
where

<
>
=
0
0
x if x
x if x
y
Q.3/ Writeaprogramtofindtheroot of first degreeequation.
Q4/ writeaprogramtoenter twonumbersandprint thelargest
number.
Q.5/ Writeaprogramtoenter twonumbersandcompute
multiplicationanddivisionoperationsusingcheckboxwithdisplayingthe
phrase(illegal divisionoperation) whenthedenominator iszero.
Q.6/ Designaformwithatext box. Useselect statement sothat when
user entersg, b, r andythenformcoloredtogreen, blue, red, andyellow
respectively.
48
Loopstatement:
Visual basicsupportsstatement toperformloops. Theloopsstatementscould
havedifferent structuresasfollows:
1- Counter loop.
2- Conditional loop.
1- Counter loop:
Loopsapplyprogrammingstatementsfor fixednumber of timesusingcounter
(fornext) statement.
Thegeneral formis:
For variable=start value to endvalue step stepvalue
Statements
Next variable
Example1: Writeaprogramtoprint (hello) fivetimes.
Sol:
Dimi asinteger
PrivateSubCommand1_Click()
For i =1To5
Print "hello"
Next i
EndSub
Example2: Writeaprogramtoprint evennumbersfrom1to10.
Sol:
Dimi asinteger
PrivateSubCommand1_Click()
For i =2To10step2
Print i
Next i
EndSub
Notes:
1-Thevariable'svaluethat weuseascounter must beinteger value(integer, long).
2- If wedont determinedthestepvaluethentheassumedvalueis1.
3- If thefinal valuesmallest thantheinitial value, thenthestepvaluemust be
negative.
2- Conditional loop
Loopsrepeat programmingstatementsaccordingtospecificcondition. Thereare
twotypesof conditional loop:
1- Dowhile
2- Dountil
1-Dowhileloop: Inthisloopthestatementswill beimplementedandrepeatedwhen
ever theconditionsatisfied. Thegeneral formis:
49
Dowhilecondition
Statements
Loop
Example3: Writeaprogramtoprint (hello) fivetimeswithitsnumberingusingdo
whileloop.
Sol:
Dimi asinteger
PrivateSubCommand1_Click ()
i =1
Dowhilei <=5
Print "hello"; i
i =i +1
Loop
EndSub
Example4: Writeaprogramtoprint evennumbersfrom1to10.
Sol:
Dimi asinteger
PrivateSubCommand1_Click()
i =2
Dowhilei <=10
Print i
i =i +2
Loop
EndSub
2-Do until loop: In this loop thestatements will beimplemented and repeated when
ever the condition not satisfied, (i.e) the loop will be stopped when the condition
satisfied. Thegeneral formis:
Dountil condition
Statements
Loop
Example5: Writeaprogramtoprint (hello) fivetimeswithitsnumberingusingdo
until loop.
Sol:
Dimi asinteger
PrivateSubCommand1_Click ()
i =1
Dountil i >5
Print "hello"; i
i =i +1
Loop
EndSub
50
Example6: Writeaprogramtofindthesummationof undeterminednumber of
positivenumberssuchthat theprogramwill bestoppedwhenweenter negative
number.
Sol:
Dimx, sumAsSingle
PrivateSubcommand1_click()
sum=0
x=Val(InputBox("enter x", "summation"))
DoWhilex>=0
sum=sum+x
x=Val(InputBox("enter x", "summation"))
Loop
MsgBox(CStr(sum))
EndSub
Example7: Writeaprogramtofindthesummationof thenumbersfrom5to15.
Sol:
DimI, sumasinteger
PrivateSubcommand1_click ()
sum=0
For i =5to15
Sum=sum+i
Next i
Label1.caption="sum="&cstr(sum)
EndSub
Example8: Writeaprogramtofindthesummationof 10numbers.
Sol:
Dimi asinteger
Dimx, sumasdouble
PrivateSubcommand1_click ()
sum=0
For i =1to10
x=val(inputbox("enter number"))
Sum=sum+x
Next i
Label1.caption="sum="& cstr(sum)
EndSub
Runningstage:
For exampleif weenteredthenumbers: 1, 5, -1, 3, 2, 0, -1, 3, 0, -4thensum=8
51
Example9: Writeaprogramtofindtheaverageof nnumbers.
Sol:
Dimi asinteger
Dimx, sum, avasDouble
PrivateSubcommand1_click ()
i =1: sum=0
n=cint (text1.text)
Dowhilei <=n
x=val(inputbox("enter number"))
Sum=sum+x
i =i +1
Loop
Av=sum/n
Text2.text =cstr(av)
EndSub
Example10: Writeaprogramtoprint multipliersof 5(from5to50)
Sol:
Dimi asinteger
PrivateSubCommand1_Click ()
i =5
Dountil i >50
Print i
i =i +5
Loop
EndSub
Example11: writeaprogramtofindtheaverageof numbersthat dividableby3(with
out remainder) from3to99.
Sol:
DimI, n, sumasinteger
DimavasDouble
PrivateSubcommand1_click ()
i =3: n=0
sum=0
Dowhilei <=99
Sum=sum+i
i =i +3
n=n+1
Loop
Av=sum/n
Print "av="; av
EndSub
52
Example12: write a programto print (welcome) ten times, the first one with the
ordinary size and color. Then make the color changed and the size bigger at each
time.
Sol:
Dimi AsInteger
PrivateSubCommand1_Click()
Print "welcome"
For i =1To9
FontSize=10+i
ForeColor =QBColor(i)
Print "welcome"
Next i
EndSub
Series:
Tocomputethevalueof series, weusesuitableloopstatementsaccordingtothe
boundaries(limits) of eachseries.
Example13: Find
Sum=1+x+x
2
+x
3
++x
n
, wherexisaninteger.
Sol:
DimI, n, x, sumasinteger
PrivateSubcommand1_click ()
sum=1
n=cint(text1.text)
x=val(text2.text)
For i =1Ton
Sum=sum+x^i
Next i
Text3.text=cstr(sum)
EndSub
Nestedloop:
Thenestedloopsaretheloopsthat areplacedinsideeachother. Themost inner
loopwill beexecutedfirst, thentheouter ones. Theseloopsshouldneither intersect,
nor havethesameindex. Asfollows:
For i =1Ton
For j =1Tom
Statements
Next j
Next i
53
Example14: writeaprogramtoprint themultiplicationtable.
Sol:
DimI, j AsInteger
PrivateSubcommand1_click()
For I =1To10
For j =1To10
p=I * j
Print I; "*"; j; "="; p,
Next j
Print
Next I
EndSub
Example15: writeaprogramtogeneratethenumbersinthefollowingform.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Sol:
DimI, j AsInteger
PrivateSubcommand1_click()
For I =1To5
For j =1Toi
Print j;
Next j
Print
Next I
EndSub
54
Exercises:
Q.1: writeaprogramtofindnfactorial (n!)
Q.2: write a programto enter n numbers and find the average of negative numbers
only.
Q.3: writeaprogramto print themultipliers of 6from12to 60, usingdo whilefirst,
thenusedountil loopsecondly.
Q.4: computethevalueof ywhere:
n
x
n
x x x
y
3 2
3 2 1
1
Q.5: Findtheoddnumbersfrom1to100.
Q.6: Writeaprogramtogeneratethenumbersasfollows:
5555
444
33
2
Q.7: Howmanymultipliersof 3aretherebetween1and100? Writeaprogramtofind
that.

You might also like