Anda di halaman 1dari 80

Visual Basic

Handbook
Contents
Contents................................................................................................................................2
Introduction to Handbook...................................................................................................1
Deadlines and Course Structure............................................Error! Bookmark not defined.
Course Structure and Deadlines..............................................................Error! Bookmark not defined.
Preface..................................................................................................................................1
Common errors:....................................................................................................................................... 1
Conventions used in this book:................................................................................................................ 1
Introduction to Visual Basic...............................................................................................2
Chater 1 ! "our first ro#ram...........................................................................................$
Hello World!............................................................................................................................................. 3
Eercises................................................................................................................................................. !
Chater 2 ! %sin# Variables...............................................................................................&
"ariables.................................................................................................................................................. #
$he %ssi&nment Statement...................................................................................................................... '
$he Console.Writeline() Statement.......................................................................................................... *
$he Console.+eadline Statement............................................................................................................ *
%rithmetic E,ressions........................................................................................................................... 1-
Comments.............................................................................................................................................. 1-
Eercises............................................................................................................................................... 1-
Chater $ ! Data t'es......................................................................................................11
.nte&er.................................................................................................................................................... 11
B/te........................................................................................................................................................ 11
Decimal.................................................................................................................................................. 11
Sin&le0Double......................................................................................................................................... 11
Char....................................................................................................................................................... 11
Strin&...................................................................................................................................................... 11
Boolean.................................................................................................................................................. 11
Date....................................................................................................................................................... 13
2rdinal data t/,es.................................................................................................................................. 1!
Sim,le t/,es.......................................................................................................................................... 1!
Constants............................................................................................................................................... 1!
%dvanta&es of usin& named constants.................................................................................................. 1!
Eercises............................................................................................................................................... 1#
Etension eercises............................................................................................................................... 1'
Chater ( ! Selection........................................................................................................1)
.f 3 $hen............................................................................................................................................... 1*
Eercise................................................................................................................................................. 14
.f 3 $hen 3 Else................................................................................................................................... 14
Eercises............................................................................................................................................... 14
5ested .f statements.............................................................................................................................. 16
Eercises............................................................................................................................................... 16
.ndentation............................................................................................................................................. 16
Select Case............................................................................................................................................ 1-
Eercises............................................................................................................................................... 11
Chater & ! Iteration *reetition+......................................................................................22
7or loo,.................................................................................................................................................. 11
Eercises............................................................................................................................................... 11
+e,eat 8oo,.......................................................................................................................................... 1!
Do While................................................................................................................................................ 1#
Eercises............................................................................................................................................... 1#
Chater , ! -rra's.............................................................................................................2,
2ne9Dimensional %rra/s........................................................................................................................ 1*
Eercises............................................................................................................................................... 1*
$:o9Dimensional %rra/s........................................................................................................................ 14
Eercises............................................................................................................................................... 16
Enumerated $/,es................................................................................................................................. 16
Sets........................................................................................................................................................ 3-
Chater ) ! .unctions.......................................................................................................$1
Built9in 7unctions.................................................................................................................................... 31
Eercises............................................................................................................................................... 31
+andom 5umbers.................................................................................................................................. 31
Eercises............................................................................................................................................... 33
;ser9defined functions........................................................................................................................... 3!
8ocal "ariables....................................................................................................................................... 3!
Eercise................................................................................................................................................. 3#
Chater / ! Procedures.....................................................................................................$,
Worked Eam,le:................................................................................................................................... 3'
<arameters............................................................................................................................................ 34
"alue and "ariable <arameters.............................................................................................................. !-
Eercise................................................................................................................................................. !-
Chater 0 ! 1ecords..........................................................................................................(1
Eercises............................................................................................................................................... !1
%rra/s of +ecords.................................................................................................................................. !1
Eercises............................................................................................................................................... !1
Chater 12 ! .iles..............................................................................................................((
$et 7iles................................................................................................................................................ !!
Eercises............................................................................................................................................... !!
Serial 7iles............................................................................................................................................. !#
Se=uential 7iles..................................................................................................................................... !#
Direct %ccess 7iles................................................................................................................................. !#
Eercises............................................................................................................................................... !*
Chater 11 3indo4s .orms -lications.......................................................................(/
Hello :orld <ro&ram............................................................................................................................... !4
$etBoes.............................................................................................................................................. #-
Chan&in& <ro,erties.............................................................................................................................. #1
Chater 12 ! 5he Basic Calculator...................................................................................&$
<ro&ram 8istin& for Basic Calculator <ro&ram....................................................................................... #'
Chater 1$ ! %sin# VB- *Visual Basic for -lications+..............................................,2
Eercises............................................................................................................................................... '1
Event Driven <ro&rammin& in "B%........................................................................................................ '1
Eercises............................................................................................................................................... '1
"ariables................................................................................................................................................ '1
7unctions............................................................................................................................................... '!
Eercises............................................................................................................................................... '!
;ser Defined 7unctions.......................................................................................................................... '!
Eercises............................................................................................................................................... '!
$he DoCmd............................................................................................................................................ '#
Eercises............................................................................................................................................... '#
<ro,erties............................................................................................................................................... '#
Eercises............................................................................................................................................... ''
%mendin& >ueries................................................................................................................................. '*
Chater 1( ! 1ecord sets in VB-.....................................................................................,0
2,enin& a table...................................................................................................................................... '6
+eferrin& to fields................................................................................................................................... *-
+ecordset 7unctions.............................................................................................................................. *1
Eercises............................................................................................................................................... *1
1) 7inal 2,en Ended Challen&e Simulatin& checkout soft:are..........................................................*3
-endi6 -7 Pro#ress Self8-ssessment.........................................................................),
.ntroduction to <ro&rammin&
;sin& "isual Basic
Introduction to Handbook.
$his is the com,utin& handbook that :ill &uide /ou throu&h /our B2'# ;nit.
?ou :ill be usin& a lan&ua&e called "isual Basic :hich is nice lan&ua&e that has
a,,lication in real :orld s/stems. We :ill be usin& this lan&ua&e to hel, /ou understand
the basic conce,ts of ,ro&rammin&. $he second half of this handbook contains all /our
"isual Basic Cha,ters and tasks.
Preface
$his &uide is intended to ,rovide an introduction to the conce,ts of ,ro&rammin& in an
im,erative hi&h9level ,ro&rammin& lan&ua&e. $he book is desi&ned to be :orked throu&h
in se=uence@ each cha,ter buildin& on the ,revious oneA buildin& u, a basic kno:led&e of
,ro&rammin& conce,ts that can be a,,lied to ever/ hi&h9level lan&ua&e.
$he eercises :ill be marked b/ /our teacher a&ainst the follo:in& criteria (all ,ro&rams
should be ,seudo9coded or annotated):
# : Efficient use of code and &ood codin& la/out (indentions etc..)
!: 5o hel,@ ,roblem solved.
3: 8ittle hel,@ ,roblem solved.
1: <roblem solved :ith hel,.
1: <roblem not solved.
?ou :ill also have a :ritten ,ro&rammin& test after the unit of :ork on the conce,ts
outlined in this book. %lso@ as this &uide has been ,re,ared a&ainst the %>% %S
Com,utin& s,ecification /ou should ensure /ou are familiar :ith all of the content.
Common errors7
2vercom,licatin& ,ro&rams B al:a/s look for the sim,lest solution
Writin& ,seudo9code after :ritin& the ,ro&ram B it does hel, /ou to solve a ,roblem
use it!
%skin& /our teacher for hel, before /ou check /our o:n code B there is a useful
checklist of common errors at the back of this book (%,,endi %).
Con9entions used in this book7
Each maCor conce,t is introduced in a ne: cha,ter and an/ code :ill be hi&hli&hted in the
follo:in& :a/:
This is programming code;
<a&e 1
.ntroduction to <ro&rammin&
;sin& "isual Basic
Introduction to Visual Basic
VIS%-: B-SIC is a hi&h level ,ro&rammin& lan&ua&e :hich evolved from the earlier
D2S version called B%S.C. B-SIC means Be&innersD -ll9,ur,ose S/mbolic Instruction
Code. .t is a ver/ eas/ ,ro&rammin& lan&ua&e to learn. $he code look a lot like En&lish
8an&ua&e. Different soft:are com,anies ,roduced different versions of B%S.C@ such as
Eicrosoft >B%S.C@ >;.CFB%S.C@ GWB%S.C @.BE B%S.C% and so on. Ho:ever@ ,eo,le
,refer to use Eicrosoft "isual Basic toda/@ as it is a :ell develo,ed ,ro&rammin& lan&ua&e
and su,,ortin& resources are available ever/:here. 5o:@ there are man/ versions of "B
eist in the market@ the most ,o,ular one and still :idel/ used b/ man/ "B ,ro&rammers is
none other than "isual Basic '. We also have "B.net@ "B1--#@ "B1--4 and the latest
"B1-1-. Both "b1--4 and "B1-1- are full/ obCect oriented ,ro&rammin& (22<)
lan&ua&e. (source 9 htt,:00:::.vbtutor.net0lesson1.html)
<a&e 1
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 1 ! "our first ro#ram
$he environment :hich :e :ill be usin& to learn "isual Basic is Eicrosoft "isual Basic
1-1- E,ress. 7or the ,ur,ose of teachin& ,ro&rammin& basics :e :ill be usin& a
console a,,lication ,roCect althou&h to:ards the end :e :ill look at the event driven visual
side of "B <ro&rammin&.
When /ou create a ne: Console %,,lication ,roCect B /ou should see the follo:in& in the
code editor.
Module Module1
Sub Main()
End Sub
End Module
Hello 3orld!
$/,e the code belo: into the :indo: bet:een the Main() and End Sub statements.
Console.Write("Hello World")
Console.Read()
$his code :rites the tet HHello WorldI to the screen@ and the H+eadI kee,s the :indo:
o,en.
$o make /our ,ro&ram :ork@ first of all save /our :ork b/ ,ressin& the follo:in& icon
$hen debu& /our ,ro&ram b/ ,ressin& the ,la/ icon on the to, bar.
?ou have :ritten /our first com,uter ,ro&ram!
Similar to Console.Write there is Console.Write8ine :hich inserts a carria&e return. See
ho: that :orks3
<a&e 3
.ntroduction to <ro&rammin&
;sin& "isual Basic
E6ercises
1. Write a ,ro&ram that :ill out,ut t:o messa&es of /our choice on the screen@ on
se,arate lines.
1. Write a ,ro&ram that :ill out,ut this rocket on the screen:
*
***
*****
*******
*******
*******
*******
*******
*******
*******
*******
***
*****
<a&e !
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 2 ! %sin# Variables
Com,uter ,ro&rams normall/ use (,rocess) data in some :a/ to ,roduce results. $his
normall/ relies on an .5<;$ from the ,ro&ram or user@ :hich is <+2CESSED b/ the
,ro&ram then dis,la/ed in the console :indo:@ 2;$<;$.
$he in,ut to the ,ro&ram is often su,,lied b/ the user :hilst the ,ro&ram is runnin&.
Variables
.n a com,uter ,ro&ram@ variables can be ima&ined as labelled boes that store data for
use in the ,ro&ram. ?ou tell the com,uter :hat :ill be stored in the variable :hen /ou
JdeclareK it.
;sin& the eam,le of a ,ro&ram that adds t:o numbers to&ether and dis,la/s the sum: 3
variables are re=uired as belo::
;umber1 ;umber2 Sum
?ou can ima&ine the variables as boes like this@ but in realit/ the/ are locations in the
com,uterKs main memor/.
$he JBo labelsK are kno:n as identifiers. %s a ,ro&rammer /ou must choose an
a,,ro,riate identifier for each variable /ou use in /our ,ro&ram. % valid identifier must
start :ith a letter and can consist of an/ combination of letters@ numerals and the
underscore character (L)@ but not s,aces.
7or ease of understandin& b/ other ,ro&rammers@ (/our teacher!) or /ourself later on@ /ou
should choose an identifier that e,lains the ,ur,ose of /our variable. $his is &ood
,ractice and ver/ useful :hen /our ,ro&rams &et more com,licated. E.&.
NumberOfEntries rather than n5 or number.
5B: "isual Basic is not case9sensitive@ so that 5umber@ number@ n;EBE+@ 5;EBE+ are
all e=uivalent.
"isual re=uires /ou to declare :hat t/,e of data /ou are &oin& to store in /our chosen
variables. $herefore if :e :ant to store :hole numbers :e need to declare them as
<a&e #
.5<;$ <+2CESS 2;$<;$
.ntroduction to <ro&rammin&
;sin& "isual Basic
inte&ers at the be&innin& of our ,ro&ram code. "B doesnKt re=uire /ou to declare at the
be&innin& of a module@ ,ro&ram or function B but it is &ood ,ractice to do so.
Module Module1
Sub Main()
Dim Number1, Number2, sum As nte!er
End Sub
End Module
5ote the use of the ke/:ord D.E at the be&innin&. $hen it is the variable names follo:ed
b/ %S then the t/,e itself.
5he -ssi#nment Statement
$o store somethin& in a variable /ou need to use an assi&nment statement. 7or eam,le:
Number1 = ;
$his stores the value 4 to the variable 5umber 1.
$he JMK is the assi&nment o,eratorA the value to the ri&ht is :hat is stored in the variable
that is identified on the left of the assi&nment o,erator. .t can be read as Hbecomes e=ual
toI or Htakes the valueI.
%n assi&nment statement can also contain an e,ression on the ri&ht side of the JMK@ :hich
:ill be calculated :hen that statement is eecuted.
Number1 " #
Number2 " 1$
sum " Number1 % Number2
$he above statements :ill result in ,uttin& the value 13 into the variable Sum.
<a&e '
.ntroduction to <ro&rammin&
;sin& "isual Basic
5he Console.3riteline*+ Statement
.f /ou :ant to dis,la/ the contents of a variable@ /ou need to use the Console.Writeline
statement and ,rovide the variable identifier in brackets:
Console.Write&ine(Number1)
5ote the difference bet:een dis,la/in& the contents of 5umber1 and dis,la/in& the tet
strin& J5umber1K.
Console.Write&ine("Number1")
?ou can combine several variable identifiers and0or messa&es in one statement. 7or
eam,le:
Console.Write&ine(Number1 ' " % " ' Number2 ' " " " ' sum)
5ote that s,aces also need to be added inside the =uotes.
5he Console.1eadline Statement
.f /ou :ant the user to be able to t/,e in values that are used in the ,ro&ram is runnin&@
/ou need to use the Console.+eadline statement. $o store the value t/,ed b/ the user in
a variable use the Console.+eadline statement :ith the variable identifier before the call:
Number1 " Console.Read&ine()
$o dis,la/ the sum of t:o numbers that the user t/,es in@ :e can :rite:
Module Module1
Sub Main()
Dim Number1, Number2, sum As nte!er
Number1 " Console.Read&ine
Number2 " Console.Read&ine
sum " Number1 % Number2
Console.Write&ine(sum)
Console.Read()
End Sub
End Module
<a&e *
.ntroduction to <ro&rammin&
;sin& "isual Basic
Save the file and run the ,ro&ram. $his :ill ,roduce the re=uired result. Ho:ever@ it is not
ver/ user9friendl/: :e need to ,rom,t the user for :hat to do. %dd some lines to /our
,ro&ram as follo:s:
Module Module1
Sub Main()
Dim Number1, Number2, sum As nte!er
Console.Write("(lease enter in a number) ")
Number1 " Console.Read&ine
Console.Write("(lease enter in anot*er number) ")
Number2 " Console.Read&ine
sum " Number1 % Number2
Console.Write&ine(Number1 ' " % " ' Number2 ' " " " ' sum)
Console.Read()
End Sub
End Module
$his :ill ,roduce the follo:in& out,ut:
;B7
Writeline :ithout the brackets (,arameters) :ill Cust out,ut a ne: line.
Write rather than Writeline :ill sta/ on the same line.
$he statement
Console.Write&ine(Number1 ' " % " ' Number2 ' " " " ' sum)
<roduces the same result as
<a&e 4
.ntroduction to <ro&rammin&
;sin& "isual Basic
Console.Write(Number1)
Console.Write(" % ")
Console.Write(Number2)
Console.Write(" " ")
Console.Write(sum)
%lthou&h the +ead statement eists@ its use is ver/ s,ecific as it leaves the Enter character
in the in,ut buffer. .f /ou tr/ it@ /our ,ro&ram ma/ not o,erate as /ou e,ect.
<a&e 6
.ntroduction to <ro&rammin&
;sin& "isual Basic
-rithmetic E6ressions
We can :rite more com,licated arithmetic e,ressions@ usin& the follo:in& s/mbols:
%rithmetic
2,erator
2,eration 2,erand data
t/,es
+esult data t/,e Eam,le
N %ddition .nte&er@ real .nte&er@ real O N ?
9 Subtraction .nte&er@ real .nte&er@ real +esult B 1
P Eulti,lication .nte&er@ real .nte&er@ real < P .nterest+ate
0 +eal Division .nte&er@ real +eal O 0 1
D." .nte&er division .nte&er .nte&er $otal D." ;nitSiQe
E2D +emainder .nte&er .nte&er ? E2D '
;B7
Division usin& 0 :ill ,roduce a result that ma/ not be a :hole number. We need to declare
a variable receivin& such a result as a +eal data t/,e@ so that it ma/ have a decimal ,oint
and a fractional ,art. 7or more data t/,es@ see the net cha,ter.
Comments
7or all of the ,ro&rams from no: on:ards /ou are e,ected to ,seudo9code /our :ork.
$his means :ritin& :hat the code :ill do in J,lain En&lishK rather than :ritin& in <ascal
code strai&ht a:a/.
<seudo9code0comments also hel, other ,eo,le understand the ,ro&ram@ and allo: /ou to
add useful notes to aid develo,ment of the code and ,rovide basic documentation. $he
com,iler i&nores these@ so /our a,,lication :ill not take u, more s,ace because of
comments.
$he structure for comments is as follo:s B 5ote the a,ostro,he at the be&innin&.
+t*is is a ,omment t*at !oes on -or one line.
E6ercises
1. Write a ,ro&ram that :ill read in three inte&ers and dis,la/ the sum.
1. Write a ,ro&ram that :ill read t:o inte&ers and dis,la/ the ,roduct.
3. Enter the len&th@ :idth and de,th of a rectan&ular s:immin& ,ool. Calculate the
volume of :ater re=uired to fill the ,ool and dis,la/ this volume
<a&e 1-
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater $ ! Data t'es
%ll variables have to be declared before the/ can be used. $he com,iler :ill allocate
memor/ to each variable de,endin& on :hat t/,e it is. "isual Basic ,rovides man/ built9in
t/,es@ some of :hich are listed belo:. ?ou can also define /our o:n data t/,es@ /ou :ill
learn about this later.
Variable Declarations 8 <lobal
Global variables are variables declared at the be&innin& of the ,ro&ram and accessible
from an/:here in the ,ro&ram. .t is not al:a/s desirable to use a &lobal variable as its
values ma/ &et chan&ed accidentall/ if /ou have multi,le functions in /our ,ro&ram
:ocal 9ariables
+ather than declarin& variables &loball/@ it is &ood ,ro&rammin& st/le to declare variables
locall/ :ithin the block :here the variable is &oin& to be used
When /ou start :ritin& ,ro&rams :ith routines B ,rocedures or functions B /ou should
declare local variables :ithin the routines. %n/ variable value that is re=uired b/ another
routine should be ,assed as a ,arameter. % routine or subroutine is a sub,ro&ram.
Belo: are some data t/,e declarations.
Inte#er
$his data t/,e su,,orts ositi9e and ne#ati9e 4hole numbers. Eemor/ allocated !
b/tes. +an&e: 911!*!43'!4 to 11!*!43'!*. Whenever ,ossible /ou should use .nte&er
variables rather than +eal variables@ because the/ use less memor/ and the store values
more accuratel/.
B'te
$his data t/,e su,,orts unsi#ned inte#ers in the ran#e 2 to 2&&. Eemor/ allocated: 1
b/te
Decimal
$his data t/,e su,,orts si#ned numbers 4ith a decimal oint and fractional ,art.
Eemor/ allocated: 1' B/tes. $his is a &ood t/,e to use for currenc/.
Sin#le=Double
$his data t/,e su,,orts floatin& ,oint numbers. $his is similar to decimal but allo:s
stora&e of lar&er fractions.
Char
$his is a sin&le character. Eemor/ allocated: 1 b/te. ?ou can assi&n a sin&le character to
a Char variable:
<a&e 11
.ntroduction to <ro&rammin&
;sin& "isual Basic
!etter1 = "#$;
Strin#
- strin# is a se>uence of characters. % strin& variable can store u, to 1
31
characters.
Ho:ever a strin& constant is limited to 1## characters (more on this later).
"%e&&o 'or&d$
"(1) *+,-./$
Eam,les of strin& literals
"%e said
"$he&&o$
.f /ou :ant to include the =uotes in a strin& literal /ou need
to t/,e t:o =uotes
" "
$his strin& literal contains a s,ace
"$
$his strin& is kno:n as a null strin&
?ou can assi&n a strin& literal to a strin& variable:
0irstName = "Thomas$
?ou can concatenate strin&s (Coin one strin& to the end of another) usin& the strin&
o,erator N
Message = "%e&&o " 1 "'or&d$ 2note the space left after hello
0u&&Name = 0irstName 1 Surname
Boolean
$his data t/,e su,,orts Cust t:o values: $rue and 7alse. 7or eam,le:
0ound = 0a&se
0inished = True
Eemor/ allocated: 1 b/te. "isual Basic re,resents $rue as 1 and 7alse as - in memor/.
Boolean o,erators are mainl/ used for selection and iteration in a ,ro&rammin& contet
(/ou :ill learn more about these in the net 1 cha,ters).
$he follo:in& Boolean o,erators can be used in e,ressions :ith Boolean variables:
Boolean
2,erator
8o&ical
o,eration
E,lanation Eam,le assumin&
7ound M $rue
7inished M 7alse
"alue of
eam,le
Not
.nversion $urns $rue to
7alse and vice
Not 0inished True
<a&e 11
.ntroduction to <ro&rammin&
;sin& "isual Basic
versa
And
%5D Both values
must be true for
the result to be
true
0ound and
finished
0a&se
Or
.nclusive 2+ Either or both
values must be
true for the result
to be true
0ound or not
0inished
True
Xor
Eclusive 2+ 2nl/ one value
must be true for
the result to be
true
0ound xor
not 0inished
0a&se
$he results of a Boolean e,ression can be assi&ned to a Boolean variable. 7or eam,le:
Searching = not 0ound or not 0inished
3i4e5p = not 0ound and 0inished
Date
$his data t/,e su,,orts dates. "isual Basic stores the date as a real number. $he inte&ral
,art of the value is the number of da/s that have ,assed since -10-10---1. $he fractional
,art of the value is the fraction of a (1!9hour) da/ that has ela,sed.
?ou can ,erform calculations :ith date variables. .f J$oda/K has toda/Ks Date$ime value
stored:
Dim .oda/, .omorro0, 1esterda/ As Date
.oda/ " No0()
.omorro0 " .oda/.AddDa/s(1)
Console.Write&ine(.oda/)
Console.Write&ine(.omorro0)
<a&e 13
.ntroduction to <ro&rammin&
;sin& "isual Basic
?rdinal data t'es
2rdinal t/,es include integer, byte, character and Boolean. %n ordinal t/,e defines an
ordered set of values. $hese t/,es are im,ortant in later cha,ters.
Simle t'es
Sim,le t/,es include ordinal types, double and Decimal. 8ater on /ou :ill lean about t/,es
that are not sim,le t/,es@ kno:n as structured t/,es. %n eam,le of a structured t/,e is
the String data t/,e.
Constants
.f /ou :ant to use values that :ill not chan&e throu&hout the ,ro&ram@ :e can declare
them as constants rather than variables at the be&innin& of the ,ro&ram in the const
section@ :here /ou also initialise them.
Module Module1
Const 2atRate " 3.14$
Sub Main()
Dim ,ost, ta5 As De,imal
Console.Write&ine("Enter t*e ,ost o- !oods) ")
,ost " Console.Read&ine
ta5 " ,ost 6 2atRate
Console.Write&ine(".*e 2A. is " ' ta5..oStrin!("N2"))
Console.Read()
End Sub
End Module
-d9anta#es of usin# named constants
3+ather than variables:
$he value of a constant cannot be accidentall/ chan&ed durin& the runnin& of the
,ro&ram.
$he ,ro&ram runs faster because all references to the constant are re,laced b/ its
value at com,ile time@ :hereas a variableKs value has to be retrieved from main
memor/ at run time.
3+ather than the actual value:
.f the value needs to be chan&ed at a later date@ such as the "%$ rate chan&es@ onl/
the constant declaration needs to be chan&ed.
<a&e 1!
Constants are declared
before variables.
+ounds to 1 decimal ,laces B
indicated b/ H51I
.ntroduction to <ro&rammin&
;sin& "isual Basic
E,ressions usin& the value are much easier to understand if a carefull/ chosen
identifier re,resents the value.
E6ercises
1. Write a ,ro&ram that :ill ask the user for their first name. $he ,ro&ram should then
concatenate the name :ith a messa&e@ such as JHello 7red. Ho: are /ouRK and
out,ut this strin& to the user
1. Write a ,ro&ram that asks the user to enter t:o real numbers and dis,la/s the
,roduct of these t:o numbers to 1 decimal ,laces@ :ith user9friendl/ messa&es.
3. Write a ,ro&ram to enter a tem,erature in de&rees 7ahrenheit and dis,la/ the
e=uivalent tem,erature in de&rees Centi&rade.
S$he formula for conversion is Centi&rade M (7ahrenheit B 31) P (#06)T
!. Write a ,ro&ram to convert a ,ersonKs hei&ht in inches into centimetres and their
:ei&ht in stones into kilo&rams. S1 inch M 1.#! cm and 1 stone M '.3'! k&T
<a&e 1#
.ntroduction to <ro&rammin&
;sin& "isual Basic
E6tension e6ercises
#. Write a ,ro&ram to enter the len&th@ :idth and de,ths at the dee,est and shallo:est
ends of a rectan&ular s:immin& ,ool. Calculate the volume of :ater re=uired to fill
the ,ool@ and dis,la/ this volume.
'. Write a ,ro&ram to enter the len&th and :idth of a rectan&ular9sha,ed &arden.
Calculate the area of the &arden and the cost of turfin& a la:n if a 1m border is
around the ,erimeter of the &arden. %ssume the cost of turf is U1- ,er s=uare
metre. Dis,la/ the result of these calculations.
<a&e 1'
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater ( ! Selection
When /ou are :ritin& ,ro&rams@ /ou :ill often :ant a com,uter to take different routes
throu&h the ,ro&ram de,endin& on various conditions. 7or this /ou can use one of the
follo:in& structured statements "isual Basic ,rovides:
If ... then
If ... then ... else
Select case
(structured statements are built from other statements@ the/ are normall/ made :hen /ou
:ant to eecute other statements se=uentiall/@ conditionall/@ or re,eatedl/.)
If @ 5hen
When /ou :ant a ,ro&ram to eecute a statement onl/ if a certain condition is met@ /ou
use:
If 6oo&eanE7pression then statement
% Boolean e6ression returns a Boolean value 5rue or .alse (See last cha,ter for
Boolean data t/,e). .f the BooleanExpression is true the statement after then is eecuted.
Eam,les of Boolean e,ressions:
#ge 8 1
(Number 8 1() and (Number 9=)5)
?ou can use the follo:in& com,arison o,erators:
= e:ua& to
98 not e:ua& to
8 greater than
9 &ess than
8= greater than or e:ua& to
9= &ess than or e:ua& to
<a&e 1*
.ntroduction to <ro&rammin&
;sin& "isual Basic
Eam,le of an if @ then statement:
Dim number, sum As nte!er
number " 1
- number 7 3 .*en
sum " sum % number
End -
E6ercise
1. Write a ,ro&ram that asks for t:o numbers from the user and then dis,la/s a
suitable messa&e if the t:o numbers are the same.
If @ 5hen @ Else
When /ou :ant /our ,ro&ram to do one statement if a certain condition is met@ and
another statement if the condition is not met@ /ou need to use:
If 6oo&eanE7pression Then statement1 else statement)
Eam,le of an if @ then @ else statement:
- number 8 3 .*en
Console.Write&ine(".*is is a ne!ati9e number")
Else
Console.Write&ine(".*is is a :ositi9e number")
End -
E6ercises
1. Write a ,ro&ram that :ill read in a ,ersonKs a&e and dis,la/ a messa&e :hether
the/ are old enou&h to drive or not.
3. Write a ,ro&ram that checks :hether a number in,ut is :ithin the ran&e 11 to 16@
inclusive@ and dis,la/s an a,,ro,riate messa&e.
!. Write a ,ro&ram that asks the user to enter 1 numbers and dis,la/s the lar&er of the
t:o numbers.
<a&e 14
.ntroduction to <ro&rammin&
;sin& "isual Basic
;ested If statements
$he statement in a then and0or else ,art of an if statement can itself be an if statement.
Eam,le:
- (letter 7" "A" And letter 8" ";") <r (letter 7" "a" And letter 8" "=") .*en
Console.Write&ine("&etter")
Else
- (letter 7" "3" And letter 8" ">") .*en
Console.Write&ine("numeral")
Else
Console.Write&ine("s:e,ial ,*ara,ter")
End -
End -
E6ercises
#. Etend ,ro&ram J3K so a number out of ran&e :ill cause a messa&e sa/in& :hether
it is above or belo: the ran&e.
'. %da,t ,ro&ram J!K to determine :hich is the lar&est of three &iven inte&ers.
Indentation
With the introduction of structured statements@ /ou need to take care over the la/out of
/our code@ to kee, it eas/ to find ,ossible errors. "isual Basic does not mind :here /ou
,ut :hite s,ace (s,aces@ indents@ ne: lines). Ho:ever@ to follo: the code@ es,eciall/
durin& error9findin& sessions /ou :ill a,,reciate clearl/ laid out code. %lso@ to &et full
marks from /our teacher@ /ou are e,ected to la/ /our code out usin& the follo:in&
convention:
Ever/ statement on a ne: line.
%n I. al:a/s must be matched b/ an End If.
Because of the nature of the "isual E,ress .DE ho:ever it automaticall/ indents code for
/ou B but even if it doesnKt make sure /ou are indentin& /our :ork after each .7 statement.
<a&e 16
.ntroduction to <ro&rammin&
;sin& "isual Basic
S,lit if statements and indent in this :a/:
If 6oo&eanE7pression
Then statement1
Else statement)
End If
Select Case
5ested if statements can &et ver/ com,licated and sometimes it is easier to use a case
statement:
Select Case Ordina&E7pression
;ase 9item or &ist8
Statement1
<<<
;ase 9itemn or &istn8
Statementn
;ase e&se
Statement
End Se&ect
$he value of the ordinal e,ression (see Cha,ter 3@ 2rdinal $/,e) :ill determine :hich
statement is eecuted. Each Case must be a constant@ a list of constants or a subran&e.
Each value in the case must be uni=ue in the case statement@ and subran&es and lists
must not overla,. See eam,les belo:.
.f Month is an inte&er variable:
Sele,t Case mont*
Case 1, ?, $, 4, #, 13, 12
No<-Da/s " ?1
Case @, A, >, 11
No<-Da/s " ?3
Case 2
No<-Da/s " 2#
Case Else
Console.Write&ine("Not a mont*")
End Sele,t
.f Ch is of t/,e Char:
<a&e 1-
5ote that there must be
no semicolon here. $his
is a common s/nta error.
.ntroduction to <ro&rammin&
;sin& "isual Basic
Sele,t Case letter
Case "A" .o ";", "a" .o "="
Console.Write&ine("&etter")
Case "3" .o ">"
Console.Write&ine("Number")
Case Else
Console.Write&ine("S:e,ial C*ara,ter")
End Sele,t
E6ercises
*. Write a ,ro&ram that asks the user for a month number and dis,la/s the number of
da/s that month has (i&nore lea, /ears for no:).
4. Write a ,ro&ram that lets the user enter a number bet:een 1 and 11 and dis,la/s
the month name for that month number. $he in,ut 3 :ould therefore dis,la/ Earch.
6. Write a ,ro&ram that reads in the tem,erature of :ater in a container (in
Centi&rade) and dis,la/s a messa&e statin& :hether :ater is froQen@ boilin& or
neither.
1-. Write a ,ro&ram that asks the user for the number of hours :orked this :eek and
their hourl/ rate of ,a/. $he ,ro&ram is to calculate the &ross ,a/. .f the number of
hours :orked is &reater than !-@ the etra hours are ,aid at 1.# times the rate. $he
,ro&ram should dis,la/ an error messa&e if the number of hours :orked is not in
the ran&e - to '-.
11. Write a ,ro&ram that reads in an eam mark and dis,la/s the relevant &rade. $he
&rade boundaries are:
- to !- marks &rade ;
!1 to #- marks &rade E
#1 to '- marks &rade D
'1 to *- marks &rade C
*1 to 4- marks &rade B
41 to 1-- marks &rade %
11. Etend /our ,ro&ram for Eercise * to include lea, /ears. % /ear is a lea, /ear if
the /ear divides eactl/ b/ !@ but a centur/ is not a lea, /ear unless it is divisible b/
!--. 7or eam,le the /ear 166' :as a lea, /ear@ the /ear 16-- :as not@ the /ear
1--- :as a lea, /ear. (ti,: use the o,erators 0 and E2D)
<a&e 11
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater & ! Iteration *reetition+
We often :ant com,uters to re,eat some ,rocess several times. $his is called iteration.
.n "isual Basic there are 3 different structures to re,eat a set of statements:
Definite Iteration (:hen /ou kno: before enterin& the loo, ho: often /ou :ant to re,eat)
.or loo,
Indefinite Iteration ( :hen /ou do not kno: beforehand ho: often /ou :ant to re,eat)
Do %ntil loo,
Do 3hile loo,
.or loo
For ;ounter = Start=a&ue to End=a&ue step StepAmount
Statement;
Next ;ounter
Counter is called the control 9ariable and must be declared as an ordinal t/,e@ often
inte&er (see cha,ter 3).
Start"alue V End"alue must be e,ressions of the same t/,e as Counter.
Eam,les:
Bor i " Counter .o 13 Ste: 1
Console.Write&ine(".*is is a line")
Ne5t Counter
Bor Counter " 13 .o 1 Ste: C1
Console.Write&ine(Counter)
Ne5t Counter
E6ercises
1. Eake each of the t:o eam,les above ,a&e into a ,ro&ram to test :hat it does.
(donKt for&et to ,ut a JConsole.+eadline()K at the end of each one)
1. Write a ,ro&ram that dis,la/s the :ord JHelloK on the screen ! times on the same
line usin& the for loo,.
3. Write a ,ro&ram that ,rom,ts the user to enter a short messa&e and the number of
times it is to be dis,la/ed and then dis,la/s the messa&e the re=uired number of
times.
<a&e 11
.ntroduction to <ro&rammin&
;sin& "isual Basic
!. Write a ,ro&ram to dis,la/ the s=uares of all the inte&ers from 1 to 11 in t:o
columns headed J5umberK and JS=uare of 5umberK.
#. Write a ,ro&ram that asks the user to enter the number of stars ,er ro: and the
number or ro:s to be dis,la/ed. 7or eam,le@ enterin& # and 3 should dis,la/:
*****
*****
*****
'. Write a ,ro&ram that asks for a number@ and dis,la/s the s=uares of all the inte&ers
bet:een 1 and this number inclusive.
*. %da,t /our ,ro&ram from eercise ' so that it :ill dis,la/ # values on each line.
(ti,: ;se Write to dis,la/ a value and a statement of the form
>f ;ontro&=ariab&e MO? 5 = ( then ;onso&e<'rite!ine()
$o out,ut a ne: line after ever/ fifth value
4. Write a ,ro&ram that asks the user to enter ho: man/ numbers are to be avera&ed@
then enters this number of numbers@ calculatin& the avera&e. $he ,ro&ram should
dis,la/ the avera&e on the screen.
6. Write a ,ro&ram to dis,la/ an Jn times tableK for a &iven inte&er n. 7or n M !@ the
out,ut should be:
1 * + = +
) * + =
* * + = 1)
<<<<
1) * + = +
<a&e 13
.ntroduction to <ro&rammin&
;sin& "isual Basic
Do :oo
Do Until 6oo&eanE7pression
Statement1;
Statement);
@
@
Loop;
$he statements enclosed b/ reeat and until are eecuted a&ain and a&ain until the
BooleanE,ression is 5rue.
;ote: $he statement se=uence is eecuted at least once@ even if BooleanE,ression is
alread/ 5rue.
Eam,le:
Do Dntil name " "EEE"
Console.Write("Enter a name C EEE to Fnis*) ")
name " Console.Read&ine()
&oo:
?ou ma/ :ish to kno: ho: man/ times the loo, :as re,eated:
Do Dntil number " 3
Console.Write("Enter a number C 3 to Fnis*) ")
number " Console.Read&ine()
,ount " ,ount % 1
&oo:
.f :e :ant to add u, all the numbers the user t/,es in@ :e need to kee, a runnin& total:
,ount " 3 +MaGe sure /ou initialise 9ariables be-ore usin! t*em
Runnin!total " 3
Do Dntil number " 3
Console.Write("Enter a number C 3 to Fnis*) ")
number " Console.Read&ine()
,ount " ,ount % 1
Runnin!total " Runnin!total % number
&oo:
?ou can also chan&e the format of the above sli&htl/ to have the control condition bein&
checked at the end of the loo, B for eam,le
<a&e 1!
.ntroduction to <ro&rammin&
;sin& "isual Basic
Do
Console.Write("Enter a number C 3 to Fnis*) ")
number " Console.Read&ine()
,ount " ,ount % 1
Runnin!total " Runnin!total % number
&oo: Dntil number " 3
$he difference here is that ,uttin& the check at the end of the statement means that the
loo, :ill eecute at least once.
Do 3hile
$he Do While loo, is eactl/ the same as the Do ;ntil loo, ece,t that the former checks
that a condition is ,ositive to continue loo,in& B :hile the latter checks that a condition is
ne&ative to continue loo,in&
E6ercises
1-. Write a ,ro&ram that reads in a series of numbers and adds them u, until the user
enters Qero. ($his sto,,in& value is often called a ro#ue 9alue.)
11. Write a ,ro&ram that asks the user for a number bet:een 1- and 1- inclusive and
:ill validate@ that is test@ the in,ut. .t should re,eatedl/ ask the user for this number
until the in,ut is :ithin the valid ran&e.
11. E,and /our ,ro&ram from Eercise 11 to dis,la/ the avera&e as :ell as the sum of
the number entered. Eake sure /ou do not count the ro&ue value as an entr/.
13. Write a ,ro&ram that dis,la/s a conversion table for ,ounds to kilo&rams@ ran&in&
from 1 ,ound to 1- ,ounds S1 k& M 1.1 ,oundsT.
1!. Write a ,ro&ram that asks the user to enter 4 inte&ers and dis,la/s the lar&est
inte&er.
1#. %da,t the last ,ro&ram so that it :ill also dis,la/ the smallest inte&er.
<a&e 1#
7red
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater , ! -rra's
Hi&h9level lan&ua&es ,rovide ,ro&rammers :ith a variet/ of :a/s of or&anisin& data.
$here are not onl/ sim,le data t/,es@ but also data structures.
% data structure is a data t/,e com,osed of a number of elements of one or more data
t/,es. % data structure allo:s a variable to be declared of that t/,e so that a number of
data items can be stored and ,rocessed as a sin&le set.
%n arra/ is an ordered set of data items of the same t/,e &rou,ed to&ether usin& a sin&le
identifier. %rra/s ma/ have man/ dimensions but hi&her dimensions can &et difficult to
ima&ine and are not needed for %S or %9level. .t is sufficient to be able to use one9
dimensional arra/s (also kno:n as linear lists) and t:o9dimensional arra/s (also kno:n as
tables).
$he arra/Ks identifier and an inde (or subscri,t) for each of the arra/Ks dimensions are
used to refer to each of the arra/Ks data items.
Without data structures@ if :e :ant to store several values in se,arate variables and
,rocess them in a similar manner@ this could result in ver/ re,etitive code. 7or eam,le@ to
store # studentKs names :ould mean declarin& # strin& variables for their names:
Dim Name1A Name)A Name*A Name+A Name5 #s String;
5ame1 5ame1 5ame3 5ame!
5ame#
$his is still mana&eable but :hat if :e needed to store several hundred studentsK namesR
<a&e 1'
Wack %nna Sue +o/
.ntroduction to <ro&rammin&
;sin& "isual Basic
?ne8Dimensional -rra's
.f :e declare an arra/:
Dim Name(3 .o @) As Strin!
5ame(-) .red
5ame(1) Aack
5ame(1) -nna
5ame(3) Sue
5ame(!) 1o'
We can refer to a ,articular element of this arra/:
Console.Write&ine(Name(2))
Would dis,la/ the name %nna. .n &eneral@ to refer to the i
th
element /ou :rite 5ame(i)
$his is ,articularl/ ,o:erful :hen combined :ith iteration statements:
$o read in five names into the arra/ :e can :rite:
Bor i " 3 .o @ Ste: 1
Console.Write("(lease Enter in a lo,ation " ' i ' ") ")
&o,ation(i) " Console.Read&ine()
Ne5t
We can easil/ dis,la/ these in reverse order:
Bor i " @ .o 3 Ste: C1
Console.Write&ine(&o,ation(i))
Ne5t
.n &eneral@ :e declare a one9dimensional arra/ usin& the format:
Dim identifier (range) #s of ?ataTBpe
+an&e must be of ordinal t/,e (see cha,ter 3).
E6ercises
1. Write a ,ro&ram that reads ' names into an arra/. $he ,ro&ram must dis,la/ the
names in the same order that the/ :ere entered and then in reverse order.
1. We :ant to simulate thro:in& a die 3- times and record the scores. .f :e did this
Jmanuall/K :e :ould end u, :ith a tall/ chart:
5umber of 1Ks ....
5umber of 1Ks ...
<a&e 1*
%rra/
identifier
+an&e of
inde
%ll elements of
an arra/ are of
the same t/,e
%rra/
identifier
.nde or
subscri,t
.ntroduction to <ro&rammin&
;sin& "isual Basic
5umber of 3Ks .... ...
5umber of !Ks .... .
5umber of #Ks .... ..
5umber of 'Ks ..
.f :e use a com,uter to kee, a count of ho: man/ times each number :as thro:n@
:e could use an inte&er arra/ (inde ran&e 1..') instead of the tall/ chart. .n
&eneral@ a die thro: :ill &ive a score i@ and :e :ant to increment the count in the i
th

element.
Ta&&B;hart(i) = Ta&&Bchart(i) 1 1
Write a ,ro&ram to simulate the thro:in& of a die 3- times. $he results of the
simulation should be ,rinted as a table of scores (1 to ') and fre=uencies.
3. We :ish to select si random numbers bet:een 1 and !6 :ith the condition that all
the numbers are different. 2ne ,ossible strate&/@ or al&orithm@ is:
Initialise an array by using a for loop to store the values to !"
#epeatedly select a random element from array until a non$%ero value is
selected
Display this value
Set that element to %ero
#epeat the above three steps until six number have been selected
Write a ,ro&ram to select si uni=ue random numbers bet:een 1 and !6.
!. We can declare t:o arra/s@ Student and DoB@ to store the name of Students and
their dates of birth. 7or eam,le if 7red is born on 1101104!@ then :e could store
J7redK in StudentS1T and J1101104!K in DoBS1T. $o find a ,articular student :e can use
a re,eat loo,
Write a ,ro&ram that stores # studentsK names and dates of birth and then searches
for a ,articular student and dis,la/s that studentKs date of birth and current a&e.
Dis,la/ a suitable messa&e if the studentKs details cannot be found.
(5i: use the built9in functions ?earS,an and Date)
54o8Dimensional -rra's
Su,,ose :e :ant to store a studentKs timetable:
<a&e 14
.ntroduction to <ro&rammin&
;sin& "isual Basic
Eonda/ $uesda/ Wednesda/ $hursda/ 7rida/
8esson 1 Eaths <h/sics Com,utin& Electronics Eaths
8esson 1 <h/sics <h/sics Electronics Eaths <h/sics
8esson 3 8unch 8unch 8unch 8unch 8unch
8esson ! Com,utin& Electronics Eaths Com,utin& Com,utin&
We can declare a t:o9dimensional arra/:
Dim timtable(3 .o ?, 3 .o @) As Strin!
$he dimensions of an arra/ are neutral. $he/ do not re,resent an/thin& until :e decide
:hat each dimension :ill re,resent@ declarin& an a,,ro,riate ran&e in the corres,ondin&
inde. $o refer to the !
th
lesson on a $uesda/@ :e could therefore :rite:
Timetab&e(+A))
$o dis,la/ all lessons for a Wednesda/ (the 3
rd
da/ of the :eek):
da/ " 2
Bor lesson " 3 .o ? Ste: 1
Console.Write&ine(timetable(lesson, da/))
Ne5t lesson
$o dis,la/ the :hole timetable:
Bor lesson " 3 .o ? Ste: 1
Bor da/ " 3 .o @ Ste: 1
Console.Write&ine(timetable(lesson, da/))
Ne5t
Ne5t
E6ercises
#. ;sin& a t:o9dimensional arra/@ :rite a ,ro&ram that stores the names of ten
countries in column 1 and their ca,itals in column 1. $he ,ro&ram should then ,ick
a random countr/ and ask the user for the ca,ital. Dis,la/ an a,,ro,riate messa&e
to the user to sho: :hether the/ are ri&ht or :ron&.
'. E,and the ,ro&ram above to ask the user # =uestions and &ive a score of ho:
man/ the/ &ot ri&ht out of #.
Enumerated 5'es
%n enumerated t/,e defines an ordered set of values. Each value is &iven an ordinal
value@ startin& at Qero. Eembers of an enumerated t/,e can be used as loo, control
variables@ in case statements and as arra/ subscri,ts.
Module Module1
<a&e 16
.ntroduction to <ro&rammin&
;sin& "isual Basic
Dim 5, / As nte!er
Enum Da/s
Sun
Mon
.ue
Wed
.*u
Bri
Sat
End Enum
Sub Main()
5 " Da/s.Wed
/ " Da/s.Sun
Console.Write&ine("Wednesda/ " H3I", 5)
Console.Write&ine("Sunda/ " H3I", /)
Console.Read&ine()
End Sub
End Module
Sets
% set is a collection of values of the same ordinal t/,e. $he values of a set have no
associated order
Module Module1
Sub Main()
Dim Set1, Set2, Set? As Ne0 Arra/&ist
Dim nitialSet() " H?, @, $I
Set1.AddRan!e(nitialSet)
Set1.Add(2)
Set1.Add(4)
- Set1.Contains(4) .*en
Console.Write&ine("Set ,ontains 4")
End -
Console.Read&ine()
End Sub
End Module
<a&e 3-
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater ) ! .unctions
Built8in .unctions
% function is a routine@ a self9contained statement block that returns a value :hen it
eecutes. <ascal ,rovides man/ read/9to9use functions. Here are Cust a fe::
7unction
identifier
<arameter(s)
(ar&uments)
+esult t/,e Descri,tion
Eath.+ound O: Decimal 0
double
.nte&er +eturns the value of O +ounded to the
nearest :hole number
Eath.$runcate O: Decimal 0
Double
.nte&er $runcates a real number to an inte&er
ChrW O: b/te Char +eturns the character for a s,ecified %SC..
code value O
%sc O: an/
ordinal t/,e
.nte&er +eturns the ordinal value of an ordinal t/,e
e,ression such as the %SC.. code for a
character
8en S: Strin& .nte&er +eturns the number of characters in strin&
S
.nStr S: Strin&
Sub: Strin&
.nte&er +eturns the inde value of the first
character in substrin& Sub that occurs in
the strin& S
;Case S: Strin& Strin& +eturns a co,/ of strin& S in u,,er case
8Case S: Strin& Strin& Converts strin& S to lo:er case
5o: 9 Date +eturns the current local date as a Date
value
CStr Date Strin& +eturns the strin& e=uivalent of D
CDate S: Strin&
e.&. 11010-3
Date .f S contains onl/ t:o numbers@ it is
inter,reted as a date in the current /ear.
8eft S: Strin&
8: .nte&er
Strin& +eturns the substrin& of len&th 8 that
a,,ears at the start of strin& S
+i&ht S: Strin&
8: .nte&er
Strin& +eturns the substrin& of len&th 8 that
a,,ears at the end of strin& S
$o use an/ of these functions /ou use its identifier and ,rovide the necessar/ ar&uments in
brackets. $his is called the function call. % function call returns a value@ :hich can be
used in e,ressions in assi&nments and com,arison o,erations.
<a&e 31
.ntroduction to <ro&rammin&
;sin& "isual Basic
7or eam,le@ to assi&n the s=uare root of a number to S=uare:
Eam,le
&ength = !en (astring)
?ou must make sure that /ou ,rovide the correct data t/,es.
7unction calls cannot a,,ear on the left side of an assi&nment statement.
E6ercises
1. Write a ,ro&ram that asks the user to t/,e in a number :ith decimal ,laces. $he
,ro&ram should then dis,la/ the rounded and the truncated number.
1. Write a ,ro&ram that reads in a strin& and dis,la/s the number of characters in the
strin&.
3. Write a ,ro&ram that dis,la/s the %SC.. code for an/ &iven character.
!. Write a ,ro&ram that :ill dis,la/ the character for a &iven %SC.. code.
#. Write a ,ro&ram that asks the user for their surname and dis,la/s the surname in
u,,ercase letters.
'. Write a ,ro&ram that dis,la/s toda/Ks date.
*. Write a ,ro&ram that reads in a date@ converts it into date format@ adds a da/ and
dis,la/s the net da/Ks date.
4. Write a ,ro&ram that asks the user for their first name and their surname. $he
,ro&ram then dis,la/s the full name@ first name ca,italised (startin& :ith a ca,ital
letter follo:ed b/ lo:er9case letters) and surname@ all u,,ercase@ re&ardless of
:hat case the user entered.
1andom ;umbers
We often :ant to simulate events :here random numbers occur@ such as thro:in& a die.
Com,uters can onl/ follo: ,ro&rams@ that means se=uences of ,redetermined statements@
so the/ cannot ,roduce trul/ random numbers. <ascal@ like most hi&h9level lan&ua&es@
,rovides us :ith a ,seudo9random number &enerator to &et over this ,roblem:
C = >nt(Cnd() * 1(() 1 1
+eturns an inte&er bet:een - and 1--
When /ou initialise the random number &enerator it uses an inte&er obtained from the
s/stem clock@ so /ou are hi&hl/ likel/ to obtain the same se=uence of numbers on an/ t:o
runs. $o ,revent this from ha,,enin& (the com,iler :ill use a different value each time)@
add the statement andomi!e"# before /ou :ant to use the random function:
<a&e 31
.ntroduction to <ro&rammin&
;sin& "isual Basic
Module Module1
Sub Main()
Dim number As nte!er
Randomi=e() +s*ould onl/ be e5e,uted on,e to initiate random
number !enerator
number " nt(Rnd() 6 A) +!enerates random number 3C$
number " number % 1 + add 1 to !et anumber 1CA
Console.Write&ine(number)
Console.Read&ine()
End Sub
End Module
E6ercises
6. Write a ,ro&ram that :ill dis,la/ random numbers bet:een 1 and ' until a si is
&enerated.
1-. Write a ,ro&ram that :ill dis,la/ si random numbers bet:een # and 1-.
11. Write a &ame in :hich the user &uesses :hat random number bet:een 1 and 1---
the com,uter has Jthou&ht ofK@ until he or she has found the correct number. $he
com,uter should tell the user :hether each &uess :as too hi&h@ too lo: or s,ot on.
<a&e 33
.ntroduction to <ro&rammin&
;sin& "isual Basic
%ser8defined functions
Dev9<ascal ma/ not ,rovide /ou :ith all the functions /ou ma/ :ish to use. ?ou can
declare /our o:n functions and then call them in e,ressions Cust like built9in functions.
$he/ are kno:n as user9defined@ but in this case the user is the ,ro&rammer usin& the
,ro&rammin& lan&ua&e@ not the end9user of the ,ro&ram.
Module Module1
Bun,tion nitial(J/2al s As Strin!) As Strin!
Dim ret As Strin!
ret " &e-t(s, 1)
ret " DCase(ret)
Return ret
End Bun,tion
Sub Main()
Dim name As Strin!
Console.Write("./:e in a name) ")
name " Console.Read&ine()
Console.Write&ine("nitial " " ' nitial(name))
Console.Read&ine()
End Sub
End Module
:ocal Variables
Sometimes /ou need variables to store values tem,oraril/. +ather than declarin&
variables that are available throu&hout the ,ro&ram (&lobal variables)@ it is &ood
,ro&rammin& st/le and less error9,rone to declare variables locall/. $he/ can onl/ be
used in the function in :hich the/ are declared and :e sa/ that the/ have local sco,e.
<a&e 3!
Declaration of the ,arameter S@ an
internal variable to receive the
value ,assed to the function
Data t/,e of return
value
.n "isual Basic
7unctions can be
declared an/:here
althou&h it is &ood
,ractice to declare them
before the main
,ro&ram.
.ntroduction to <ro&rammin&
;sin& "isual Basic
Module Module1
Dim number As nte!er
Bun,tion Ba,torial(J/2al N As nte!er) As nte!er
Dim ,ount, :rodu,t As nte!er
:rodu,t " 1
Bor ,ount " 1 .o N Ste: 1
:rodu,t " :rodu,t 6 ,ount
Ne5t ,ount
Return :rodu,t
End Bun,tion
Sub Main()
Console.Write("./:e in a number bet0een 1 and 13) ")
number " Console.Read&ine()
Console.Write&ine("return -rom -un,tion) " ' Ba,torial(number))
Console.Read&ine()
End Sub
End Module
E6ercise
11. Write a function to convert tem,eratures from 7ahrenheit to Celsius. $he function
should take one inte&er ,arameter (the tem,erature in 7ahrenheit) and return a real
result (the tem,erature in Celsius). $he formula for conversion is:
Centi&rade M ( 7ahrenheit B 31 ) P ( #06 )
<a&e 3#
Global "ariable
.t is &ood ,ractice
to declare local
variables after the
function headin&.
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater / ! Procedures
% routine is a self9contained statement block that can be called from different locations in a
,ro&ram. % function is a routine that returns a value in its name :hen it eecutes@ and so a
function call is used as ,art of an e,ression. % ,rocedure is a routine that does not return
a value in this :a/ and a ,rocedure call is treated like a statement. Dev9<ascal ,rovides
man/ built9in ,rocedures@ for eam,le +eadln and Writeln. Ho:ever@ :e can also :rite
our o:n ,rocedures.
% &ood ,rocedure declaration has the form
S$% DrocedureName(Darameter!ist)
!oca&?ec&arations;
Statements
End S$% {of procedure}
Durin& the develo,ment of a ,ro&rammed solution to a ,roblem :e ma/ :rite do:n an
al&orithm or ste,:ise strate&/. Each ste, can be used as a ,rocedure call@ and the
detailed ,rocessin& of the solution is ,erformed in the ,rocedure. $his makes the main
,ro&ram bod/ eas/ to understand as the ,rocedure calls reflect the al&orithm.
3orked E6amle7
Write a ,ro&ram :hich :ould dis,la/ a ,/ramid of JPK:
*
***
*****
*******
*********
***********
$he solution to this ,roblem can be broken do:n into the follo:in& ste,s:
>nitia&iEe number of spaces and stars
Cepeat
Output &eading spaces
Output &ine of stars
#dFust number of spaces and stars
5nti& number of stars is the number re:uired
<a&e 3'
.ntroduction to <ro&rammin&
;sin& "isual Basic
Module Module1
Dim Ma5No<-Stars, No<-Stars, No<-S:a,es As nte!er
Sub nitialiseNo<-S:a,esAndStars()
Console.Write("Ho0 man/ stars s*ould be at t*e baseK ")
Ma5No<-Stars " Console.Read&ine()
No<-S:a,es " Ma5No<-Stars L 2 +enou!* s:a,e to a,,omodate base
No<-Stars " 1 + .i: *as one star
End Sub
Sub <ut:ut&eadin!S:a,es()
Dim ,ount As nte!er
Bor ,ount " 1 .o No<-S:a,es Ste: 1
Console.Write(" ") + No ne0 line reMuired
Ne5t ,ount
End Sub
Sub <ut:ut&ine<-Stars()
Dim ,ount As nte!er
Bor ,ount " 1 .o No<-Stars Ste: 1
Console.Write("6")
Ne5t ,ount
Console.Write&ine() + Mo9e to ne5t line
End Sub
Sub AdNustNo<-S:a,esAndStars()
No<-S:a,es " No<-S:a,es C 1
No<-Stars " No<-Stars % 2
End Sub
+ Main :ro!ram starts *ere
Sub Main()
nitialiseNo<-S:a,esAndStars()
Do
<ut:ut&eadin!S:a,es()
<ut:ut&ine<-Stars()
<a&e 3*
.ntroduction to <ro&rammin&
;sin& "isual Basic
AdNustNo<-S:a,esAndStars()
&oo: Dntil No<-Stars 7 Ma5No<-Stars
Console.Read&ine()
End Sub
End Module
Parameters
$hose routines that do not rel/ on &lobal variables are self9contained and easil/ reused in
other ,ro&rams. $he/ also make it easier to find ,ro&rammin& errors (lo&ic errors) as
each routine can be tested se,aratel/ and :ill not interfere :ith other routines. "alues
re=uired b/ routines are best ,assed to the routine b/ means of ,arameters. +outines can
have an/ number of ,arameters@ but the order must be the same in the routine declaration
and the routine call.
$he :orked eam,le from overleaf could be :ritten:
Module Module1
Dim Ma5No<-Stars, No<-Stars, No<-S:a,es As nte!er
Sub nitialise(J/Re- S:a,es As nte!er, J/Re- Stars As nte!er,
J/Re- Ma5 As nte!er)
Console.Write("Ho0 man/ stars s*ould be at t*e baseK ")
Ma5 " Console.Read&ine()
S:a,es " Ma5No<-Stars L 2 +enou!* s:a,e to a,,omodate base
Stars " 1 + .i: *as one star
End Sub
Sub <ut:ut&eadin!S:a,es(J/2al S:a,es As nte!er)
Dim ,ount As nte!er
Bor ,ount " 1 .o S:a,es Ste: 1
Console.Write(" ") + No ne0 line reMuired
Ne5t ,ount
End Sub
Sub <ut:ut&ine<-Stars(J/2al Stars As nte!er)
Dim ,ount As nte!er
<a&e 34
.ntroduction to <ro&rammin&
;sin& "isual Basic
Bor ,ount " 1 .o Stars Ste: 1
Console.Write("6")
Ne5t ,ount
Console.Write&ine() + Mo9e to ne5t line
End Sub
Sub AdNust(J/Re- S:a,es As nte!er, J/Re- Stars As nte!er)
S:a,es " S:a,es C 1
Stars " Stars % 2
End Sub
+ Main :ro!ram starts *ere
Sub Main()
nitialiseNo<-S:a,esAndStars(No<-S:a,es, No<-Stars, Ma5No<-Stars)
Do
<ut:ut&eadin!S:a,es(No<-S:a,es)
<ut:ut&ine<-Stars(No<-Stars)
AdNustNo<-S:a,esAndStars(No<-S:a,es, No<-Stars)
&oo: Dntil No<-Stars 7 Ma5No<-Stars
Console.Read&ine()
End Sub
End Module
With careful choice of identifiers the main ,ro&ram bod/ is eas/ to understand. $he
routines are no: self9contained and could even be ,ut into a se,arate unit.
8ook at the ,rocedure headin&s a&ain:
Sub nitialise(J/Re- S:a,es As nte!er, J/Re- Stars As nte!er,
J/Re- Ma5 As nte!er)
Sub <ut:ut&eadin!S:a,es(J/2al S:a,es As nte!er)
Sub <ut:ut&ine<-Stars(J/2al Stars As nte!er)
Sub AdNust(J/Re- S:a,es As nte!er, J/Re- Stars As nte!er)
<rocedures .nitialise and %dCust differ from 2ut,ut8eadin&S,aces and 2ut,ut8ine2fStars.
<arameters that ,ass a value back to the main ,ro&ram from the ,rocedure must be
declared as variable ,arameters :ith the ke/:ord B/+ef in front of them@ :hereas those
,arameters that onl/ ,ass a value into the ,rocedure are kno:n as value ,arameters and
have B/"al in front of them.
<a&e 36
.ntroduction to <ro&rammin&
;sin& "isual Basic
Value and Variable Parameters
"alue ,arameters are ,assed b/ value@ :hile variable ,arameters are ,assed b/
reference.
.f /ou ,ass a variable as a 9alue arameter@ the ,rocedure or function co,ies the value of
the callin& ,ro&ramKs variable to the ,rocedureKs ,arameter. Chan&es made to the co,/
have no effect on the ori&inal variable and are lost :hen ,ro&ram eecution returns to the
callin& ,ro&ram.
.f a ,arameter is ,assed as a 9ariable arameter@ a ,ointer referrin& to the address in
main memor/ of the ori&inal variable is ,assed. Chan&es made to the ,arameter :ithin
the bod/ of the routine are made to the ori&inal variable@ so in effect the ne: value is
,assed back to the ,ro&ram :here the routine :as called.
E6ercise
1. $he &ame J8ast one 8osesK is ,la/ed b/ t:o ,la/ers and uses a ,ile of n counters.
<la/ers take turns at removin& 1@ 1 or 3 counters from the ,ile. $he &ame
continues until there are no counters left and the :inner is the one :ho does not
take the last counter. ;sin& ,rocedures@ :rite a ,ro&ram to allo: the user to
s,ecif/ n in the ran&e 1- B #- inclusive and act as one ,la/er@ ,la/in& at random
until fe:er than # counters remain. $r/ ,la/in& a&ainst /our ,ro&ram@ and then
,la/in& to :in.
<a&e !-
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 0 ! 1ecords
% record data t/,e is a structured t/,e. % record is a collection of variables@ :hich need
not all be of the same t/,e and :ith no associated orderin&. $he variables can be
re&arded as fields of the record. Before :e can use records :e need to define :hat t/,e
of record :e :ant@ that is@ :hat fields our record is &oin& to have and :hat t/,e of data :e
are &oin& to store in them.
$he s/nta of a record t'e declaration is:
Str$ct$re >dentifier = record
?im 0ie&d&ist1 #s tBpe1;
?im 0ie&d&ist) #s tBpe);
<< <<
?im fi&d&istn #s tBpen
End Str$ct$re {of record type declaration}
.t is &ood ,ractice to declare $/,e declarations &lobal declarations. 2nce the t/,e is
declared :e can declare variables of this ne: t/,e Cust as :e declared variables usin&
t/,es from cha,ter 3. % useful namin& convention is to ,refi a t/,e :ith $@ so a record
t/,e to store student details :ould be called $Student:
Stru,ture .Student
Dim BirstName As Strin!
Dim Surname As Strin!
Dim De:osit(aid As De,imal
Dim Date<-Jirt* As Date
End Stru,ture
Declare record variables of t/,e $student:
Dim Student1A Student) #s TStudent
5o: :e can access individual fields of this record variable:
Student1<0irstName = "0red$
2r Student1<Surname = ;onso&e<Cead!ine()
<a&e !1
+ecord variable name 7ield name
.ntroduction to <ro&rammin&
;sin& "isual Basic
E6ercises
1. Declare a record t/,e to store the name of a countr/@ the name of its currenc/ and
the echan&e rate to the U. Write a ,ro&ram that reads in the details of one countr/
and dis,la/s them formatted in a user9friendl/ :a/.
1. Etend /our ,ro&ram from Eercise 1 to read in 3 countries and their res,ective
details and dis,la/ them in tabulated format.
3. Declare a record t/,e to store the follo:in& em,lo/ee details:
Em,lo/ee name@ em,lo/ee number@ total hours :orked this :eek@ hourl/ rate of
,a/.
Write a ,ro&ram that allo:s the user to enter an em,lo/eeKs data and dis,la/s a
sim,le ,a/ sli, :ith the above details and the calculated :eekl/ &ross ,a/.
-rra's of 1ecords
Wust as :ith standard variables@ :hen :e :ant to :ork :ith a lar&e collection it is better to
access them b/ a collective name. +ather than declarin& se,arate variables Student1@
Student1@ Student3@ ... :e can declare an arra/ of student records@ usin& the record t/,e
,reviousl/ defined
Dim Student(3 .o 133) As .Student
$o assi&n a value to the first name of the #
th
student in the arra/:
Student(5)<0irstName = "GacH$
5o: :e can use a for loo, to access all the studentsK details:
Bor :tr " 3 .o >> Ste: 1
Console.Write&ine(Student(:tr).BirstName,Student(:tr).Surname
Ne5t :tr
E6ercises
!. Etend /our ,ro&ram from eercise 1 to store the details of 1- countries in an arra/
of records. Dis,la/ the details in tabulated format.
#. Etend /our ,ro&ram from Eercise 3 to store details of 1# em,lo/ees. $he
,ro&ram should be able to search b/ em,lo/ee number and dis,la/ that ,articular
em,lo/eeKs ,a/ sli,. Dis,la/ a suitable messa&e if the em,lo/ee cannot be found
<a&e !1
%rra/
name
+ecord
subscri,t
7ield
name
.ntroduction to <ro&rammin&
;sin& "isual Basic
'. Declare an arra/ Student do record t/,e $Student as above. Write a ,ro&ram to
store # studentsK details. Enter # studentsK details and dis,la/ their details in
tabulated format.
*. Write a ,ro&ram that reads in an uns,ecified number@ not eceedin& 1--@ of friendsK
first names and a&es into records. $he ,ro&ram should then calculate the avera&e
a&e of /our friends and dis,la/ the avera&e a&e correct to 1 decimal ,laces. .t
should then dis,la/ each of /our friendsK names and :hether the/ are older or
/oun&er than the avera&e a&e.
<a&e !3
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 12 ! .iles
So far@ :e have lost an/ data the user t/,ed in durin& the runnin& of the ,ro&ram. .f :e
:ant to kee, data from one time of runnin& a ,ro&ram to the net@ :e need to save it in a
com,uter file. % file is a se=uence of elements of the same t/,e.
Stes to use a file7
2,en file for readin& 0i&eOpen (9num8A9path8A9OpenMode8)
+ead from the file: &ine = !ine>nput(9num8)
2r :rite to the file: Drint!ine (9num8A 9string8)
Close the file: 0i&e;&ose (9num8)
5e6t .iles
% tet file re,resents a file containin& a se=uence of characters formatted into lines@ :here
each line is terminated b/ an end9of9line marker. % tet file can be o,ened and read in a
tet editor.
$o create and :rite to a tet file J$est.ttK $o read from the tet file J$est.ttK
:at* " "d)O,om:utin!
resour,esO9isual basi,Otest.t5t"
Bile<:en(1, :at*, <:enMode.<ut:ut)
line " "Ho0 are /ou"
(rint&ine(1, line)
BileClose(1)
:at* " "d)O,om:utin! resour,esO9isual
basi,Otest.t5t"

Bile<:en(1, :at*, <:enMode.n:ut)
Do W*ile Not E<B(1)
line " &inen:ut(1)
Console.Write&ine(line)
&oo:
BileClose(1)
E6ercises
1. Write a ,ro&ram that reads in # lines of tet the user t/,es in at the ke/board. %s
each line is t/,ed in@ the ,ro&ram should :rite the line to a tet file@ usin& <rint8ine.
1. Write a ,ro&ram that reads lines of tet from a tet file and dis,la/s them to the
user. ?ou can create a tet file in an/ tet editor. Save it in the same folder as the
code for this ,ro&ram. +emember to use Eof (7ile5umber) to check :hen /ou
reach the end of the file.
Serial .iles
3. Declare a record t/,e to store names and dates of birth. Write a ,ro&ram that
reads a name and date of birth t/,ed in at the ke/board and saves it to an eternal
file.
<a&e !!
.ntroduction to <ro&rammin&
;sin& "isual Basic
!. Etend /our ,ro&ram from the eercise above to read in several names and dates
of birth and save each record out to the eternal file as it is entered. %llo: the user
to terminate in,ut b/ ,ressin& the Enter ke/ :ithout t/,in& in a name.
#. Write a ,ro&ram that reads the file created in Eercise 3 and dis,la/s the record.
'. Write a ,ro&ram that reads the file created in Eercise ! and dis,la/s the records
as a table of names and dates of birth.
*. Write a ,ro&ram that reads records from the file created in Eercise ! until it finds a
s,ecified name. $he ,ro&ram should then dis,la/ the name and corres,ondin&
date of birth. $he ,ro&ram should dis,la/ a suitable messa&e if the name cannot
be found in the file.
4. Write a ,ro&ram that :ill delete a s,ecified record from the file created in Eercise
!.
;ote7 ?ou cannot Cust delete a record in a serial or se=uential file. ?ou need to co,/ all
records to a ne: file@ omittin& the s,ecified record.
Se>uential .iles
6. Create a file :ith records in al,habetical order of name. 5o: :rite a ,ro&ram that
:ill add a record in the correct ,osition in the file.
;ote: /ou cannot insert a record in a serial or se=uential file. ?ou need to co,/ records
from the ori&inal file to a ne: file@ insertin& the ne: record in the correct ,lace
1-. Write a ,ro&ram that reads the file created in Eercise 6 and searches for a
s,ecified name. .f the name does not eist in the file@ the ,ro&ram should abort the
search at the earliest ,ossible time and dis,la/ a suitable messa&e.
11. Write a ,ro&ram that :ill dis,la/ a set of o,tions to the user to add@ delete or search
for a record. ;se the ,ro&rams develo,ed above to ,roduce a full/ :orkin& s/stem.
Direct -ccess .iles
$he disadvanta&es :ith serial and se=uential files are that /ou must start a search for a
record from the be&innin& of the file@ and addin& or deletin& records means :ritin& all the
records to a ne: file.
Direct access files (also kno:n as random access files) do not store records one after the
other but each record is stored at an address (or ,osition relative to the start of the file)
calculated from the value of its ke/ field. $his means a record can be inde,endentl/
accessed usin& its address. Since <ascal onl/ allo:s fied9len&th records@ :e can udate
in situ (over:rite an eistin& record :ith an u,dated record) :ithout disru,tin& the file.
<a&e !#
.ntroduction to <ro&rammin&
;sin& "isual Basic
7or eam,le@ if :e :ish to store details about stock items and these each have a uni=ue
item code (or ,rimar/ ke/) bet:een - and 1---@ and then this item code could be used
directl/ as the uni=ue record address.
Module Module1
Stru,ture .Sto,Gtem
Dim Sto,GtemCode As nte!er
82JBi5edStrin!(23)7 Dim Des,ri:tion As Strin!
Dim Dnit(ri,e As De,imal
Dim NonSto,G As nte!er
End Stru,ture
Sub Main()
Dim Sto,Gtem As .Sto,Gtem
Dim :at* As Strin!
Dim (osition As nte!er
:at* " "d)O,om:utin! resour,esO2isual Jasi,Osto,G.dat"
Bile<:en(1, :at*, <:enMode.Random, <:enA,,ess.De-ault,
<:enS*are.De-ault, &en(Sto,Gtem))
Console.Write("Enter in a Des,ri:tion) (E to Fnis*) ")
Sto,Gtem.Des,ri:tion " Console.Read&ine()
Do W*ile Sto,Gtem.Des,ri:tion 87 "E"
Console.Write("Enter Sto,G item ,ode (3 to 1333)) ")
Do
Sto,Gtem.Sto,GtemCode " Console.Read&ine()
&oo: Dntil Sto,Gtem.Sto,GtemCode 7" 3
Console.Write("Enter Dnit (ri,e) ")
Sto,Gtem.Dnit(ri,e " Console.Read&ine()
Console.Write("Enter Number o- items in sto,G) ")
Sto,Gtem.NonSto,G " Console.Read&ine()
(osition " Sto,Gtem.Sto,GtemCode
+SeeG(1, (osition)
Bile(ut(1, Sto,Gtem, (osition)
Console.Write("Enter in a Des,ri:tion) (E to Fnis*) ")
Sto,Gtem.Des,ri:tion " Console.Read&ine()
&oo:
BileClose(1)
End Sub
End Module
<a&e !'
.ntroduction to <ro&rammin&
;sin& "isual Basic
2ften@ the ,rimar/ ke/ for a set of records ma/ be in a ran&e not directl/ suitable as record
addresses. 7or eam,le@ if the stock item codes :ere in the ran&e 1--- to 6666@ the first
666 record s,aces in the file :ould never be used@ so :astin& a lot of disk s,ace. .n such
a case@ the ,rimar/ ke/ could be used in a calculation to ,roduce a more suitable address.
Such a calculation is called a hashin# al#orithm or hashin# function. $he ,rimar/ ke/
ma/ not be numerical@ a&ain makin& it necessar/ to ,roduce an address throu&h some
calculation on the ,rimar/ ke/. .t is im,ortant to desi&n a hashin& al&orithm in such a :a/
that it :ill ,roduce the re=uired ran&e of record addresses@ &ives a &ood s,read of
addresses and minimises the number of different record ke/s that :ill ,roduce the same
record address (kno:n as a collision or s'non'm). .f :e kno: that there :ill at most be
6-- different stock items and the stock item codes are in the ran&e 1--- to 6666@ :e mi&ht
:ish to &enerate addresses in the ran&e - to 666. $his could be done b/ takin& the
remainder after dividin& the stock item code b/ 1---. Belo: is the function that could be
called to &ive <osition a valid address:
Bun,tion Has*(J/2al ,ode As nte!er) As nte!er
Return ,ode Mod 1333
End Bun,tion
We can also read an eistin& record b/ calculatin& its address usin& the same hashin&
function.
.f a hashin& function mi&ht ,roduce s/non/ms@ the ,ro&ram needs to check that the record
s,ace is vacant before :ritin& a record at a &iven address. Similarl/@ :hen readin& a
record from a &iven address@ the ,ro&ram needs to check that it is the re=uired record.
<rovision can be made for s/non/ms b/ storin& subse=uent records that hash to the same
address in the net free record s,ace@ :ra,,in& to the be&innin& of the file :hen the end
of the file has been reached.
E6ercises
11. $/,e the ,ro&ram Direct%ccess7ileEam,le as a console a,,lication and test it.
13. Write a ,ro&ram to read the file created b/ the ,ro&ram from Eercise 11. $he
,ro&ram should find a record :hen its ,rimar/ ke/ is su,,lied.
<a&e !*
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 11 3indo4s .orms -lications
Hello 4orld Pro#ram
.n this cha,ter :e :ill look at :hat "isual Basic is reall/ used for and that is the Windo:s
7orms %,,lications. $his is the initial screen :hen /ou start a :indo:s forms a,,lication
in "isual E,ress 1-1-
%s /ou can see /ou are ,resented :ith an em,t/ form :hich is effectivel/ /our first
:indo: for /ou /our a,,lication.
Windo:s a,,lication is ,rimar/ about usin& controls such as tet boes@ buttons@
labels@dro,do:n lists etc.. and ho: /ou interact :ith them. .f /ou click on the toolbo /ou
can see the different amount of controls that /ou can ,lace on /our form.
<a&e !4
.ntroduction to <ro&rammin&
;sin& "isual Basic
Ever/ obCect has it o:n set of ,ro,erties. $he button is an obCect :ith its o:n list of
,ro,erties. When it is selected /ou can see this list on the ri&ht side of the screen.
Chan&e the 5ame ,ro,ert/ of the button to btnHello and the tet ,ro,ert/ to ?B.
Windo:s a,,lications are run b/ events. 7or instance clickin& on a button :ill tri&&er an
event that runs the code /ou ,ro&ram for it. 5othin& ha,,ens in a :indo:s a,,lication
until an event has tri&&ered it. $here are man/ ,ossible events for the different obCects@
<a&e !6
7or our first ,ro&ram the control
:e are &oin& to use is the
button. Dra& it across to /our
form.
.ntroduction to <ro&rammin&
;sin& "isual Basic
includin& for loadin& the 7orm in the first ,lace. We are &oin& :rite the code for the clickin&
event of the button.
.f /ou double click on the button itself /ou :ill be taken to the code :indo:. ?ou should
see the follo:in& code.
(ubli, Class Borm1
(ri9ate Sub btnHelloPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnHello.Cli,G
End Sub
End Class
We need to add out code bet:een the declaration and the End Sub. We are &oin& to add
the code
Ms!Jo5("Hello World")
Which sim,l/ brin&s u, a messa&e bo that sa/s Hello 3orld :hen /ou click on a button.
?ou have com,leted /our first "isual Basic Windo:s a,,lication.
5e6tBo6es
%nother common control is the tetbo. Create the follo:in& form.
<a&e #-
.ntroduction to <ro&rammin&
;sin& "isual Basic
$he tetboes in this form act like variables and :ill store :hat ever value that /ou ,ut in
them. ?ou can then reference them in an/ event tri&&ered b/ this form. Double click on
the button to brin& u, the code editor for that button and enter in the follo:in& code.
(ubli, Class Borm1
(ri9ate Sub btnCal,PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnCal,.Cli,G
Dim num1, num2, :rodu,t As nte!er
num1 " t5tNum1..e5t
num2 " t5tNum2..e5t
:rodu,t " num1 % num2
t5tSum..e5t " :rodu,t
End Sub
End Class
%s /ou can see /ou can access the values in the tetboes directl/ b/ referrin& to the
names /ou have &iven them and then accessin& the ,ro,ert/ 5e6t.
Chan#in# Proerties
%s mentioned before@ ever/ obCect@ includin& forms@ has their o:n ,ro,erties. ?ou can
alter them at run time. .n the eam,le belo: :e :ill look at chan&in& the ,ro,erties of the
back&round colour of the form de,endin& on :hat values the user enters in.
<a&e #1
5ame9 tt5um1
5ame9 tt5um1
5ame9 ttSum
8abels
5ame9 btnCalc
.ntroduction to <ro&rammin&
;sin& "isual Basic
Create the follo:in& form in a ne: "isual Basic Windo:s 7orm %,,lication ,roCect.
%nd insert the follo:in& code for the button btnChan&e
(ubli, Class Borm1
(ri9ate Sub btnC*an!ePCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnC*an!e.Cli,G
Dim red, !reen, blue As nte!er
red " t5tRed..e5t
!reen " t5tQreen..e5t
blue " t5tJlue..e5t
Me.Ja,GColor " Color.BromAr!b(red, !reen, blue)
End Sub
End Class
%s /ou can see /ou can &et the +GB numbers from the tet boes and then access the
,ro,erties of the form itself and chan&e it. .n this case the BackColor ,ro,ert/. 5ot that
/ou can access the form itself b/ usin& the obCect Ce. $his label :ill al:a/s refer to the
current form that /ou are in.
<a&e #1
$etBo 9 tt+ed
$etBo 9 tt+ed
$etBo 9 ttBlue
Button 9
btnChan&e
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 12 ! 5he Basic Calculator.
Buildin& on the addition a,,lication :e built earlier :e are no: &oin& to build a basic
calculator a,,lication.
Build the follo:in& form in a ne: "B ,roCect.
$he follo:in& &lobal variables are declared at the to, of the code
(ubli, Runnin!.otal As De,imal
(ubli, No<-Nums As nte!er
(ubli, <:eration As C*ar
(ubli, <: As Joolean
+unnin&$otal Bthis is the on&oin& total entered into the calculator
5o2f5ums B this is the number of numbers that make u, the runnin& total.
2,eration B $he current mathematic o,eration under:a/
2, B :hether an o,eration as taken ,lace so that the dis,la/ can no: be over:ritten.
%s /ou can ,robabl/ &uess from the t/,e of a,,lication there are &oin& to be a lot click
events for all the buttons. 7or each event the code is &oin& to look somethin& like this.
(ri9ate Sub btn3PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn3.Cli,G
- <: .*en
t5tDis:la/..e5t " "3"
<: " Balse
<a&e #3
%ll number buttons are &iven the
name btn and then the number@
e.&. btn,btn& etc3 $he decimal
is called btnDecimal. $he
o,erators are called as follo:s
btnClear
btn'lus
btnMult
btnMinus
btnDiv
btnE(uals
%nd the tet bo is called
txtDisplay
.ntroduction to <ro&rammin&
;sin& "isual Basic
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "3"
End -
End Sub
7irst thin& that is done is that :e check the Boolean variable 2,. .f it is true then an
o,eration has recentl/ been carried out on the calculator and therefore as :e start t/,in&
more numbers in B :e need to over:rite :hat is alread/ there. .f this is not the case then
:e need to add our number to the eistin& strin&.
$his code needs to be done for all the click events for the number buttons B chan&in& the
number itself :hen a,,ro,riate. 7or the decimal it is sli&htl/ different.
(ri9ate Sub btnDe,imalPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnDe,imal.Cli,G
- <: .*en
t5tDis:la/..e5t " "3."
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "."
End -
End Sub
5otice that if :e are over:ritin& then there has not been a number before B therefore b/
addin& a decimal :e are effectivel/ sa/in& that it is a decimal less than one Bhence the
need to start :ith H).I
5o: the code for each of the o,erators is sim,le.
(ri9ate Sub btn(lusPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn(lus.Cli,G
Carr/<:eration("%")
<: " .rue
End Sub
$o make this ,ro&ram more efficient :e :ill create a ,rocedure called Carry*peration
:hich takes a char as the ,arameter. $he ,arameter :ill be the o,eration that is to be
carried out. .n the events for the o,erators :e sim,l/ call that ,rocedure B ,assin& the
a,,ro,riate ,arameter and then set out Global *p variable to true. $his code is the same
for btnMult, btnDiv, btnMinus and btnE(uals.
$he code for out ,rocedure Carry*peration is as follo:s.
<a&e #!
.ntroduction to <ro&rammin&
;sin& "isual Basic
Sub Carr/<:eration(J/2al N5<: As C*ar)
No<-Nums " No<-Nums % 1
- No<-Nums 7 1 .*en
Sele,t Case <:eration
Case "%"
Runnin!.otal " Runnin!.otal % t5tDis:la/..e5t
Case "C"
Runnin!.otal " Runnin!.otal C t5tDis:la/..e5t
Case "6"
Runnin!.otal " Runnin!.otal 6 t5tDis:la/..e5t
Case "L"
Runnin!.otal " Runnin!.otal L t5tDis:la/..e5t
End Sele,t
Else
Runnin!.otal " t5tDis:la/..e5t
End -
<:eration " N5<:
t5tDis:la/..e5t " Runnin!.otal
End Sub
When /ou use the calculator an eam,le of the ,rocess &oes somethin& like this.
;ser action Dis,la/ <rocess
;ser enters in 1-- 1-- 1-- dis,la/ed
;ser enter in N 1-- 1-- dis,la/ed
;ser enters in #- #- #- is added onto1--
;ser enters in N 1#- $he result of ,revious
o,eration is sho:n
;ser enters in 1# 1# 1# is added to 1#-
;ser enters in M 1*# +esult of ,revious o,eration
is sho:n.
.f /ou notice that the results of the o,eration is not sho:n until the user either in,uts
another o,eration or ,resses e=uals. So in the Carr/2,eration ,rocedure :e carr/ out the
o,eration from the ,revious user in,ut so :e can dis,la/ that to the screen and then
chan&e the current o,erator for the net time.
Belo: is the full listin& for the Calculator <ro&ram.
<a&e ##
.ntroduction to <ro&rammin&
;sin& "isual Basic
Pro#ram :istin# for Basic Calculator Pro#ram
<:tion E5:li,it <n
(ubli, Class Borm1
(ubli, Runnin!.otal As De,imal
(ubli, No<-Nums As nte!er
(ubli, <:eration As C*ar
(ubli, <: As Joolean
(ri9ate Sub Borm1P&oad(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles M/Jase.&oad
No<-Nums " 3
Runnin!.otal " 3
<: " .rue
End Sub
(ri9ate Sub btnDe,imalPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnDe,imal.Cli,G
- <: .*en
t5tDis:la/..e5t " "3."
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "."
End -
End Sub
(ri9ate Sub btn3PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn3.Cli,G
- <: .*en
t5tDis:la/..e5t " "3"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "3"
End -
End Sub
(ri9ate Sub btn1PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn1.Cli,G
- <: .*en
t5tDis:la/..e5t " "1"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "1"
End -
End Sub
<a&e #'
.ntroduction to <ro&rammin&
;sin& "isual Basic
(ri9ate Sub btn2PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn2.Cli,G
- <: .*en
t5tDis:la/..e5t " "2"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "2"
End -
End Sub
(ri9ate Sub btn?PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn?.Cli,G
- <: .*en
t5tDis:la/..e5t " "?"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "?"
End -
End Sub
(ri9ate Sub btn@PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn@.Cli,G
- <: .*en
t5tDis:la/..e5t " "@"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "@"
End -
End Sub
(ri9ate Sub btn$PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn$.Cli,G
- <: .*en
t5tDis:la/..e5t " "$"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "$"
End -
End Sub
(ri9ate Sub btnAPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnA.Cli,G
- <: .*en
t5tDis:la/..e5t " "A"
<: " Balse
Me.Re-res*()
Else
<a&e #*
.ntroduction to <ro&rammin&
;sin& "isual Basic
t5tDis:la/..e5t " t5tDis:la/..e5t % "A"
End -
End Sub
(ri9ate Sub btn4PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn4.Cli,G
- <: .*en
t5tDis:la/..e5t " "4"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "4"
End -
End Sub
(ri9ate Sub btn#PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn#.Cli,G
- <: .*en
t5tDis:la/..e5t " "#"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % "#"
End -
End Sub
(ri9ate Sub btn>PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn>.Cli,G
- <: .*en
t5tDis:la/..e5t " ">"
<: " Balse
Me.Re-res*()
Else
t5tDis:la/..e5t " t5tDis:la/..e5t % ">"
End -
End Sub
(ri9ate Sub btnClearPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnClear.Cli,G
t5tDis:la/..e5t " "3"
Runnin!.otal " 3
No<-Nums " 3
<: " .rue
End Sub
(ri9ate Sub btn(lusPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btn(lus.Cli,G
Carr/<:eration("%")
<: " .rue
End Sub
<a&e #4
.ntroduction to <ro&rammin&
;sin& "isual Basic
(ri9ate Sub btnMultPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnMult.Cli,G
Carr/<:eration("6")
<: " .rue
End Sub
(ri9ate Sub btnMinusPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnMinus.Cli,G
Carr/<:eration("C")
<: " .rue
End Sub
(ri9ate Sub btnDi9PCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnDi9.Cli,G
Carr/<:eration("L")
<: " .rue
End Sub
(ri9ate Sub btnEMualsPCli,G(J/2al sender As S/stem.<bNe,t, J/2al e As
S/stem.E9entAr!s) Handles btnEMuals.Cli,G
Carr/<:eration(""")
<: " .rue
End Sub
Sub Carr/<:eration(J/2al N5<: As C*ar)
No<-Nums " No<-Nums % 1
- No<-Nums 7 1 .*en
Sele,t Case <:eration
Case "%"
Runnin!.otal " Runnin!.otal % t5tDis:la/..e5t
Case "C"
Runnin!.otal " Runnin!.otal C t5tDis:la/..e5t
Case "6"
Runnin!.otal " Runnin!.otal 6 t5tDis:la/..e5t
Case "L"
Runnin!.otal " Runnin!.otal L t5tDis:la/..e5t
End Sele,t
Else
Runnin!.otal " t5tDis:la/..e5t
End -
<:eration " N5<:
t5tDis:la/..e5t " Runnin!.otal
End Sub
End Class
<a&e #6
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 1$ ! %sin# VB- *Visual Basic for -lications+
"isual Basic for %,,lications is a ,o:erful tool that allo:s /ou to ,ro&ram the Eicrosoft
2ffice ,roducts to tailor them to real client needs. .t uses the "isual Basic ,ro&ram
lan&ua&e. .n this book :e :ill be lookin& at "B% for %ccess@ but as mentioned /ou can
also use it in Ecel@ <ublisher@ <o:er,oint@ <ublisher@ 2utlook and Word.
?ou can select "isual Basic throu&h the Database $ools ribbon in %ccess. $he screen
blo: is the .DE that /ou :ill :ork :ith. .t is similar to "isual Studio E,ress.

?ou can use the above editor like /ou can in "isual Basic E,ress. $/,e the follo:in& in
the code :indo:
Sub HelloWorld()
Es&Bo XHello WorldX@ vb2F2nl/@ XE/ 7irst "B% <ro&ramX
End Sub
?ou can run the routine b/ ,lacin& /our cursor directl/ in the code and clickin& on the
<8%? button. $his :ill run the ,rocedure /ou are in.
<a&e '-
Code is entered here.
Eodules
created
here
<ro,erties of the modules.
.ntroduction to <ro&rammin&
;sin& "isual Basic
Es&Bo is a ,rocedure that dis,la/s a messa&e. $he second ,arameter determines :hat
t/,e of messa&e bo it is. Belo: are the ,ossibilities for that ,arameter:
9b?B?nl' - Dis,la/ ?B button onl/.
9b?BCancel 1 Dis,la/ ?B and Cancel buttons.
9b-bort1etr'I#nore 1 Dis,la/ -bort@ 1etr'@ and I#nore buttons.
9b"es;oCancel 3 Dis,la/ "es@ ;o@ and Cancel buttons.
9b"es;o ! Dis,la/ "es and ;o buttons.
9b1etr'Cancel # Dis,la/ 1etr' and Cancel buttons.
9bCritical 1' Dis,la/ Critical Cessa#e icon.
9bDuestion 31 Dis,la/ 3arnin# Duer' icon.
9bE6clamation !4 Dis,la/ 3arnin# Cessa#e icon.
9bInformation '! Dis,la/ Information Cessa#e icon.
9bDefaultButton1 - 7irst button is default.
9bDefaultButton2 1#' Second button is default.
E6ercises
1) Create a ne: module in /our database and name it Hun&r/ Eouse. Create a
subroutine :ithin this module to dis,la/ the follo:in& messa&e.
1) Create another subroutine :hich dis,la/s the follo:in& messa&e:
<a&e '1
.ntroduction to <ro&rammin&
;sin& "isual Basic
E9ent Dri9en Pro#rammin# in VB-
%s mentioned in ,revious cha,ters most of the code in "isual Basic is tri&&ered b/ events@
for instance b/ clickin& on a button in a form. 2r b/ u,datin& a field in a form. Eost of the
tools that /ou can add to a user form :ill have a set of events associated :ith them
$o add the code for an event B Cust sim,l/ click on the button net to the event in
the ,ro,erties :indo: and select Code Builder. $his :ill set u, a skeleton subroutine for
that event :hich /ou can then add code to.
E6ercises
1) Create a form :ith t:o buttons in. 1 button runs /our Eouse Hun&r/ routine. $he
other button runs /our Eouse "er/ Hun&r/ routine.
Variables
%s :ith an/ ,ro&rammin& lan&ua&e "B% also uses variables. $hese variables can be of
man/ t/,es@ and also user defined t/,es.
.n "B% /ou do not have to declare variables B Cust use them :hen /ou :ant. Ho:ever is it
&ood ,ractice to declare them at the to,@ es,eciall/ :hen it comes to error checkin&.
<a&e '1
7orm Desi&n
<ossible events
for a button
.ntroduction to <ro&rammin&
;sin& "isual Basic
"ariables are declared as such:
Dim VariableName %s Datatype
.t is al:a/s best to include the :ords H2,tion E,licitI at the to, of ever/ module :hich
forces declaration of variables.
$he variable t/,es in "B% are virtuall/ the same as normal "B B here is a summar/ of
them
Data 5'e Descrition B'tes Con9ersion
B/te %n/ inte&er bet:een - and 1## 1 Cb/te
.nte&er %n/ inte&er :ith absolute value
less than 31@*'*
1 Cint
8on& %n/ inte&er :ith absolute value
less than 1 billion
! C8n&
Sin&le %n/ number :ith absolute value
less than 1-
34
! CSn&
Double %n/ number :ith absolute value
less than 1-
3-4
4 CDbl
Currenc/ %n/ amount :ith absolute value
less than 6O1-
1!
4 Ccur
Boolean "ariable that takes the value
$+;E or 7%8SE
1 Cbool
Date %n/ variable :hich contains a
date
4 Cdate
Strin& %n/ variable :hich contains tet R CStr
"ariant %n/ variable :hose data t/,e is
not kno:n
1'N Cvar
2bCect % reference to a "isual Basic
2bCect
! 50%
.unctions
7unctions in "B% are eactl/ the same as "B 9 the/ return a value.
<a&e '3
.ntroduction to <ro&rammin&
;sin& "isual Basic
$he .n,utBo is a function that returns a strin&.
.n,utBo(promptS@ titleT S@ defaultT S@ xposT S@ yposT S@ helpfile@ contextT)
E6ercises
1) Create a form that has a button. Create an event that :hen this button is ,ressed
an in,ut bo a,,ears that asks the user to enter 1 number. $hen another number .
%fter:ards a messa&e bo should a,,ear statin&:
$he ,roduct of Yfirst5umberZ and Ysecond5umberZ is Y%ns:erZ
e.&.
%ser Defined .unctions
?ou can create /our o:n functions usin& the format:
Function <name>(<par1> As <type?,) As <return type>
<name> = <return value>
n! Function
5ote that the variable that /ou assi&n the return value to is the same name as the function
name itself and does not have to be declared se,aratel/.
E6ercises
1) ;sin& the G2%8 Database create an u,date =uer/ that uses a function to ask the
user :hat ,la/er the/ :ant. 7or the &oals scored for that ,la/er B increment that
b/ one. 5ote: ;se .n,utbo to &et the criteria re=uired.
1) .n /our Goals database create a module called 5enure-tClub. Create a function
called 5enure to calculate the number of /ears each ,la/er has ,la/ed for his or her
club usin& the follo:in& formula:
<a&e '!
.ntroduction to <ro&rammin&
;sin& "isual Basic
5enure E "earEnd ! "earStart
.ncor,orate the function :ithin a =uer/ as follo:s:
5he DoCmd
$here is one command in %ccess that does an a:ful lot of thin&s. $his is the DoCmd. ?ou
can o,en forms@ run =ueries@ re,orts@ tables etc. % &reat man/ of them are self9
e,lanator/. Wust add the ,oint after DoCmd and a :hole list of ,rocedures :ill a,,ear in
the hel, menu.
E6ercises
1) Create a subroutine that o,ens u, the form that /ou created in Eercise 3 usin& the
Docmd.2,en7orm ,rocedure. See if /ou can &uess :hat /ou need to ,ut in the
,arameters. Hint: /ou :ill onl/ need the first 1.
Proerties
%s mentioned :ith "B@ all obCects used in forms have ,ro,erties. $he same a,,lies :ith
the forms in %ccess. Ever/ form@ re,ort@ control@ table etc.. .n %ccess has ,ro,erties.
$hese ,ro,erties can be mani,ulated b/ "B% code. 7or eam,le ho: about a sill/
,ro&ram :here :hen /ou click on a button it moves the button to the left.
"rivate #ub btn$%ase&$lic'()
(e)btn$%ase)*e+t = (e)btn$%ase)*e+t , 1--
n! #ub
HEeI is a s,ecial ke/:ord that is basicall/ the form /ou are on.
HbtnChaseI is the name of the button.
H8eftI is the name of the ,ro,ert/ /ou are chan&in&.
$r/ it out and see!!

<a&e '#
.ntroduction to <ro&rammin&
;sin& "isual Basic
E6ercises
1) 2,en the Database H<ro,erties Eam,leI and the form H7orm Code Eam,lesI
Can /ou do :hat the buttons are askin& /ou to doR
1) 2,en the database named <ro,erties Eam,les 1 and o,en the form titled $eams
(:ith buttons)
Can /ou do :hat the buttons are askin& /ou to do hereR
-mendin# Dueries
% ,o:erful tool that /ou can im,lement :ith "B% is to chan&e =ueries d/namicall/. ?ou
can &ather information durin& runtime and create an S>8 statement based on that
information. $his S>8 statement can then be substituted to a =uer/ that alread/ eists.
<a&e ''
.ntroduction to <ro&rammin&
;sin& "isual Basic
;sin& the G2%8S Database available on 7+2G create a =uer/ called
>r'Pla'ers-bo9e-Certain-#e. that sim,l/ returns ,la/ers above the a&e of 1#. We are
also &oin& to create a re,ort that dis,la/s the results of the above =uer/. Call this re,ort
rt:ist?fPla'ers.
5et :e are &oin& to create a form called frmPla'ers-bo9e-Certain-#e.
$he code belo: is for the click event of the button.
<rivate Sub btnSho:<la/ersLClick()

Dim = %s >uer/Def D the =uer/
Dim db %s Database D the database
Dim Ein%&e %s Strin& D the maimum a&e
Dim Ea%&e %s Strin& D the minimum a&e

D s,ecif/ the database
Set db M CurrentDb
D s,ecif/ the =uer/
Set = M db.>uer/Defs(X=r/8ist2f<la/ersX)
D &rab the maimum and minimum a&es from the form
Ein%&e M Ee.ttEin%&e
Ea%&e M Ee.ttEa%&e

D set the S>8
=.S>8 M XSE8EC$ <la/er5ame@ <la/er%&e 7+2E <la/ers WHE+E <la/er%&e
BE$WEE5 X V Ein%&e V X %nd X V Ea%&e

D o,en the re,ort in ,revie: mode
DoCmd.2,en+e,ort re,ortname:MXr,t8ist2f<la/ersX@ vie::Mac"ie:<revie:
<a&e '*
5ame 9
ttEin%&e
5ame 9
ttEa%&e
5ame 9
btnSho:<la/ers
.ntroduction to <ro&rammin&
;sin& "isual Basic
$here are a cou,le of data t/,es that /ou :ill be unfamiliar :ith in the variable declaration
section. 2ne is Database. $his is an obCect that encom,asses an %ccess Database.
$he other is Duer'Defs. $his is an obCect that encom,asses a =uer/ in that Database.
2nce the =uer/ is chan&ed b/ assi&nin& a ne: value the re,ort is run. $his re,ort
automaticall/ reruns the =uer/ :ith the ne: S>8.
<a&e '4
.ntroduction to <ro&rammin&
;sin& "isual Basic
Chater 1( ! 1ecord sets in VB-
?enin# a table
+ecord sets in "B% allo:s /ou to access and mani,ulate the tables directl/ in access.
?ou declare a variable as a record set and then use that variable to then access all the
fields@ ,ro,erties and data in the table.
?ou declare it like so:
Dim a+recordset ,S ,D*DB.#ecordset
?ou then need to initialise it.
Set a+recordset - .e/ ,D*DB.#ecordset
%fter /ou have initialised the recordset /ou need to o,en /our selected table. $o do this@
/ou use the H2,enI command as follo:s:
a+recordset.*pen
$he ,arameters for this function are:
1) 5ame of the table /ou :ish to o,en
$his :ill be the name of the table /ou :ish to o,en as a strin&
1) What t/,e of connection /ou :ish to o,en
$his :ill usuall/ be the current ,roCect B so the s/nta is as follo:s:
aLrecordset.2,en H$eamsI@ Current<roCect.Connection
3) $he Cursor t/,e
a!.penFor/ar!.nly 9 ?ou are ,ositioned at the be&innin& of the recordset@ and can onl/
move in one direction B for:ard.
a!.pen#tatic 9 Creates a co,/ of all the records in the recordset B chan&es made to the
underl/in& table b/ other users :onKt be detected.
a!.pen0eyset B Creates a co,/ of the ,rimar/ ke/ field onl/ for each record in the
recordset and returns to the main table for the other fields as and :hen needed. $his
cursor t/,e :ill sho: chan&es other users have made to eistin& records@ but :ill not sho:
records additions or deletions
<a&e '6
.ntroduction to <ro&rammin&
;sin& "isual Basic
a!.penDynamic 9 +eturns at an/ ,oint the latest set of records B but this comes at a hi&h
,rice in terms of ,erformance.
!) $he 8ock t/,e
a!*oc'1ea!.nly 9 ?ou can not chan&e an/ data
a!*oc'.ptimistic B ?ou can chan&e an/ data@ but %ccess :ill onl/ lock a record to
,revent others chan&in& it :hen /ou u,date /our chan&es usin& the u,date method.
a!*oc'"essimistic 9 ?ou can chan&e an/ data B the moment /ou scroll to a record@
%ccess locks it to ,revent other users chan&in& it.
a!*oc'2atc%.ptimistic 9 2nl/ used for Batch u,datin& (:hen /ou are ,ro&rammaticall/
chan&in& a number of records simultaneousl/.
So one :a/ of o,enin& a table is:
aLrecordset.2,en H$eamsI@ Current<roCect.Connection@ L
ad2,enD/namic@ ad8ock2,timistic
$he underscore at the end of the first line needs to be ,ut in if /our statement &oes over
one line.
1eferrin# to fields
$here are several :a/s of referrin& to fields in a recordset
aLrecordset.7ields(H$eam5ameI)."alue
$he value ,ro,ert/ of the s,ecified field
aLrecordset.7ields(H$eam5ameI)
$he default ,ro,ert/ of a field is its value@ so /ou can omit this.
aLrecordset(H$eam5ameI)
$he default collection for a recordset is to divide it into fields@ so /ou donKt need to s,ecif/
the collection name.
aLrecordset(-)
$he $eam5ame field is the first one in order
<a&e *-
.ntroduction to <ro&rammin&
;sin& "isual Basic
1ecordset .unctions
Some ver/ useful functions :hen usin& recordsets to mani,ulate Data
%Lrecordset.%ddne:
..
..
%Lrecordset.;,date
%ddne: starts a blank ro: in /our table. ?ou then add /our data to /our fields and then
u,date at the end.
%Lrecordset.Delete
2nce /ou have a ro: /ou :ish to delete B callin& this function deletes that ro:.
%Lrecordset.Edit
..
..
%Lrecordset.;,date
.f /ou :ant to edit a ro: B once /ou are at the correct ro: B callin& Edit allo:s /ou to edit
that ro:. %n u,date must be called at the end to make the chan&es.
When searchin& for ro:s@ either to delete them@ edit them or dis,la/ them /ou can use
loo,s to :ork throu&h the table as sho:n.
Do ;ntil aLrecordset.E27 J end of file

J Code that is re=uired
Dmust move onto net record@ or :ill never finish
aLrecordset.Eove5et

8oo,
$he E27 function returns true :hen /ou have reached the end of the table.
Some other useful functions that can be used in records sets are
Some other useful functions.
aLrecordset.Eove5et J move to the net record in the table
<a&e *1
.ntroduction to <ro&rammin&
;sin& "isual Basic
aLrecordset.Eove7irst J move to the first record in the table
aLrecordset.Eove<revious J move to the ,revious record in the table
aLrecordset.Eove8ast J move to the last record in the table
aLrecordset.7ind7irst(HS7.E8DL5%EETMJ"%8;EKIT
$he 7ind7irst function :ill find the first records that matched the criteria.

E6ercises
1) ;sin& the Goals Database Create a form that asks a user to enter in a ne: ,la/er
name and his a&e. Do not have this form linked to the <la/ers $able. %dd a
Confirm Button. %dd code to the click event of the confirm button that o,ens the
table H<la/ersI and adds the ne: ,la/er.
1) Create the follo:in& three modules
a. % ,rocedure called %ddChelsea to add Chelsea into the $eams $able
b. % ,rocedure called DeleteBlue$eams to delete all teams :ho ,la/ in blue
c. % ,rocedure called Chan&ed%rsenalGround to chan&e %rsenalKs &round from
Hi&hbur/ to %shbourne Grove.
$hese all can be done usin& a,,end@ delete and u,date =ueries but for the ,ur,ose
of ,racticin& :e :ill use %D2 recordsets.
<a&e *1
.ntroduction to <ro&rammin&
;sin& "isual Basic
Programming
Challenge
The National
Lottery
Details of ,la/
$o ,la/ the lotter/ /ou need to bu/ a ticket that cost U1. ?ou ,ick si numbers
bet:een 1 and !6. 2n dra: ni&ht the machine :ill ,ick si numbers and a
bonus ball. ?ou normall/ :in mone/ if /ou match 3@ !@ # and # N bonus.
Eatch all si numbers and /ou have :on the Wack,ot!
Write a :ro!ram t*at simulates t*e lotter/ b/ asGin! t*e user -or A
numbers and t*en s*o0s on t*e s,reen -or 5 number o- dra0s *o0
man/ times t*e/ mat,*ed ?,@,$, $ % bonus or A numbers.
.*e :ro!ram 0ill be marGed out o- ei!*tR @ -or t*e basi, :ro!ram
and u: to a -urt*er @ e5tra marGs -or t*e -ollo0in! e5tension tasGs)
Create a simulation o- t*e Slu,G/ di:T (0*ere numbers are
:i,Ged at random -or a :la/er)
Cal,ulate t*e number o- /ears to 0in t*e lotter/
Cal,ulate t*e :roFt and loss (U1 :er dra0 out!oin!s, 0innin!s
are ,ounted as in,ome)
<a&e *3
.ntroduction to <ro&rammin&
;sin& "isual Basic
Programming Challenge
Mayan Calendar
$his ,roblem :as set b/ the British .nformatics 2l/m,iad@ s,onsored b/
8ionhead Studios: one of the leadin& video&ames develo,ers in the ;F.
n t*e Ma/an ,alendar t*ere 0ere 23 da/s (,alled Gins) in a uinal, 1#
uinals in a tun, 23 tuns in a Gatun and 23 Gatuns in a baGtun. We
0rite our dates in t*e order da/, mont* t*en /ear. .*e Ma/a 0rote
t*eir dates in re9erse, !i9in! t*e baGtun, Gatun, tun, uinal t*en Gin.
.*e Ma/an date 1?C23C4C1AC? ,orres:onds to 1C1C2333. Write a
:ro!ram 0*i,* ,on9erts bet0een t*e Ma/an ,alendar and our o0n.
<a&e *!
.ntroduction to <ro&rammin&
;sin& "isual Basic
Programming Challenge
London Underground
$his ,roblem :as set b/ the British .nformatics 2l/m,iad@ s,onsored b/
8ionhead Studios: one of the leadin& video&ames develo,ers in the ;F.
It is a little known fact that the only station on the London
Underground that can be formed without using any of the letters
in the word mackerel is St Johns Wood. This is also true for the
words piranha and sturgeon (although for different stations).
For a given list of stations, write a rogram that takes a word and
determines if there is a single station that can be formed without
using any of its letters.
<a&e *#
.ntroduction to <ro&rammin&
;sin& "isual Basic
-endi6 -7 Pro#ress Self8-ssessment
5ask Due In *Date+ ComletedF Cark
Cha,ter 1 Eercises
Cha,ter 1 Eercises
Cha,ter 3 Eercises
Cha,ter ! Eercises
Cha,ter # Eercises
Cha,ter ' Eercises
Cha,ter * Eercises
Cha,ter 4 Eercises
Cha,ter 6 Eercises
Cha,ter 1- Eercises
-dditional e6ercises
:otter' Pro#ram
Checkout Soft4are
Pro#rammin# 5est Date
<a&e *'

Anda mungkin juga menyukai