Visual Basic Handbook

80
Visual Basic Handbook

Transcript of Visual Basic Handbook

Page 1: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 1/80

Visual Basic

Handbook

Page 2: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 2/80

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.................................................................................................................................................. 11Sin&le0Double......................................................................................................................................... 11

Char....................................................................................................................................................... 11

Strin&...................................................................................................................................................... 1

Boolean.................................................................................................................................................. 1

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 $hen............................................................................................................................................... 1*

Eercise................................................................................................................................................. 14

f $hen Else................................................................................................................................... 14

Eercises............................................................................................................................................... 14

5ested f statements.............................................................................................................................. 16

Eercises............................................................................................................................................... 16

ndentation............................................................................................................................................. 16

Select Case............................................................................................................................................ -

Eercises............................................................................................................................................... 1

Chater & Iteration *reetition+......................................................................................22

7or loo,..................................................................................................................................................

Eercises...............................................................................................................................................

Page 3: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 3/80

+e,eat 8oo,..........................................................................................................................................

Do While................................................................................................................................................ #

Eercises............................................................................................................................................... #

Chater , -rra's.............................................................................................................2,

2ne9Dimensional %rra/s........................................................................................................................ *

Eercises............................................................................................................................................... *

$o9Dimensional %rra/s........................................................................................................................ 4Eercises............................................................................................................................................... 6

Enumerated $/,es................................................................................................................................. 6

Sets........................................................................................................................................................ 3-

Chater ) unctions.......................................................................................................$1

Built9in 7unctions.................................................................................................................................... 31

Eercises............................................................................................................................................... 3

+andom 5umbers.................................................................................................................................. 3

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 ecords..........................................................................................................(1

Eercises...............................................................................................................................................

 %rra/s of +ecords..................................................................................................................................

Eercises...............................................................................................................................................

Chater 1 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.............................................................................................................................. #1Chater 12 5he Basic Calculator...................................................................................&$

<ro&ram 8istin& for Basic Calculator <ro&ram.......................................................................................#'

Chater 1$ %sin# VB- *Visual Basic for -lications+..............................................,

Eercises............................................................................................................................................... '1

Event Driven <ro&rammin& in "B%........................................................................................................'

Eercises............................................................................................................................................... '

"ariables................................................................................................................................................ '

7unctions............................................................................................................................................... '

Eercises............................................................................................................................................... '

;ser Defined 7unctions.......................................................................................................................... '

Eercises............................................................................................................................................... '

$he DoCmd............................................................................................................................................ '#

Eercises............................................................................................................................................... '#

Page 4: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 4/80

<ro,erties............................................................................................................................................... '#

Eercises............................................................................................................................................... ''

 %mendin& >ueries................................................................................................................................. '*

Chater 1( ecord sets in VB-.....................................................................................,0

2,enin& a table...................................................................................................................................... '6

+eferrin& to fields................................................................................................................................... *-

+ecordset 7unctions.............................................................................................................................. *1Eercises............................................................................................................................................... *

1) 7inal 2,en Ended Challen&e Simulatin& checkout softare..........................................................*3

-endi6 -7 Pro#ress Self8-ssessment.........................................................................),

Page 5: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 5/80

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 understandthe 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 knoled&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 folloin& 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.

• : <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 ala/s look for the sim,lest solution

• Writin& ,seudo9code after ritin& the ,ro&ram it does hel, /ou to solve a ,roblem

use it!

•  %skin& /our teacher for hel, before /ou check /our on code there is a useful

checklist of common errors at the back of this book (%,,endi %).

Con9entions used in this book7

Each maor conce,t is introduced in a ne cha,ter and an/ code ill be hi&hli&hted in the

folloin& a/:

This is programming code;

<a&e 1

Page 6: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 6/80

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%SC. B-SIC means Be&inners -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 softare com,anies ,roduced different versions of B%SC@ such as

icrosoft >B%SC@ >;CFB%SC@ GWB%SC @B B%SC% and so on. Hoever@ ,eo,le

,refer to use icrosoft "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@ "B--#@ "B--4 and the latest

"B-1-. Both "b--4 and "B-1- are full/ obect oriented ,ro&rammin& (22<)

lan&ua&e. (source 9 htt,:00.vbtutor.net0lesson1.html)

<a&e

Page 7: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 7/80

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 icrosoft "isual Basic

-1- E,ress. 7or the ,ur,ose of teachin& ,ro&rammin& basics e ill be usin& a

console a,,lication ,roect althou&h toards the end e ill look at the event driven visual

side of "B <ro&rammin&.

When /ou create a ne Console %,,lication ,roect /ou should see the folloin& in the

code editor.

Module Module1

  Sub Main()

  End Sub

End Module

Hello 3orld!

$/,e the code belo into the indo beteen the Main() and End Sub statements.

Console.Write("Hello World")Console.Read()

$his code rites the tet Hello WorldI to the screen@ and the +eadI kee,s the indo

o,en.

$o make /our ,ro&ram ork@ first of all save /our ork b/ ,ressin& the folloin& 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 orks

<a&e 3

Page 8: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 8/80

ntroduction to <ro&rammin&

;sin& "isual Basic

E6ercises

1. Write a ,ro&ram that ill out,ut to messa&es of /our choice on the screen@ on

se,arate lines.. Write a ,ro&ram that ill out,ut this rocket on the screen:

*

***

*****

*******

*******

*******

*******

*******

*******

*******

*******

***

*****

<a&e

Page 9: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 9/80

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 foruse 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 to 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 knon 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;BE+@ 5;BE+ are

all e=uivalent.

"isual re=uires /ou to declare hat t/,e of data /ou are &oin& to store in /our chosenvariables. $herefore if e ant to store hole numbers e need to declare them as

<a&e #

5<;$ <+2CESS 2;$<;$

Page 10: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 10/80

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 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 at the be&innin&. $hen it is the variable names folloed

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 becomes e=ual

toI or takes 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 3 into the variable Sum.

<a&e '

Page 11: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 11/80

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 beteen 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.eadline 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 to 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 *

Page 12: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 12/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Save the file and run the ,ro&ram. $his ill ,roduce the re=uired result. Hoever@ it is not

ver/ user9friendl/: e need to ,rom,t the user for hat to do. %dd some lines to /our

,ro&ram as follos:

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 folloin& out,ut:

;B7

Writeline ithout the brackets (,arameters) ill ust 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

Page 13: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 13/80

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

Page 14: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 14/80

ntroduction to <ro&rammin&

;sin& "isual Basic

-rithmetic E6ressions

We can rite more com,licated arithmetic e,ressions@ usin& the folloin& 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 1

P ulti,lication nte&er@ real nte&er@ real < P nterest+ate

0 +eal Division nte&er@ real +eal O 0

D" nte&er division nte&er nte&er $otal D" ;nitSiQe

2D +emainder nte&er nte&er ? 2D '

;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 ,ointand a fractional ,art. 7or more data t/,es@ see the net cha,ter.

Comments

7or all of the ,ro&rams from no onards /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 aa/.

<seudo9code0comments also hel, other ,eo,le understand the ,ro&ram@ and allo /ou toadd 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 follos 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.

. Write a ,ro&ram that ill read to inte&ers and dis,la/ the ,roduct.

3. Enter the len&th@ idth and de,th of a rectan&ular simmin& ,ool. Calculate the

volume of ater re=uired to fill the ,ool and dis,la/ this volume

<a&e 1-

Page 15: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 15/80

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 on 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 ala/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 ,rocedures or functions /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. emor/ allocated

b/tes. +an&e: 91*43'4 to 1*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 to 2&&. emor/ allocated: 1

b/te

Decimal$his data t/,e su,,orts si#ned numbers 4ith a decimal oint and fractional ,art.

emor/ 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 allos

stora&e of lar&er fractions.

Char 

$his is a sin&le character. emor/ allocated: 1 b/te. ?ou can assi&n a sin&le character to

a Char variable:

<a&e 11

Page 16: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 16/80

ntroduction to <ro&rammin&

;sin& "isual Basic

!etter1 = "#$;

Strin#

- strin# is a se>uence of characters. % strin& variable can store u, to 31 characters.

Hoever a strin& constant is limited to ## 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 to =uotes

" " $his strin& literal contains a s,ace

"$ $his strin& is knon as a null strin&

?ou can assi&n a strin& literal to a strin& variable:

0irstName = "Thomas$

?ou can concatenate strin&s (oin one strin& to the end of another) usin& the strin&

o,erator N

Message = "%e&&o " "'or&d$ 2note the space left after hello

0u&&Name = 0irstName Surname

Boolean

$his data t/,e su,,orts ust to values: $rue and 7alse. 7or eam,le:

0ound = 0a&se

0inished = True

emor/ 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 cha,ters).

$he folloin& 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 1

Page 17: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 17/80

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

3i4ep = 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 (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, esterda/ As Date

 oda/ No0() omorro0 oda/.AddDa/s(1)

  Console.Write&ine(oda/)  Console.Write&ine(omorro0)

<a&e 13

Page 18: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 18/80

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'esSim,le t/,es include ordinal types, double and Decimal. 8ater on /ou ill lean about t/,es

that are not sim,le t/,es@ knon 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 atRate 3.14$

  Sub Main()

  Dim ost, ta5 As Deimal

  Console.Write&ine("Enter t*e ost o- !oods ")  ost Console.Read&ine

  ta5 ost 6 atRate  Console.Write&ine("*e A is " ' ta5.oStrin!("N2"))  Console.Read()

  End Sub

End Module

-d9anta#es of usin# named constants

+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.

+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 decimal ,laces

indicated b/ 5I

Page 19: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 19/80

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 

. Write a ,ro&ram that asks the user to enter to real numbers and dis,la/s the

,roduct of these to numbers to 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.

$he formula for conversion is Centi&rade M (7ahrenheit 3) P (#06)T

. Write a ,ro&ram to convert a ,ersonKs hei&ht in inches into centimetres and theirei&ht in stones into kilo&rams. 1 inch M .# cm and 1 stone M '.3' k&T

<a&e 1#

Page 20: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 20/80

Page 21: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 21/80

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

folloin& 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 folloin& 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*

Page 22: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 22/80

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 to numbers from the user and then dis,la/s a

suitable messa&e if the to 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

. 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 1 to 6@

inclusive@ and dis,la/s an a,,ro,riate messa&e.

. Write a ,ro&ram that asks the user to enter numbers and dis,la/s the lar&er of the

to numbers.

<a&e 14

Page 23: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 23/80

Page 24: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 24/80

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:

Selet Case mont*  Case 1, ?, $, 4, #, 13, 12  No<-Da/s ?1  Case @, , >, 11  No<-Da/s ?3  Case 2  No<-Da/s 2#  Case Else  Console.Write&ine("Not a mont*")  End Selet

f Ch is of t/,e Char :

<a&e -

5ote that there must be

no semicolon here. $his

is a common s/nta error.

Page 25: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 25/80

ntroduction to <ro&rammin&

;sin& "isual Basic

  Selet Case letter  Case "A"  o ";", "a"  o "="  Console.Write&ine("&etter")  Case "3"  o ">"  Console.Write&ine("Number")

  Case Else  Console.Write&ine("S:eial C*arater")  End Selet

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 beteen 1 and 1 and dis,la/s

the month name for that month number. $he in,ut 3 ould therefore dis,la/ arch.

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 %

1.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

--- as a lea, /ear. (ti,: use the o,erators 0 and 2D)

<a&e 1

Page 26: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 26/80

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 = Starta&ue to Enda&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: 1  Console.Write&ine(Counter)  Ne5t Counter

E6ercises

1. ake each of the to 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)

. 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

Page 27: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 27/80

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 1 in to

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 ros 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

beteen 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 3

Page 28: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 28/80

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 ntil name ""  Console.Write("Enter a name to Fnis* ")  name Console.Read&ine()  &oo:

?ou ma/ ish to kno ho man/ times the loo, as re,eated:

  Do ntil number 3  Console.Write("Enter a number 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 ntil number 3  Console.Write("Enter a number 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, for eam,le

<a&e

Page 29: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 29/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Do Console.Write("Enter a number 3 to Fnis* ")

  number Console.Read&ine()  ount ount % 1  Runnin!total Runnin!total % number  &oo: ntil number 3

$he difference here is that ,uttin& the check at the end of the statement means that theloo, 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 checksthat a condition is ,ositive to continue loo,in& hile the latter checks that a condition isne&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 beteen 1- and - 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.

1.E,and /our ,ro&ram from Eercise 11 to dis,la/ the avera&e as ell as the sum of 

the number entered. ake 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 - ,ounds 1 k& M . ,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 #

Page 30: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 30/80

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 datat/,es. % data structure allos 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 knon as linear lists) and to9dimensional arra/s (also knon 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 NameA NameA Name+A Name5 #s String;

5ame1 5ame 5ame3 5ame

5ame#

$his is still mana&eable but hat if e needed to store several hundred studentsK namesR

<a&e '

ack %nna Sue +o/

Page 31: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 31/80

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() -nna

5ame(3) Sue

5ame() o'

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 ith

 element /ou rite 5ame(i)

$his is ,articularl/ ,oerful 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 loation " ' i ' " ")  &oation(i) Console.Read&ine()  Ne5t

We can easil/ dis,la/ these in reverse order:

  Bor i @ o 3 Ste: 1  Console.Write&ine(&oation(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.

. We ant to simulate throin& 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 Ks

<a&e *

 %rra/

identifier 

+an&e of

inde

 %ll elements of

an arra/ are of

the same t/,e

 %rra/

identifier 

nde or

subscri,t

Page 32: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 32/80

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 thron@

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&&Bhart(i) = Ta&&Bchart(i) 1

Write a ,ro&ram to simulate the throin& 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 beteen 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 beteen 1 and 6.

. We can declare to arra/s@ Student and DoB@ to store the name of Students and

their dates of birth. 7or eam,le if 7red is born on 0104@ then e could store

J7redK in Student1T and J0104K in DoB1T. $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 4

Page 33: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 33/80

Page 34: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 34/80

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/ 3I", 5)  Console.Write&ine("Sunda/ 3I", /)  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() ?, @, $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-

Page 35: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 35/80

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 ust a fe:

7unction

identifier 

<arameter(s)

(ar&uments)

+esult t/,e Descri,tion

ath.+ound O: Decimal 0

double

nte&er +eturns the value of O +ounded to the

nearest hole number 

ath.$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 loer case5o 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.&. 100-3

Date f S contains onl/ to 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

Page 36: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 36/80

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.

. 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 inu,,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 folloed b/ loer9case letters) and surname@ all u,,ercase@ re&ardless of

hat case the user entered.

andom ;umbers

We often ant to simulate events here random numbers occur@ such as throin& 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

+eturns an inte&er beteen - 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/ to

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 3

Page 37: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 37/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Module Module1

  Sub Main()  Dim number As nte!er

  Randomi=e() +s*ould onl/ be e5euted one to initiate random

  number !enerator

  number nt(Rnd() 6 ) +!enerates random number 3$  number number % 1 + add 1 to !et anumber 1

  Console.Write&ine(number)  Console.Read&ine()

  End Sub

End Module

E6ercises

6. Write a ,ro&ram that ill dis,la/ random numbers beteen 1 and ' until a si is

&enerated.

1-.Write a ,ro&ram that ill dis,la/ si random numbers beteen # and 1-.

11. Write a &ame in hich the user &uesses hat random number beteen 1 and 1---

the com,uter has Jthou&ht ofK@ until he or she has found the correct number. $hecom,uter should tell the user hether each &uess as too hi&h@ too lo or s,ot on.

<a&e 33

Page 38: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 38/80

Page 39: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 39/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Module Module1

  Dim number As nte!er

  Buntion Batorial(J/al N As nte!er) As nte!er

  Dim ount, :rodut As nte!er

  :rodut 1

  Bor ount 1 o N Ste: 1  :rodut :rodut 6 ount  Ne5t ount

  Return :rodut

  End Buntion

  Sub Main()

  Console.Write("/:e in a number bet0een 1 and 13 ")  number Console.Read&ine()  Console.Write&ine("return -rom -untion " ' Batorial(number))  Console.Read&ine()

  End Sub

End Module

E6ercise

1.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 3 ) P ( #06 )

<a&e 3#

Global "ariable

t is &ood ,ractice

to declare local

variables after the

function headin&.

Page 40: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 40/80

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 ,rovidesman/ built9in ,rocedures@ for eam,le +eadln and Writeln. Hoever@ e can also rite

our on ,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 don 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 don into the folloin& ste,s:

>nitia&ie number of spaces and stars

Cepeat

Output &eading spaces

Output &ine of stars

#dFust number of spaces and stars

nti& number of stars is the number re:uired

<a&e 3'

Page 41: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 41/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Module Module1

  Dim Ma5No<-Stars, No<-Stars, No<-S:aes As nte!er

  Sub nitialiseNo<-S:aesAndStars()

  Console.Write("Ho0 man/ stars s*ould be at t*e baseK ")  Ma5No<-Stars Console.Read&ine()  No<-S:aes Ma5No<-Stars L 2 +enou!* s:ae to aomodate base  No<-Stars 1 + i: *as one star

  End Sub

  Sub <ut:ut&eadin!S:aes()

  Dim ount As nte!er

  Bor ount 1 o No<-S:aes Ste: 1  Console.Write(" ") + No ne0 line reuired  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 AdustNo<-S:aesAndStars()

  No<-S:aes No<-S:aes 1  No<-Stars No<-Stars % 2

  End Sub

  + Main :ro!ram starts *ere

  Sub Main()

  nitialiseNo<-S:aesAndStars()

  Do  <ut:ut&eadin!S:aes()  <ut:ut&ine<-Stars()

<a&e 3*

Page 42: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 42/80

ntroduction to <ro&rammin&

;sin& "isual Basic

  AdustNo<-S:aesAndStars()

  &oo: ntil 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 canhave 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:aes As nte!er

  Sub nitialise(J/Re-  S:aes 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:aes Ma5No<-Stars L 2 +enou!* s:ae to aomodate base  Stars 1 + i: *as one star

  End Sub

  Sub <ut:ut&eadin!S:aes(J/al S:aes As nte!er)

  Dim ount As nte!er

  Bor ount 1 o S:aes Ste: 1  Console.Write(" ") + No ne0 line reuired  Ne5t ount

  End Sub

  Sub <ut:ut&ine<-Stars(J/al Stars As nte!er)

  Dim ount As nte!er

<a&e 34

Page 43: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 43/80

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 Adust(J/Re-  S:aes As nte!er, J/Re-  Stars As nte!er)

  S:aes S:aes 1  Stars Stars % 2

  End Sub

  + Main :ro!ram starts *ere

  Sub Main()

  nitialiseNo<-S:aesAndStars(No<-S:aes, No<-Stars, Ma5No<-Stars)

  Do  <ut:ut&eadin!S:aes(No<-S:aes)  <ut:ut&ine<-Stars(No<-Stars)  AdustNo<-S:aesAndStars(No<-S:aes, No<-Stars)

  &oo: ntil 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:aes As nte!er, J/Re-  Stars As nte!er,  J/Re-  Ma5 As nte!er)

Sub <ut:ut&eadin!S:aes(J/al S:aes As nte!er)Sub <ut:ut&ine<-Stars(J/al Stars As nte!er)Sub Adust(J/Re-  S:aes As nte!er, J/Re-  Stars As nte!er)

<rocedures nitialise and %dust 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 knon as value ,arameters and

have B/"al in front of them.

<a&e 36

Page 44: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 44/80

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/ to ,la/ers and uses a ,ile of n counters.

<la/ers take turns at removin& 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- #- inclusive and act as one ,la/er@ ,la/in& at randomuntil feer than # counters remain. $r/ ,la/in& a&ainst /our ,ro&ram@ and then

,la/in& to in.

<a&e -

Page 45: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 45/80

Page 46: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 46/80

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/.

. 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 folloin& 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 allos 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 ecords

ust 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@

Student@ 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

 %rra/

name

+ecord

subscri,t

7ield

name

Page 47: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 47/80

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 decimal ,laces. tshould 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

Page 48: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 48/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Chater 1 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* "dOom:utin!resouresO9isual basiOtest.t5t"

Bile<:en(1, :at*, <:enMode.<ut:ut)line "Ho0 are /ou"rint&ine(1, line)BileClose(1)

:at* "dOom:utin! resouresO9isualbasiOtest.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.

. 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 thatreads a name and date of birth t/,ed in at the ke/board and saves it to an eternal

file.

<a&e

Page 49: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 49/80

Page 50: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 50/80

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/) beteen - and 1---@ and then this item code could be used

directl/ as the uni=ue record address.

Module Module1

  Struture  StoGtem  Dim StoGtemCode As nte!er  8JBi5edStrin!(23)7 Dim Desri:tion As Strin!  Dim nitrie As Deimal  Dim NonStoG As nte!er  End Struture

  Sub Main()

  Dim StoGtem As  StoGtem

  Dim :at* As Strin!  Dim osition As nte!er

  :at* "dOom:utin! resouresOisual JasiOstoG.dat"

  Bile<:en(1, :at*, <:enMode.Random, <:enAess.De-ault,  <:enS*are.De-ault, &en(StoGtem))

  Console.Write("Enter in a Desri:tion ( to Fnis*) ")  StoGtem.Desri:tion Console.Read&ine()

  Do W*ile StoGtem.Desri:tion 87 ""  Console.Write("Enter StoG item ode (3 to 1333) ")  Do  StoGtem.StoGtemCode Console.Read&ine()  &oo: ntil StoGtem.StoGtemCode 7 3

  Console.Write("Enter nit rie ")  StoGtem.nitrie Console.Read&ine()  Console.Write("Enter Number o- items in stoG ")  StoGtem.NonStoG Console.Read&ine()

  osition StoGtem.StoGtemCode

  +SeeG(1, osition)  Bileut(1, StoGtem, osition)

  Console.Write("Enter in a Desri:tion ( to Fnis*) ")  StoGtem.Desri:tion Console.Read&ine()  &oo:

  BileClose(1)

  End Sub

End Module

<a&e '

Page 51: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 51/80

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 (knon 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 becalled to &ive <osition a valid address:

  Buntion Has*(J/al ode As nte!er) As nte!er  Return ode Mod 1333  End Buntion

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

1.$/,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 1. $he

,ro&ram should find a record hen its ,rimar/ ke/ is su,,lied.

<a&e *

Page 52: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 52/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Chater 11 3indo4s orms -lications

Hello 4orld Pro#ramn this cha,ter e ill look at hat "isual Basic is reall/ used for and that is the Windos

7orms %,,lications. $his is the initial screen hen /ou start a indos forms a,,lication

in "isual E,ress -1-

 %s /ou can see /ou are ,resented ith an em,t/ form hich is effectivel/ /our first

indo for /ou /our a,,lication.

Windos a,,lication is ,rimar/ about usin& controls such as tet boes@ buttons@

labels@dro,don 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

Page 53: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 53/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Ever/ obect has it on set of ,ro,erties. $he button is an obect ith its on 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 ?.

Windos 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 indos a,,lication

until an event has tri&&ered it. $here are man/ ,ossible events for the different obects@

<a&e 6

7or our first ,ro&ram the control

e are &oin& to use is the

button. Dra& it across to /our

form.

Page 54: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 54/80

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 folloin& code.

ubli Class Borm1

  ri9ate Sub btnHelloPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnHello.CliG

  End SubEnd Class

We need to add out code beteen 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 Windos a,,lication.

5e6tBo6es

 %nother common control is the tetbo. Create the folloin& form.

<a&e #-

Page 55: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 55/80

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 folloin& code.

ubli Class Borm1

  ri9ate Sub btnCalPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnCal.CliG

  Dim num1, num2, :rodut As nte!er

  num1 t5tNum1.e5t  num2 t5tNum2.e5t

  :rodut num1 % num2

  t5tSum.e5t :rodut

  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/ obect@ includin& forms@ has their on ,ro,erties. ?ou canalter 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 tt5um

5ame9 ttSum

8abels 5ame9 btnCalc

Page 56: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 56/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Create the folloin& form in a ne "isual Basic Windos 7orm %,,lication ,roect.

 %nd insert the folloin& code for the button btnChan&e

ubli Class Borm1

  ri9ate Sub btnC*an!ePCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnC*an!e.CliG  Dim red, !reen, blue As nte!er

  red t5tRed.e5t  !reen t5tQreen.e5t  blue t5tJlue.e5t

  Me.JaGColor Color.BromAr!b(red, !reen, blue)

  End SubEnd 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 obect e. $his label ill ala/s refer to the

current form that /ou are in.

<a&e #

$etBo 9 tt+ed

$etBo 9 tt+ed

$etBo 9 ttBlue

Button 9

btnChan&e

Page 57: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 57/80

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 folloin& form in a ne "B ,roect.

$he folloin& &lobal variables are declared at the to, of the code

  ubli Runnin!otal As Deimal  ubli No<-Nums As nte!er  ubli <:eration As C*ar  ubli <: As Joolean

+unnin&$otal this is the on&oin& total entered into the calculator 

5o2f5ums this is the number of numbers that make u, the runnin& total.

2,eration $he current mathematic o,eration undera/

2, hether an o,eration as taken ,lace so that the dis,la/ can no be overritten.

 %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 btn3PCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btn3.CliG

  -  <: *en  t5tDis:la/.e5t "3"  <: Balse

<a&e #3

 %ll number buttons are &iven the

name btn and then the number@

e.&. btn,btn&  etc $he decimal

is called btnDecimal.  $he

o,erators are called as follos

btnClear 

btn'lus

btnMult 

btnMinus

btnDiv 

btnE(uals

 %nd the tet bo is calledtxtDisplay  

Page 58: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 58/80

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 ano,eration has recentl/ been carried out on the calculator and therefore as e start t/,in&

more numbers in e need to overrite 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 chan&in& the

number itself hen a,,ro,riate. 7or the decimal it is sli&htl/ different.

ri9ate Sub btnDeimalPCliG(J/al sender As S/stem.<bet, J/al e As 

S/stem.E9entAr!s) Handles btnDeimal.CliG  -  <: *en  t5tDis:la/.e5t "3."  <: Balse  Me.Re-res*()  Else  t5tDis:la/.e5t t5tDis:la/.e5t % "."  End - End Sub

5otice that if e are overritin& then there has not been a number before therefore b/addin& a decimal e are effectivel/ sa/in& that it is a decimal less than one hence the

need to start ith ).I

5o the code for each of the o,erators is sim,le.

ri9ate Sub btnlusPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnlus.CliG  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 ,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 follos.

<a&e #

Page 59: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 59/80

Page 60: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 60/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Pro#ram :istin# for Basic Calculator Pro#ram

<:tion E5:liit <n

ubli Class Borm1

  ubli Runnin!otal As Deimal  ubli No<-Nums As nte!er  ubli <:eration As C*ar  ubli <: As Joolean

  ri9ate Sub Borm1P&oad(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles M/Jase.&oad  No<-Nums 3  Runnin!otal 3  <:  rue

  End Sub

  ri9ate Sub btnDeimalPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnDeimal.CliG  -  <: *en  t5tDis:la/.e5t "3."  <: Balse  Me.Re-res*()  Else  t5tDis:la/.e5t t5tDis:la/.e5t % "."  End - 

  End Sub

  ri9ate Sub btn3PCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btn3.CliG  -  <: *en  t5tDis:la/.e5t "3"  <: Balse  Me.Re-res*()  Else

  t5tDis:la/.e5t t5tDis:la/.e5t % "3"  End -   End Sub

  ri9ate Sub btn1PCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btn1.CliG  -  <: *en  t5tDis:la/.e5t "1"  <: Balse  Me.Re-res*()  Else

  t5tDis:la/.e5t t5tDis:la/.e5t % "1"  End -   End Sub

<a&e #'

Page 61: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 61/80

Page 62: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 62/80

ntroduction to <ro&rammin&

;sin& "isual Basic

  t5tDis:la/.e5t t5tDis:la/.e5t % ""  End -   End Sub

  ri9ate Sub btn4PCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btn4.CliG

  -  <: *en  t5tDis:la/.e5t "4"  <: Balse  Me.Re-res*()  Else  t5tDis:la/.e5t t5tDis:la/.e5t % "4"  End -   End Sub

  ri9ate Sub btn#PCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btn#.CliG  -  <: *en  t5tDis:la/.e5t "#"  <: Balse  Me.Re-res*()  Else  t5tDis:la/.e5t t5tDis:la/.e5t % "#"  End -   End Sub

  ri9ate Sub btn>PCliG(J/al sender As S/stem.<bet, J/al e As 

S/stem.E9entAr!s) Handles btn>.CliG  -  <: *en  t5tDis:la/.e5t ">"  <: Balse  Me.Re-res*()  Else  t5tDis:la/.e5t t5tDis:la/.e5t % ">"  End -   End Sub

  ri9ate Sub btnClearPCliG(J/al sender As S/stem.<bet, J/al e As 

S/stem.E9entAr!s) Handles btnClear.CliG  t5tDis:la/.e5t "3"  Runnin!otal 3  No<-Nums 3  <:  rue  End Sub

  ri9ate Sub btnlusPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnlus.CliG  Carr/<:eration("%")  <:  rue  End Sub

<a&e #4

Page 63: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 63/80

ntroduction to <ro&rammin&

;sin& "isual Basic

  ri9ate Sub btnMultPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnMult.CliG  Carr/<:eration("6")  <:  rue

  End Sub

  ri9ate Sub btnMinusPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnMinus.CliG  Carr/<:eration("")  <:  rue  End Sub

  ri9ate Sub btnDi9PCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnDi9.CliG  Carr/<:eration("L")  <:  rue  End Sub

  ri9ate Sub btnEualsPCliG(J/al sender As S/stem.<bet, J/al e As S/stem.E9entAr!s) Handles btnEuals.CliG  Carr/<:eration("")  <:  rue  End Sub

  Sub Carr/<:eration(J/al N5<: As C*ar)

  No<-Nums No<-Nums % 1

  -  No<-Nums 7 1 *en  Selet Case <:eration  Case "%"  Runnin!otal Runnin!otal % t5tDis:la/.e5t  Case ""  Runnin!otal Runnin!otal t5tDis:la/.e5t  Case "6"  Runnin!otal Runnin!otal 6 t5tDis:la/.e5t

  Case "L"  Runnin!otal Runnin!otal L t5tDis:la/.e5t  End Selet  Else  Runnin!otal t5tDis:la/.e5t  End - 

  <:eration N5<:  t5tDis:la/.e5t Runnin!otal

  End SubEnd Class

<a&e #6

Page 64: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 64/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Chater 1$ %sin# VB- *Visual Basic for -lications+

"isual Basic for %,,lications is a ,oerful tool that allos /ou to ,ro&ram the icrosoft

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@ <oer,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 folloin& in

the code indo

Sub HelloWorld()

  s&Bo XHello WorldX@ vb2F2nl/@ X/ 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.odules

created

here

<ro,erties of the modules.

Page 65: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 65/80

ntroduction to <ro&rammin&

;sin& "isual Basic

s&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??nl'   - Dis,la/ ? button onl/.

9b?Cancel  1 Dis,la/ ? and Cancel buttons.9b-bortetr'I#nore  Dis,la/ -bort@ etr'@ and I#nore buttons.

9b"es;oCancel  3 Dis,la/ "es@ ;o@ and Cancel buttons.

9b"es;o  Dis,la/ "es and ;o buttons.

9betr'Cancel  # Dis,la/ etr' and Cancel buttons.

9bCritical  1' Dis,la/ Critical essa#e icon.

9buestion  3 Dis,la/ 3arnin# uer' icon.

9bE6clamation  4 Dis,la/ 3arnin# essa#e icon.

9bInformation  ' Dis,la/ Information essa#e icon.

9bDefaultButton1  - 7irst button is default.9bDefaultButton2  #' Second button is default.

E6ercises

1) Create a ne module in /our database and name it Hun&r/ ouse. Create a

subroutine ithin this module to dis,la/ the folloin& messa&e.

) Create another subroutine hich dis,la/s the folloin& messa&e:

<a&e '1

Page 66: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 66/80

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. ost 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 ust 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 to buttons in. 1 button runs /our ouse Hun&r/ routine. $he

other button runs /our ouse "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 ust use them hen /ou ant. Hoever is it

&ood ,ractice to declare them at the to,@ es,eciall/ hen it comes to error checkin&.

<a&e '

7orm Desi&n <ossible events

for a button

Page 67: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 67/80

ntroduction to <ro&rammin&

;sin& "isual Basic

"ariables are declared as such:

Dim VariableName %s Datatype

t is ala/s best to include the ords 2,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 here is a summar/ of

them

Data 5'e Descrition B'tes Con9ersion

B/te %n/ inte&er beteen - and ## 1 Cb/te

nte&er %n/ inte&er ith absolute value

less than 3@*'*

Cint

8on& %n/ inte&er ith absolute value

less than 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

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 isnot knon

1'N Cvar  

2bect % reference to a "isual Basic

2bect

50%

unctions

7unctions in "B% are eactl/ the same as "B 9 the/ return a value.

<a&e '3

Page 68: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 68/80

ntroduction to <ro&rammin&

;sin& "isual Basic

$he n,utBo is a function that returns a strin&.

n,utBo( prompt @ titleT @ default T @ xposT @ yposT @ helpfile@ context T)

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 .

 %fterards a messa&e bo should a,,ear statin&:

$he ,roduct of Yfirst5umberZ and Ysecond5umberZ is Y%nserZ

e.&.

%ser Defined unctions

?ou can create /our on 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 increment that

b/ one. 5ote: ;se n,utbo to &et the criteria re=uired.

) 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 folloin& formula:

<a&e '

Page 69: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 69/80

Page 70: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 70/80

ntroduction to <ro&rammin&

;sin& "isual Basic

E6ercises

1) 2,en the Database <ro,erties Eam,leI and the form 7orm Code Eam,lesI

Can /ou do hat the buttons are askin& /ou to doR

) 2,en the database named <ro,erties Eam,les and o,en the form titled $eams

(ith buttons)

Can /ou do hat the buttons are askin& /ou to do hereR

-mendin# ueries

 % ,oerful 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 ''

Page 71: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 71/80

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 #. 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 the =uer/  Dim db %s Database the database

  Dim in%&e %s Strin& the maimum a&e

  Dim a%&e %s Strin& the minimum a&e

 

s,ecif/ the database

  Set db M CurrentDb

  s,ecif/ the =uer/

  Set = M db.>uer/Defs(X=r/8ist2f<la/ersX)

  &rab the maimum and minimum a&es from the form  in%&e M e.ttin%&e

  a%&e M e.tta%&e

 

set the S>8

  =.S>8 M XSE8EC$ <la/er5ame@ <la/er%&e 7+2 <la/ers WHE+E <la/er%&e

BE$WEE5 X V in%&e V X %nd X V a%&e

 

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

ttin%&e

5ame 9

tta%&e

5ame 9

btnSho<la/ers

Page 72: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 72/80

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 obect that encom,asses an %ccess Database.

$he other is uer'Defs. $his is an obect 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

Page 73: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 73/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Chater 1( ecord sets in VB-

?enin# a table

+ecord sets in "B% allos /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 2,enI command as follos:

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&

) What t/,e of connection /ou ish to o,en

$his ill usuall/ be the current ,roect so the s/nta is as follos:

aLrecordset.2,en $eamsI@ Current<roect.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 forard.

a!.pen#tatic  9 Creates a co,/ of all the records in the recordset chan&es made to the

underl/in& table b/ other users onKt be detected.

a!.pen0eyset   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 shorecords additions or deletions

<a&e '6

Page 74: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 74/80

ntroduction to <ro&rammin&

;sin& "isual Basic

a!.penDynamic  9 +eturns at an/ ,oint the latest set of records but this comes at a hi&h

,rice in terms of ,erformance.

) $he 8ock t/,e

a!*oc'ea!.nly  9 ?ou can not chan&e an/ data

a!*oc'.ptimistic   ?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 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 $eamsI@ Current<roect.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.

eferrin# to fields

$here are several a/s of referrin& to fields in a recordset

aLrecordset.7ields($eam5ameI)."alue

$he value ,ro,ert/ of the s,ecified field

aLrecordset.7ields($eam5ameI)

$he default ,ro,ert/ of a field is its value@ so /ou can omit this.

aLrecordset($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 *-

Page 75: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 75/80

ntroduction to <ro&rammin&

;sin& "isual Basic

ecordset 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 callin& this function deletes that ro.

 %Lrecordset.Edit

..

..

 %Lrecordset.;,date

f /ou ant to edit a ro once /ou are at the correct ro callin& Edit allos /ou to editthat ro. %n u,date must be called at the end to make the chan&es.

When searchin& for ros@ either to delete them@ edit them or dis,la/ them /ou can use

loo,s to ork throu&h the table as shon.

Do ;ntil aLrecordset.E27 J end of file

 

J Code that is re=uired

must move onto net record@ or ill never finish  aLrecordset.ove5et

 

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.ove5et J move to the net record in the table

<a&e *1

Page 76: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 76/80

Page 77: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 77/80

ntroduction to <ro&rammin&

;sin& "isual Basic

Programming

ChallengeThe National

Lottery

Details of ,la/$o ,la/ the lotter/ /ou need to bu/ a ticket that cost U1. ?ou ,ick si numbers

beteen 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.

atch all si numbers and /ou have on the ack,ot!

Write a :ro!ram t*at simulates t*e lotter/ b/ asGin! t*e user -or

numbers and t*en s*o0s on t*e sreen -or 5 number o- dra0s *o0

man/ times t*e/ mat*ed ?,@,$, $ % bonus or numbers.

 *e :ro!ram 0ill be marGed out o- ei!*t @ -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 luG/ di:T (0*ere numbers are

:iGed at random -or a :la/er)

• Calulate t*e number o- /ears to 0in t*e lotter/

• Calulate t*e :roFt and loss (U1 :er dra0 out!oin!s, 0innin!s

are ounted as inome)

<a&e *3

Page 78: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 78/80

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?2341? orres:onds to 112333. Write a

:ro!ram 0*i* on9erts bet0een t*e Ma/an alendar and our o0n.

<a&e *

Page 79: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 79/80

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 John’s 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 *#

Page 80: Visual Basic Handbook

8/11/2019 Visual Basic Handbook

http://slidepdf.com/reader/full/visual-basic-handbook 80/80

ntroduction to <ro&rammin&

;sin& "isual Basic

-endi6 -7 Pro#ress Self8-ssessment

5ask Due In *Date+ ComletedF ark

Cha,ter 1 Eercises

Cha,ter 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