Вы находитесь на странице: 1из 59

Lesson1 :Introduction

1.1 A brief description of Visual Basic


is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginners' Allpurpose Symbolic Instruction Code. It is a fairly easy programming language to learn. The codes loo a bit li e !nglish "anguage. Different soft#are companies produced different version of BASIC$ such as %icrosoft &BASIC$ &'IC(BASIC$ )*BASIC $IB% BASICA and so on. +IS'A" BASIC is a +IS'A" and events driven ,rogramming "anguage.These are the main divergence from the old BASIC. In BASIC$ programming is done in a te-t.only environment and the prgram is e-ecuted se/uentially. In +IS'A" BASIC$ programming is done in a graphical environment. Because users may clic on a certain ob0ect randomly$ so each ob0ect has to be programmed indepently to be able to response to those actions1events2.Therefore$ a +IS'A" BASIC ,rogram is made up of many subprograms$ each has its o#n program codes$ and each can be e-cecuted indepently and at the same time each can be lin ed together in one #ay or another.
VISUAL BASIC

1.2 The Visual Basic Environment


On start up$ +isual Basic 3.4 #ill display the follo#ing dialog bo- as sho#n in figure 5.5. 6ou can choose to start a ne# pro0ect$ open an e-isting pro0ect or select a list of recently opened programs. A pro0ect is a collection of files that ma e up your application. There are various types of applications #e could create$ ho#ever$ #e shall concentrate on creating Standard !7! programs1!7! means e-ecutable program2. 8o#$ clic on the Standard !7! icon to go into the actual +B programming environment.

Fi ure 1.1 The Visual Basic Start!u" #ialo Bo$

In figure 5.9$ the +isual Basic !nviroment consists of the The Blank Form window which you can design your application's interface. The Project window displays the files that are created in your application. The Properties window which displays the properties of various controls and objects that are created in your applications. It also includes a Toolbox that consists of all the controls essential for developing a VB Application. Controls are tools such as bo es! buttons! labels and other objects draw on a for" to get input or display output. They also add visual appeal. Fi ure 1.2: The Visual Basic Enviroment

Lesson 2: Buildin a Visual Basic A""lication


2.1 Creatin !our First Application In this section$ #e are not going into the technical aspect of +B programming$ 0ust have a feel of it. 8o#$ you can try out the e-amples belo#: E$am"le 2.1.1 is a simple program . ;irst of all$ you have to launch %icrosoft +isual Basic. 8ormally$ a default form Form1 #ill be available for you to start your ne# pro0ect. 8o#$ double clic on form5$ the source code #indo# for form5 #ill appear. Don't #orry about the begining and the end statements1i.e %rivate Su& Form'Load.......End Su&.2< =ust ey in the lines in bet#een the above t#o statements e-actly as are sho#n here.*hen you run the program$ you #ill be surprise that nothing sho#n up.In order to display the output of the program$ you have to add the Form1.sho( statement li e in !-ample 95.9 and !-ample 9.5.>. Try them out. $ a"ple #.1.1 ,rivate Sub ;orm?"oad ;or i@5 to A print BCelloB ne-t i $ a"ple #.1.# ,rivate Sub ;orm?"oad ;orm5.sho# ;or i@5 to A print BCelloB $ a"ple #.1.% ,rivate Sub ;orm?"oad ;orm5.sho# ;or i@5 to54 print i %

!nd Sub

ne-t i

ne-t i

!nd Sub !nd Sub 2.2 Ste"s in Buildin a Visual Basic A""lication Step 5 Draw the interface Step 9 Set Properties Step > Write the events code E$am"le 2.1 This program is a simple program that calculate the volume of a cylinder. "et design the interface:

;irst of all$ go to the properties #indo# and change the form caption to +olume Of Cylinder. Then dra# three label bo-es and change their captions to Base )adius* hei ht andvolume respectively. After that$ dra# three Te-t Bo-es and clear its te-t contents so that you get three empty bo-es. 8amed the te-t bo-es asradius *h ht+#e cannot use hei ht as it is the built.in control name of +B,and volume respectively. "astly$ insert a command button and change its caption to-... and its name to -.. 8o# save the pro0ect as cylinder.vbp and the form as cylinder.vbp as #ell. *e shall leave out the codes at the moment #hich you shall learn it in lesson>. E$am"le 2.2 Designing an attractive and user friendly interface should be the first step in constructing a +B program. To illustrate$ let's loo at the calculator program.

&

D 8o#$ please follo# the follo#ing steps to design the calculator interface. 'esi(e the for" until you get the si(e you are satisfed with. )o to the properties window and change the default caption to the caption you want ! such as %# Calculator*****+esigned by V,liew. Change other properties of the for"! such as bac,ground color! foreground color ! border style.I reco""end you set the following properties for -or"1 for this calculator progra".

Border"tyle #axButton

-i ed /ingle -alse

minButton True These properties will ensure that the users cannot resi(e or "a i"i(e your calculator window! but able to "ini"i(e the window. +raw the +isplay 0anel by clic,ing on the 1abel button and and place your "ouse on the for". /tart drawing by pressing down your "ouse button and drag it along. Clic, on the panel and the corresponding properties window will appear. Clear the default label so that the caption is blan,2because the display panel is supposed to show the nu"ber as we clic, on the nu"ber button3. It is good to set the bac,ground color to a bright color while the foreground color should be so"ething li,e blac,..2for easy viewing3. Change the na"e to display as I a" going to use it later to write codes for the calculator. 4ow draw the co""and buttons that are necessary to operate a calculator. I suggest you follow e actly what is shown in the i"age above. Test run the project by pressing -5. If you are satisfied with the appearance! go ahead to save the project. At the sa"e ti"e! you should also save the file that contain your for". 5

4ow! I ,now you are very ,een to ,now how to write the code so that the calculator is wor,ing. 0lease refer to "y sa"ple VB progra"s for the source codes.

Lesson / : 0ritin the Codes


4ow we shall atte"pt to write the codes for the cylinder progra".

8o#$ doubleclic on the O.( button and enter the codes bet#een ,rivate Sub O(?Clic 1 2 and !nd Sub Pri$ate "ub %&'Click( ) r * Val(radius.Text) + * Val(+ +t.Text) pi * 22 , $ * pi . (r / 2) . + $olume.Text* "tr0($) 1nd "ub when you run the progra" ! you should be able to see the interface as shown above. if you enter a value each in the radius bo and the height bo ! then clic, 67! the value of of the Volu"e will be displayed in the volu"e bo . I shall attempt to e-plain the above source program to ne#comers in +isual Basic1 If you are a veteran$ you can s ip this part2 . "et me describe the steps using pseudocodes as follo#s: Procedure for clicking the OK button to calculate the volume of cylinder get the value of r from the radius text box get the value of h from the height text box assign a constant value 22/7 to pi calculate the volume using formula output the results to the Volume text box End of Procedure The synta- radius.Text consists of t#o parts$ radius is the name of te-t bo- #hile Te$t is the te-tual contents of the te-t bo-. )enerally$ the syntais: -&1ect.%ro"ert2 In our e-ample$ the ob0ects are radius, hght and volume$ each having text as their property.Ob0ect and property is separated by a period1or 8

dot2.The contents of a te-t bo- can only be displayed in te-tual form$ or in programming term$as string. To convert the contents of a te-t bo- to a numeric value so that mathematical operations can be performed $ you have to use the function Val. ;inally$ In order to display the results in a te-t bo-$ #e have to perform the reverse procedure$ that is$ to convert the numeric value bac to the te-tual form$ using the function Str3. I shall also e-plain the synta- that defines the sub procedure %rivate Su& -.'clic4. Private Sub here means that the parameters $ values and formulas that are used here belong only to the O( subprocedure1an ob0ect by itself2.They cannot be used by other sub procedures or modules. O(?Clic defines #hat ind of action the subprocedure O( #ill response .Cere$ the action is mouse clic . There are other ind of actions li e eypress$ eyup$ eydo#n and etc that I am going to due #ith in other lessons.

Lesson 5!0or4in 0ith Controls


Before writing an event procedure for a control to response to a user's action! you have to set certain properties for the control to deter"ine its appearance and how it will wor, with the event procedure. 9ou can set the properties of the controls in the properties windows. I a" not going into the details on how to set the properties. :owever! I would li,e to stress a few i"portant points about setting up the properties. 9ou should set the Caption Property of a control clearly so that a user ,now what to do with that co""and. -or e a"ple! in the calculator progra"! all the captions of the co""and buttons such as ;! * ! <C !<' are co""only found in an ordinary calculator! a user should have no proble" in "anipulating the buttons. 9ou should set a "eaningful na"e for the 2ame Property because it is easier for you to write and read the event procedure and easier to debug your progra" later. Another property that is i"portant is whether you want your control to be $isible or not at start up.This property can only set to be true or false. 6ne "ore i"portant property is whether the control is enabled or not.

Lesson 6 : 7ana in Visual Basic #ata


There are many types of data #e come across in our daily life. ;or e-ample$ #e need to handle data such as names$ adresses$ money$ date$ stoc /uotes$ statistics and etc everyday. Similarly In +isual Basic$ #e are also going to deal #ith these inds of data. Co#ever$ to be more systematic$ +B divides data into different types. 6.1 T2"es o8 Visual Basic #ata 6.1.1 9umeric #ata 8umeric data are data that consists of numbers$ #hich can be computed mathematically #ith various standard operators such as add$ minus$ multiply$ divide and so on. In +isual Basic$ the numeric data are divided into E types$ they are summarised in Table 3.5 Ta&le 6.1: 9umeric #ata T2"es =

Type Byte Integer 1ong

3an e of Values > to #55 *%#!=8? to %#!=8= *#!1&=!&?%!8&? to #!1&=!&?%!8&? *%.&>#?#%$;%? to *1.&>1#@?$*&5 for negative values /ingle & bytes 1.&>1#@?$*&5 to %.&>#?#%$;%? for positive values. *1.=@=8@%1%&?8#%#e;%>? to *&.@&>858&5?&1#&=$*%#& for negative values +ouble ? bytes &.@&>858&5?&1#&=$*%#& to 1.=@=8@%1%&?8#%#e;%>? for positive values. Currency ? bytes *@##!%%=!#>%!8?5!&==.5?>? to @##!%%=!#>%!8?5!&==.5?>= ;A* =@!##?!18#!51&!#8&!%%=!5@%!5&%!@5>!%%5 if no deci"al is use +eci"al 1# bytes ;A* =.@##?18#51&#8&%%=5@%5&%@5>%%5 2#? deci"al places3. 6.1.2 9on!numeric #ata T2"es the nonnumeric data types are summarised in Table A.9 Ta&le 6.2: 9onnumeric #ata T2"es 4ata Type "tora e 3an e /tring2fi ed 1ength of string 1 to 85!&>> characters length3 /tring2variable 1ength ; 1> > to # billion characters length3 bytes +ate ? bytes Banuary 1! 1>> to +ece"ber %1! @@@@ Boolean # bytes True or -alse 6bject & bytes Any e"bedded object Variant2nu"eric3 18 bytes Any value as large as +ouble Variant2te t3 1ength;## bytes /a"e as variable*length string 6.1./ Su88i$es 8or Literals "iterals are values that you assign to a data. In some cases$ #e need to add a suffi- behind a literal so that +B can handle the calculation more accurately. ;or e-ample$ #e can use num@5.>4FGH for a Double type data. Some of the suffi-es are displayed in Table A.>. Ta&le 6./ "uffix 4ata Type C 1ong D /ingle E +ouble F Currency In additon$ #e need to enclose string literals #ithin t#o /uotations and date and time literals #ithin t#o H sign. Strings can contain any characters$ including numbers. The follo#ing are fe# e-amples: member8ame@BTurban$ =ohn.B Tel8umber@B5F44.G44.FFF.EEEB "astDay@H>5.Dec.44H !-pTime@H59:44 amH 6.2 7ana in Varia&les ?

"tora e 1 byte # bytes & bytes

+ariables are li e mail bo-es in the post office. The contents of the variables changes every no# and then$ 0ust li e the mail bo-es. In term of +B$ variables are areas allocated by the computer memory to hold data. "i e the mail bo-es$ each variable must be given a name. To name a variable in +isual Basic$ you have to follo# a set of rules. 6.2.1 Varia&le 9ames The follo#ing are the rules #hen naming the variables in +isual Basic It "ust be less than #55 characters 4o spacing is allowed It "ust not begin with a nu"ber 0eriod is not per"itted $ a"ples of valid and invalid variable na"es are displayed in Table 5.& Ta&le 6.5 Valid 2ame 5n$alid 2ame <yGCar <y.Car This9ear 14ewBoy 1ongG4a"eGCanGbeH/$ :eC:is-ather IC is not acceptable 6.2.2 #eclarin Varia&les In +isual Basic$ one needs to declare the variables before using them by assigning names and data types. They are normally declared in the genaral section of the codes' #indo#s using the #im statement. The format is as follo#s: Dim variable8mae as DataType !-ample A.5 Dim pass#ord As String Dim your8ame As String Dim firstnum As Integer Dim secondnum As Integer Dim total As Integer Dim doDate As Date 6ou may also combine them in one line $ separating each variable #ith a comma$ as follo#s: Dim pass#ord As String$ your8ame As String$ firstnum As Integer$............. If data type is not specified$ +B #ill automatically declares the variable as a +ariant. ;or string declaration$ there are t#o possible format$ one for the variable.length string and another for the fi-ed.length string. ;or the variable.length string$ 0ust use the same format as e-ample A.5 above. Co#ever$ for the fi-ed.length string$ you have to use the format as sho#n belo#: Dim VariableName as String * n$ #here n define- the number of characters the string can hold. !-ample A.9: Dim your8ame as String I 54 your8ame can holds no more than 54 Characters.

Lesson : : 0or4in (ith Varia&les


@

6.1 Assi nin Values to Variables After declaring various variables using the Dim statements$ #e can assign values to those variables. The general format of an assignment is VariableJ$ pression The variable can be a declared variable or a control property value. The e pression could be a "athe"atical e pression! a nu"ber! a string! a boolean value2true or false3 and etc. The following are so"e e a"ples. first8umber@544 second8umber@first8umber.GG user8ame@B=ohn "yanB userpass.Te-t @ pass#ord "abel5.+isible @ True Command5.+isible @ false "abelJ.Caption @ te-tbo-5.Te-t Third8umber @ +al1usernum5.Te-t2 total @ first8umber K second8umberKThird8umber :.2 -"erators in Visual Basic In order to co"pute inputs fro" users and to generate results! we need to use various "athe"atical operators. In Visual Basic! e cept for ; and *! the sy"bols for the operators are different fro" nor"al "athe"atical operators!as shown in Table 8.1. Table 3.5 %perator #at+ematical function 1xample $ ponential #K&J18 <ultiplication &I%J1# +ivision 1#A&J% <odulus2return the re"ainder fro" an 15 <od &J% integer division3 Integer +ivision2discards 1@L&J& the deci"al places3 MVisualMCMBasicMJMVisual /tring concatenation BasicM

K I
A <od L ; or C

!-ample 3.5: first8ame@Te-t5.Te-t second8ame@Te-t9.Te-t your8ame@first8ameKsecond8ame number5@val1Te-t>.Te-t2 number9@val1Te-tJ.Te-t2 number>@num5I1num9L>2 numberJ@number> %od 9 1>

numberA@numberJMnumber5 Total@number5Knumber9Knumber>KnumberJKnumberA Average@TotalNA In lesson$ #e #ill see ho# do #e use operators in #riting the +B programs codes.

Sam"le %ro ram: Usin I8....Then....Else

In this program$ you have to dra# three te-t bo-es$ three label bo-es$ one image boand four command buttons.Change the of the first te-t bo- to - 1te-t bo- starting from the left2$ second te-t bo- to y and third te-t bo- to O. Change the caption of label5 to B;Band the caption of label9 to B<B.Clear the caption of label> and change its name to display$ its purpose is to sho# that #hether the ans#er is #rong or correct. 8o#$ change the caption of the four command buttons to Start* 9e$t* -. and Sto"* you may also change their names follo#ing their captions respectively. 6ou also need to dra# a line and insert an image in the image bo- as sho#n in my program. 8o# let's loo at the codes: ,rivate Sub Stop?Clic 12 !nd !nd Sub ,rivate Sub Te-t5?Change12 !nd Sub Sub Start?Clic 12 ' To get any random integers from 4 to 544 PandomiOe Timer first8um @ Int1Pnd I 5442 K 5 second8um @ Int1Pnd I 5442 K 5 -.Te-t @ StrQ1first8um2 y.Te-t @ StrQ1second8um2 11

!nd Sub ,rivate Sub ,icture5?Clic 1 2 !nd Sub ,rivate Sub O(?Clic 1 2 If O.Te-t @ -.Te-t K y.Te-t Then display.Caption @ BCorrectB Image9.+isible @ BtrueB "ine5.+isible @ BtrueB !lse display.Caption @ B*rongB Image9.+isible @ BfalseB "ine5.+isible @ BfalseB !nd If !nd Sub ,rivate Sub 8e-t?Clic 12 O.Te-t @ BB display.Caption @ BB Start?Clic !nd Sub if you #ould li e the user to press the !nter ey after typing the ans#er$ #rite an event procedure for the ey,ress event as follo#s: ,rivate Sub O?(ey,ress1(eyAscii As Integer2 If 1(eyAscii @ 5>2 Then O(?Clic !nd If !nd Sub #here (eyAscii@5> denotes the !nter ey. After starting the program$ the user 1can be a teacher$ parent or a child himself2 have to clic on the Start button. T#o numbers #ill be presented in the first t#o te-t bo-. The user have to ey in the ans#er and clic O(. The user #ill no# #hether the ans#er is correct or #rong as it #ill be sho#n in the third label. To end$ 0ust clic on the Stop button. In this program$ you may need to no# #hat is the )nd and Int function . )nd return a random number bet#een 4 and 5 #hile Int returns the ne-t smallest integer of a number. !-ample: if Pnd@4.EJ9> 544IPnd@EJ.9> Int1544IPnd2@EJ By combining )nd and Int functions$ you can generate random integers of any range. The Str3 function is to convert a number to te$t #hile Val function is to convert te$t to num&er. ,lease try out the above program. If you have any doubts$ don't hesitate to email me.

1#

The Code Dim num5 As Integer Dim num9 As Integer Dim int8umber As Integer ,rivate Sub score12 int8umber @ int8umber K 5 !nd Sub ,rivate Sub begin12 int8umber @ 4 Image5.+isible @ ;alse Image9.+isible @ ;alse "abel3.+isible @ ;alse "abelA.+isible @ ;alse Te-t>.Te-t @ BB If Option5.+alue @ BtrueB Then n @ 54 !lseIf Option9.+alue @ BtrueB Then n @ 544 !lseIf Option>.+alue @ BtrueB Then n @ 5444 !nd If PandomiOe Timer 1%

num5 @ Int1Pnd I n2 num9 @ Int1Pnd I n2 Te-t5.Te-t @ num5 Te-t9.Te-t @ num9 Te-t>.Set;ocus !nd Sub

,rivate Sub Command>?Clic 12 !nd Sub ,rivate Sub Command9?Clic 12 !nd !nd Sub ,rivate Sub ;orm?"oad12 Image5.+isible @ ;alse Image9.+isible @ ;alse "abel3.+isible @ ;alse "abelA.+isible @ ;alse !nd Sub ,rivate Sub Start?Clic 12 begin !nd Sub ,rivate Sub te-t>? eyDo#n1 eyCode As Integer$ shift As Integer2 If eyCode @ vb(ey8e-t Or eyCode @ vb(eyDo#n Then begin !nd If !nd Sub ,rivate Sub te-t>? eypress1 eyAscii As Integer2 If 1 eyAscii @ 5>2 And +al1Te-t>.Te-t2 @ +al1Te-t5.Te-t2 K +al1Te-t9.Te-t2 Then Image5.+isible @ True Image9.+isible @ ;alse "abelA.+isible @ True "abel3.+isible @ ;alse score total.Caption @ StrQ1int8umber2 !lseIf 1 eyAscii @ 5>2 And +al1Te-t>.Te-t2 RD +al1Te-t5.Te-t2 K +al1Te-t9.Te-t2 Then Image5.+isible @ ;alse Image9.+isible @ True "abelA.+isible @ ;alse "abel3.+isible @ True 1&

Te-t>.Te-t @ BB !nd If !nd Sub

,rivate Sub Command5?Clic 12 !nd Sub ,rivate Sub 8e-t?Clic 12 Image5.+isible @ ;alse Image9.+isible @ ;alse "abel3.+isible @ ;alse "abelA.+isible @ ;alse If Option5.+alue @ BtrueB Then n @ 54 !lseIf Option9.+alue @ BtrueB Then n @ 544 !lseIf Option>.+alue @ BtrueB Then n @ 5444 !nd If Te-t5.Te-t @ BB Te-t9.Te-t @ BB Te-t>.Te-t @ BB PandomiOe Timer num5 @ Int1Pnd I n2 num9 @ Int1Pnd I n2 Te-t5.Te-t @ num5 Te-t9.Te-t @ num9 Te-t>.Set;ocus !nd Sub ,rivate Sub O(?Clic 12 If +al1Te-t>.Te-t2 @ +al1Te-t5.Te-t2 K +al1Te-t9.Te-t2 Then Image5.+isible @ True Image9.+isible @ ;alse "abelA.+isible @ True "abel3.+isible @ ;alse score total.Caption @ StrQ1int8umber2 !lse Image5.+isible @ ;alse Image9.+isible @ True "abelA.+isible @ ;alse "abel3.+isible @ True Te-t>.Te-t @ BB 15

!nd If !nd Sub ,rivate Sub Option5?Clic 12 n @ 54 !nd Sub ,rivate Sub ,icture5?Clic 12 !nd Sub ,rivate Sub Option9?Clic 12 n @ 544 !nd Sub ,rivate Sub Option>?Clic 12 n @ 5444 !nd Sub

Lesson = : 7ore -n %ro ram Control


=.1 Select Case
If you have a lot of conditional state"ents! using If..Then..$lse could be very "essy. -or "ultiple conditional state"ents! it is better to use /elect Case The format is : Select Case e-pression Case value5 Bloc of one or more +B statements Case value9 Bloc of one or more +B Statements Case value> Bloc of one or more +B statements Case valueJ . . . Case !lse Bloc of one or more +B Statements !nd Select I The data type specified in e-pression must match that of Case values.

=.2 E$am"les
$ a"ple ?.1 ' !-amination )rades Dim grade As String ,rivate Sub Compute?Clic 1 2 grade@t-tgrade.Te-t 18

Select Case grade Case BAB result.Caption@BCigh DistinctionB Case BA.B result.Caption@BDistinctionB Case BBB result.Caption@BCreditB Case BCB result.Caption@B,assB Case !lse result.Caption@B;ailB !nd Select I,lease note that grade is a string$ so all the case values such as BAB are of String data type. !-ample F.9 Dim mar As Single ,rivate Sub Compute?Clic 12 '!-amination %ar s mar @ mr .Te-t Select Case mar Case Is D@ FA comment.Caption @ B!-cellenceB Case Is D@ E4 comment.Caption @ B)oodB Case Is D@ 34 comment.Caption @ BAbove AverageB Case Is D@ A4 comment.Caption @ BAverageB Case !lse comment.Caption @ B8eed to #or harderB !nd Select !nd Sub I 8ote #e use the ey#ord Is here to impose the conditions. This is generally used for numeric data. !-ample F.> !-ample F.9 could be re#ritten as follo#s: Dim mar As Single ,rivate Sub Compute?Clic 12 '!-amination %ar s mar @ mr .Te-t Select Case mar Case 4 to JG comment.Caption @ B8eed to #or harderB 1=

Case A4 to AG comment.Caption @ BAverageB Case 34 to 3G comment.Caption @ BAbove AverageB Case E4 to FJ comment.Caption @ B)oodB Case !lse comment.Caption @ B!-cellenceB !nd Select !nd Sub

Lesson 1>: Introduction to VB Functions! %art I


-unctions are si"ilar to nor"al procedures but the "ain purpose of the functions is to accept certain inputs and pass the" on to the "ain progra" to finish the e ecution. They are two types of function! the built*in functions2or internal functions3 and the functions created by the progra""ers. The general format of a function is function4a"e2argu"ents3 where argu"ents are values that are passed on to the functions. In this lesson$ #e are going to learn t#o very basic but useful internal functions$ i.e. the %sgBo-1 2 and InputBo- 1 2 functions.

1>.1 7s Bo$ + , Function


The objective of <sgBo is to produce a pop*up "essage bo and pro"pt the user to clic, on a co""and button before he Ashe can continues. This "essage bo for"at is as follows. your%sg@%sgBo-1,rompt$ Style +alue$ Title2 The first argument$ ,rompt$ #ill display the message in the message bo-. The Style +alue #ill determine #hat type of command buttons appear on the message bo-$ please refer Table 54.5 for types of command button displayed. The Title argument #ill display the title of the message board. Ta&le 1>.1: St2le Values "tyle Value > 1 # % & 5 2amed Constant vb6,6nly vb6,Cancel vbAbort'etryIgnore vb9es4oCancel vb9es4o vb'etryCancel Buttons 4isplayed 6, button 6, and Cancel buttons Abort! 'etry and Ignore buttons. 9es! 4o and Cancel buttons 9es and 4o buttons 'etry and Cancel buttons 1?

*e can use named constant in place of integers for the second argument to ma e the programs more readable. Infact$ +B3 #ill automatically sho#s up a list of names constant #here you can select one of them. e-ample: your%sg@%sgBo-1 BClic O( to ,roceedB$ 5$ BStartup %enuB2 and your%sg@%sg1BClic O( to ,roceedB. vbO Cancel$BStartup %enuB2 are the same. your%sg is a variable that holds values that are returned by the %sgBo- 1 2 function. The values are determined by the type of buttons being clic ed by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 54.9 sho#s the values$ the corresponding named constant and buttons. Ta&le 1>.2 : )eturn Values and Command Buttons Value 2amed Constant Button Clicked 1 vb6, 6, button # vbCancel Cancel button % vbAbort Abort button & vb'etry 'etry button 5 vbIgnore Ignore button 8 vb9es 9es button = vb4o 4o button !-ample 54.5 i. The Interface: 6ou dra# three command buttons and a label as sho#n in ;igure 54.5 ;igure 54.5

ii. The procedure for the test button:

0rivate /ub TestGClic,23 +i" test"sg As Integer test"sg J <sgBo 2MClic, to testM! 1! MTest "essageM3 If test"sg J 1 Then +isplay.Caption J MTesting /uccessfulM $lse +isplay.Caption J MTesting failM $nd If 1@

!nd Sub Nhen a user clic, on the test button! the i"age li,e the one shown in -igure 1>.# will appear. As the user clic, on the 67 button! the "essage MTesting sucessfulM will be diplayed and when heAshe clic,s on the Cancel button! the "essage MTesting failM will be displayed. ;igure 54.9

To ma e the message bo- loo s more sophisticated$ you can add an icon besides the message. The are four types of icons available in +B as sho#n in Table 54.> Table 54.> Value 18 %# &? 8& 2amed Constant vbCritical vbOuestion vb$ cla"ation vbInfor"ation 5con

!-ample 54.9 In this e-ample$ the follo#ing message bo- #ill be displayed: ;igure 54.>

6ou could dra# the same Interface as in e-ample 54.5 but modify the codes as follo#s: 0rivate /ub test#GClic,23 +i" test<sg# As Integer test<sg# J <sgBo 2MClic, to TestM! vb9es4oCancel ; vb$ cla"ation! #>

MTest <essageM3 If test<sg# J 8 Then display#.Caption J MTesting successfulM $lseIf test<sg# J = Then display#.Caption J MAre you surePM $lse display#.Caption J MTesting failM $nd If !nd Sub

1>.2 The In"utBo$+ , Function


An InputBo 2 3 function will display a "essage bo where the user can enter a value or a "essage in the for" of te t. The for"at is "y<essageJInputBo 20ro"pt! Title! defaultGte t! *position! y*position3 "y<essage is a variant data type but typically it is declared as string! which accept the "essage input bu the users.The argu"ents are e plained as follows.

0ro"pt * The "essage displayed nor"ally as a Question as,ed. Title * The title of the Input Bo . default*te t * The default te t that appears in the input field where users can use it as his intended input or he "ay change to the "essage he wish to ,ey in. *position and y*position * the position or the coordinate of the input bo .

$ a"ple 1>.% i. The Interface ;igure 54.J

ii. The procedure for the O( button

#1

0rivate /ub 67GClic,23 +i" user<sg As /tring user<sg J InputBo 2MNhat is your "essagePM! M<essage $ntry -or"M! M$nter your "essge hereM! 5>>! =>>3 If user<sg RS MM Then "essage.Caption J user<sg $lse "essage.Caption J M4o <essageM $nd If !nd Sub Nhen a user clic, the 67 button! the input bo as shown in -igure 1>.5 will appear. After user entering the "essage and clic, 67! the "essage will be displayed on the caption! if he clic, Cancel! M4o "essageM will be displayed.

Lesson 11: Introduction to VB Functions! %art II


11.1 Creatin !our %7n Functions The general format of a function is as follo#s: ,ublic ;unction function8ame 1Arg As dataType$..........2 As dataType or ,rivate ;unction function8ame 1Arg As dataType$..........2 As dataType I ,ublic indicates that the function is applicable to the #hole program and ,rivate indicates that the function is only applicable to a certain module or procedure. !-ample 55.5 In this e-ample$ a user can calculate future value of a certain amount of money he has today based on the interest rate and the number of years from no#1supposing he #ill invest this amount of money some#here2. The calculation is based on the compound interest rate.

##

,ublic ;unction ;+1,+ As +ariant$ i As +ariant$ n As +ariant2 As +ariant ';ormula to calculate ;uture +alue1;+2 ',+ denotes ,resent +alue ;+ @ ,+ I 15 K i N 5442 L n !nd ;unction ,rivate Sub compute?Clic 12 'This procedure #ill calculate ;uture +alue Dim ;uture+al As +ariant Dim ,resent+al As +ariant Dim interest As +ariant Dim period As +ariant ,resent+al @ ,+.Te-t interest @ rate.Te-t period @ years.Te-t ;uture+al @ ;+1,resent+al$ interest$ period2 %sgBo- 1BThe ;uture +alue is B S ;uture+al2 !nd Sub !-ample 55.9 The follo#ing program #ill automatically compute e-amination grades based on the mar s that a student obtained.

,ublic ;unction grade1mar As +ariant2 As String Select Case mar #%

Case Is D@ F4 grade @ BAB Case Is D@ E4 grade @ BBB Case Is D@ 34 grade @ BCB Case Is D@ A4 grade @ BDB Case Is D@ J4 grade @ B!B Case !lse grade @ B;B !nd Select !nd ;unction ,rivate Sub compute?Clic 12 grading.Caption @ grade1mar 2 !nd Sub ,rivate Sub !nd?Clic 12 !nd !nd Sub

Lesson 12: Creatin VB Functions For 7S E$cel


12.2 T+e 2eeds to Create 8ser94efined Functions in #"91xcel 6ou can create your o#n functions to supplement the built.in functions in %icrosoft !-cel spreadsheet #hich are /uite limited. These functions could be very useful and po#erful if you no# ho# to program them properly. One main reason #e need to create user defined functions is to enable us to customiOe our spreadsheet environment for individual needs. ;or e-ample$ #e might need a function that could calculate commissions payment based on the sales volume$ #hich is /uite difficult if not impossible by using the built.in function alone. "ets loo at the table belo#: Ta&le 12.1: Commissions %a2ment Ta&le /ales Volu"e2T3 Co""issons R5>> %U R1>>> 8U R#>>> @U R5>>> 1#U S5>>> 15U In the above table$ if a saleman attain a sale volume of Q3444$ he #ill be paid Q3444-59T@QE94.44. A visual basic function to calculate the commissions could be #ritten as follo#s: ;unction Comm1Sales?+ As +ariant2 as +ariant If Sales?+ RA44 Then Comm@Sales?+I4.4> #&

!lseif Sales?+D@A44 and Sales?+R5444 Then Comm@Sales?+I4.43 !lseif Sales?+D@5444 and Sales?+R9444 Then Comm@Sales?+I4.4G !lseif Sales?+D@944 and Sales?+RA444 Then Comm@Sales?+I4.59 !lseif Sales?+D@A444 Then Comm@Sales?+I4.5A !nd If !nd ;unction 12.2 Usin 7icroso8t E$cel Visual Basic Editor To create 'ser Defined functions in %S !-cel$ you can clic on tools$ select macro and then clic on +isual Basic !ditor as sho#n in ;igure 59.5

Fi ure 12.1: Insertin 7s'E$cel Visual Basic Editor

'pon clic ing the +isual Basic !ditor$ the +B !ditor #indo#s #ill appear as sho#n in figure 59.9. To create a function$ type in the function as illustrated in section 59.5 above After typing$ save the file and then return to the $ cel windows. Fi ure 12.2 : The VB Editor

#5

In the !-cel #indo#s$ type in the titles Sales +olume and Commissions in any t#o cells. By refering to figure 59.>$ ey.in the Comm function at cell CJ and by referencing the value in cell BJ$ using the format Comm1BJ2. Any value appear in cell BJ #ill pass the value to the Comm function in cell CJ. ;or the rest of the ro#s$ 0ust copy the formula by draging the bottom right corner of cell CJ to the re/uired cells$ and a nice and neat table that sho# the commisions #ill automatically appear. It can also be updated anytime

Fi ure 12./: 7S E$cel 0indo(s! Sales Volume

#8

Lesson 1/: Arra2s


1/.1 Introduction to Arra2s
By definition! an array is a list of variables! all with the sa"e data type and na"e. Nhen we wor, with a single ite"! we only need to use one variable. :owever! if we have a list of ite"s which are of si"ilar type to deal with! we need to declare an array of variables instead of using a variable for each ite". -or e a"ple! if we need to enter one hundred na"es! instead of declaring one hundred different variables! we need to declare only one array. Ne differentiate each ite" in the array by using subscript! the inde value of each ite"! for e a"ple na"e213! na"e2#3!na"e2%3 .......etc.

1/.2 #eclarin Arra2s


Ne could use 0ublic or +i" state"ent to declare an array just as the way we declare a single variable. The 0ublic state"ent declares an array that can be used throughout an application while the +i" state"ent declare an array that could be used only in a local procedure. The general format to declare an array is as follo#: Dim array8ame1subs2 as dataType #here subs indicates the last subscript in the array. #=

E$am"le 1/.1 Dim Cus8ame1542 as String #ill declare an array that consists of 54 elements if the statement Option Base 5 appear in the declaration area$ starting from Cus8ame152 to Cus8ame1542. Other#ise$ there #ill be 55 elements in the array starting from Cus8ame142 through to Cus8ame1542 E$am"le 1/.2 Dim Count1544 to A442 as Integer declares an array that consists of the first element starting from Count15442 and ends at Count1A442

1/./ Sam"le %ro rams


2i3 The Inter8ace

The codes Dim student8ame1542 As String Dim num As Integer ,rivate Sub add8ame12 ;or num @ 5 To 54 student8ame1num2 @ InputBo-1B!nter the student nameB$ B!nter 8ameB$ BB$ 5A44$ JA442 If student8ame1num2 RD BB Then ;orm5.,rint student8ame1num2 !lse !nd !nd If #?

8e-t !nd Sub ,rivate Sub !-it?Clic 12 !nd !nd Sub ,rivate Sub Start?Clic 12 ;orm5.Cls add8ame !nd Sub The above program accepts data entry through an input bo- and displays the entries in the form itself. As you can see$ this program #ill only allo#s a user to enter 54 names each time he clic on the start button. 1ii2 The Inter8ace

The Codes Dim student8ame1542 As String Dim num As Integer ,rivate Sub add8ame1 2 ;or num @ 5 To 54 student8ame1num2 @ InputBo-1B!nter the student nameB2 "ist5.AddItem student8ame1num2 8e-t !nd Sub ,rivate Sub Start?Clic 12 add8ame !nd Sub The above program accepts data entries through an InputBo- and displays the items in a list bo-.

#@

Lesson 15: 0or4in (ith Files


15.1 Introduction Hp until lesson 1% we are only creating progra"s that could accept data at runti"e! when a progra" is ter"inated! the data also disappear. Is it possible to save data accepted by a VB progra" into a storage device! such as a hardis, or dis,ette! or even C+'NP The answer is possible. Is this chapter! we will learn how to create files by writing the" into a storage device and then retrieve the data by reading the contents of the files using custo"i(ed VB progra"s. 15.2 Creatin 8iles To create a file ! use the following co""and -"en ?8ile9ame? For -ut"ut As @8ile9um&er !ach file created must have a file name and a file number for identification. As for file name$ you must also specify the path #here the file #ill reside. ;or e-ample -"en ?c:A72 #ocumentsAsam"le.t$t? For -ut"ut As @1 #ill create a te-t file by the name of sample.t-t in the %y Document folder. The accompany file number is 5. If you #ish to create and save the file in A drive$ simply change the path$ as follo#sB -"en ?A:Asam"le.t$t? For -ut"ut As @1 If you #ish to create a CT%" file $ simple change the e-tension to .html -"en ?c:A72 #ocumentsAsam"le.html? For -ut"ut As @ 2 15.2.1 Sam"le %ro ram : Creatin a te$t 8ile ,rivate Sub create?Clic 12 Dim int%sg As String Dim Student8ame As String Open Bc:M%y DocumentsMsample.t-tB ;or Output As H5 int%sg @ %sgBo-1B;ile sample.t-t openedB2 Student8ame @ InputBo-1B!nter the student 8ameB2 ,rint H5$ Student8ame int%sg @ %sgBo-1B*riting aB S Student8ame S B to sample.t-t B2 Close H5 int%sg @ %sgBo-1B;ile sample.t-t closedB2 !nd Sub I The above program #ill create a file sample.t-t in the %y Documents' folder and ready to receive input from users. Any data input by users #ill be saved in this te-t file. 15./ )eadin 8iles To read a file created in section 1&.#! you can use the input E state""ent. :owever! we can only read the file according to the for"at when it was written. 9ou have to open the file according to its file nu"ber and the variable that hold the data. Ne also need to declare the variable using the +I< co""and. 15./.1 Sam"le %ro ram: )eadin 8ile %>

,rivate Sub Peading?Clic 12 Dim variable5 As String Open Bc:M%y DocumentsMsample.t-tB ;or Input As H5 Input H5$ variable5 Te-t5.Te-t @ variable5 Close H5 !nd Sub I This program #ill open the sample.t-t file and display its contents in the Te-t5 te-tbo-.

Lesson 16: Creatin 7ultimedia A""lications


9ou can create various "ulti"edia applications in VB that couold play audio C+! audiofiles! VC+ ! video files and etc. To be able to play "ulti"edia files or "ulti"edia devices! you have to insert <icrosoft <ulti"edia Control into your VB applications that you are going to create. :owever! <icrosoft <ulti"edia Control is not nor"ally included in the startup toolbo ! therefore you need to add the << control by pressing Ctrl;T and select it fro" the co"ponents dialog bo that is displayed. 5A.5 Creating a CD player 1a2 The Interface.

,rivate Sub ;orm?"oad12 'To position the page at the center "eft @ 1Screen.*idth . *idth2 M 9 Top @ 1Screen.Ceight . Ceight2 M 9 'Open the CD myCD.Command @ BOpenB !nd Sub ,rivate Sub myCD?Status'pdate12 ''pdate the trac number trac 8um.Caption @ myCD.Trac !nd Sub %1

,rivate Sub 8e-t?Clic 12 myCD.Command @ B8e-tB !nd Sub ,rivate Sub ,lay?Clic 12 myCD.Command @ B,layB !nd Sub ,rivate Sub ,revious?Clic 12 myCD.Command @ B,revB !nd Sub ,rivate Sub Stop?Clic 12 myCD.Command @ BStopB !nd Sub ,rivate Sub !-it?Clic 12 !nd !nd Sub

Lesson 1:: Creatin 7ultimedia A""lications!%art 2


In previous lesson$ #e have programmed a CD player. 8o#$ #ith some modifications$ #e #ill transform the CD player into an audio file player. This player #ill be created in such a #ay that it could search for #ave and midi files in your drives and play them. In this pro0ect$ you need to insert a ComboBo-$ a Drive"istBo-$ a Dir"istBo-$ a Te-tBo- and a ;ile"istBo- into your form.I Shall briefly discuss the function of each of the above controls. Besides$ you must also insert %icrosoft %ultimedia Control1%%Control2 in your form $ you may ma e it visible or invisible. In my program$ I choose to ma e it invisible so that I could use the command buttons created to control the player. ComboBo-. to display and enable selection of different type of files. Drive"istBo-. to allo# selection selection of different drives available on your ,C. Dir"istBo- . To display directories Te-tBo- . To display selected files ;ile"istBo-. To display files that are available Pelevant codes must be #ritten to coordinate all the above controls so that the application can #or properly. The program should flo# in the follo#ing logical #ay: Step 5: 'ser choose the type of files he #ants to play. Step9:'ser selects the drive that might contains the relevant audio files. Step >:'ser loo s into directories and subdirectories for the files specified in step5. The files should be displayed in the ;ile"istBo-. Step J: 'ser selects the files from the ;ile"istBo- and clic the ,lay button. Step A: 'ser clic on the Stop to stop playing and !-it button to end the application. The Inter8ace

%#

The Code ,rivate Sub Combo5?Change12 ' to determine file type If "istInde- @ 4 Then ;ile5.,attern @ 1BI.#avB2 !lseIf "istInde- @ 5 Then ;ile5.,attern @ 1BI.midB2 !lse ;iel5.,attern @ 1BI.IB2 !nd If !nd Sub ,rivate Sub Dir5?Change12 'To change directories and subdirectories1or folders and subfolders2 ;ile5.,ath @ Dir5.,ath If Combo5."istInde- @ 4 Then ;ile5.,attern @ 1BI.#avB2 !lseIf Combo5."istInde- @ 5 Then ;ile5.,attern @ 1BI.midB2 !lse ;ile5.,attern @ 1BI.IB2 !nd If !nd Sub ,rivate Sub Drive5?Change12 'To change drives Dir5.,ath @ Drive5.Drive !nd Sub ,rivate Sub ;ile5?Clic 12 If Combo5."istInde- @ 4 Then %%

;ile5.,attern @ 1BI.#avB2 !lseIf Combo5."istInde- @ 5 Then ;ile5.,attern @ 1BI.midB2 !lse ;ile5.,attern @ 1BI.IB2 !nd If If Pight1;ile5.,ath$ 52 RD BMB Then filenam @ ;ile5.,ath K BMB K ;ile5.;ile8ame !lse filenam @ ;ile5.,ath K ;ile5.;ile8ame !nd If Te-t5.Te-t @ filenam !nd Sub ,rivate Sub ;orm?"oad12 'To center the Audioplayer startup page "eft @ 1Screen.*idth . *idth2 M 9 Top @ 1Screen.Ceight . Ceight2 M 9 Combo5.Te-t @ BI.#avB Combo5.AddItem BI.#avB Combo5.AddItem BI.midB Combo5.AddItem BAll filesB !nd Sub ,rivate Sub Audio,layer?Clic 12 !nd Sub ,rivate Sub play?Clic 12 'To play *aveAudio file or %idi ;ile Command9?Clic If Combo5."istInde- @ 4 Then Audio,layer.DeviceType @ B*aveAudioB !lseIf Combo5."istInde- @ 5 Then Audio,layer.DeviceType @ BSe/uencerB !nd If Audio,layer.;ile8ame @ Te-t5.Te-t Audio,layer.Command @ BOpenB Audio,layer.Command @ B,layB !nd Sub ,rivate Sub stop?Clic 12 If Audio,layer.%ode @ A9J Then !-it Sub %&

If Audio,layer.%ode RD A9A Then Audio,layer.*ait @ True Audio,layer.Command @ BStopB !nd If Audio,layer.*ait @ True Audio,layer.Command @ BCloseB !nd Sub ,rivate Sub !-it?Clic 12 !nd !nd Sub

Lesson 1B: Creatin 7ultimedia A""lications!%art /


In lesson 53$ #e have created an audio player. 8o#$ #ith some modifications$ #e #ill transform the audio player into a picture vie#er. This player #ill be created in such a #ay that it could search for all types of graphics your drives and play them. Similar to the previous pro0ect$ in this pro0ect$ you need to insert a ComboBo-$ a Drive"istBo-$ a Dir"istBo-$ a Te-tBo- and a ;ile"istBo- into your form. I Shall brieflye-plain again the function of each of the above controls. ComboBo-. to display and enable selection of different type of files. Drive"istBo-. to allo# selection selection of different drives available on your ,C. Dir"istBo- . To display directories Te-tBo- . To display selected files ;ile"istBo-. To display files that are available Pelevant codes must be #ritten to coordinate all the above controls so that the application can #or properly. The program should flo# in the follo#ing logical #ay: Step 5: 'ser choose the type of files he #ants to play. Step9:'ser selects the drive that might contains the relevant graphic files. Step >:'ser loo s into directories and subdirectories for the files specified in step5. The files should be displayed in the ;ile"istBo-. Step J: 'ser selects the files from the ;ile"istBo- and clic the Sho# button. Step A: 'ser clic on !-it button to end the application. The Inter8ace

%5

CTest run the "ro ramD The Code ,rivate Sub ;orm?"oad12 "eft @ 1Screen.*idth . *idth2 M 9 Top @ 1Screen.Ceight . Ceight2 M 9 Combo5.Te-t @ BAll graphic filesB Combo5.AddItem BAll graphic filesB Combo5.AddItem BAll filesB !nd Sub

%rivate Su& Com&o1'Chan e+, I8 ListInde$ < > Then File1.%attern < +?E.&m"FE.(m8FE.1" FE. i8?, Else
%8

Fiel1.%attern < +?E.E?, End I8 End Su& %rivate Su& #ir1'Chan e+, File1.%ath < #ir1.%ath File1.%attern < +?E.&m"FE.(m8FE.1" FE. i8?, End Su& %rivate Su& #rive1'Chan e+, #ir1.%ath < #rive1.#rive End Su& %rivate Su& E$it'Clic4+, End End Su& %rivate Su& File1'Clic4+, I8 Com&o1.ListInde$ < > Then File1.%attern < +?E.&m"FE.(m8FE.1" FE. i8?, Else File1.%attern < +?E.E?, End I8 I8 )i ht+File1.%ath* 1, GH ?A? Then 8ilenam < File1.%ath ; ?A? ; File1.File9ame Else 8ilenam < File1.%ath ; File1.File9ame End I8
%=

Te$t1.Te$t < 8ilenam End Su& %rivate Su& "la2'Clic4+, 77%la2er.File9ame < Te$t1.Te$t End Su&

%rivate Su& sho('Clic4+, I8 )i ht+File1.%ath* 1, GH ?A? Then 8ilenam < File1.%ath ; ?A? ; File1.File9ame Else 8ilenam < File1.%ath ; File1.File9ame End I8 "icture1.%icture < Load%icture+8ilenam, End Su& Lesson 1=: Creatin 7ultimedia A""lications! %art 5: A 7ultimedia %la2er
In lesson 53$ #e have created an audio player. 8o#$ #ith some modifications$ #e #ill transform the audio player into a multimedia player that could play all inds of movie files besides audio files. This player #ill be created in such a #ay that it could search for all types of graphics your drives and play them. In this pro0ect$ you need to insert a ComboBo-$ a Drive"istBo-$ a Dir"istBo-$ a Te-tBo- $a ;ile"istBo- and a picture bo-1for playing movie2 into your form. I Shall briefly discuss the function of each of the above controls. Besides$ you must also insert %icrosoft %ultimedia Control1%%Control2 in your form $ you may ma e it visible or invisible. In my program$ I choose to ma e it invisible so that I could use the command buttons created to control the player. ComboBo-. to display and enable selection of different type of files. %?

Drive"istBo-. to allo# selection selection of different drives available on your ,C. Dir"istBo- . To display directories Te-tBo- . To display selected files ;ile"istBo-. To display files that are available

Pelevant codes must be #ritten to coordinate all the above controls so that the application can #or properly. The program should flo# in the follo#ing logical #ay: Step 5: 'ser choose the type of files he #ants to play. Step9:'ser selects the drive that might contains the relevant audio files. Step >:'ser loo s into directories and subdirectories for the files specified in step5. The files should be displayed in the ;ile"istBo-. Step J: 'ser selects the files from the ;ile"istBo- and clic the ,lay button. Step A: 'ser clic on the Stop to stop playing and !-it button to end the application. The Inter8ace

CTest run the "ro ramD The Code ,rivate Sub ;orm?"oad12 "eft @ 1Screen.*idth . *idth2 M 9 Top @ 1Screen.Ceight . Ceight2 M 9 Combo5.Te-t @ BI.#avB Combo5.AddItem BI.#avB %@

Combo5.AddItem BI.midB Combo5.AddItem BI.avi<I.mpgB Combo5.AddItem BAll filesB !nd Sub ,rivate Sub Combo5?Change12 If "istInde- @ 4 Then ;ile5.,attern @ 1BI.#avB2 !lseIf "istInde- @ 5 Then ;ile5.,attern @ 1BI.midB2 !lseIf "istInde- @ 9 Then ;ile5.,attern @ 1BI.avi<I.mpgB2 !lse ;iel5.,attern @ 1BI.IB2 !nd If !nd Sub ,rivate Sub Dir5?Change12 ;ile5.,ath @ Dir5.,ath If Combo5."istInde- @ 4 Then ;ile5.,attern @ 1BI.#avB2 !lseIf Combo5."istInde- @ 5 Then ;ile5.,attern @ 1BI.midB2 !lseIf Combo5."istInde- @ 9 Then ;ile5.,attern @ 1BI.avi<I.mpgB2 !lse ;ile5.,attern @ 1BI.IB2 !nd If !nd Sub ,rivate Sub Drive5?Change12 Dir5.,ath @ Drive5.Drive !nd Sub ,rivate Sub !-it?Clic 12 !nd !nd Sub ,rivate Sub ;ile5?Clic 12 If Combo5."istInde- @ 4 Then ;ile5.,attern @ 1BI.#avB2 !lseIf Combo5."istInde- @ 5 Then ;ile5.,attern @ 1BI.midB2 !lseIf Combo5."istInde- @ 9 Then ;ile5.,attern @ 1BI.avi<I.mpgB2 !lse ;ile5.,attern @ 1BI.IB2 !nd If &>

If Pight1;ile5.,ath$ 52 RD BMB Then filenam @ ;ile5.,ath K BMB K ;ile5.;ile8ame !lse filenam @ ;ile5.,ath K ;ile5.;ile8ame !nd If Te-t5.Te-t @ filenam !nd Sub

,rivate Sub %%,layer?Clic 12 !nd Sub ,rivate Sub ,icture5?Clic 12 !nd Sub ,rivate Sub play?Clic 12 %%,layer.;ile8ame @ Te-t5.Te-t %%,layer.Command @ BOpenB %%,layer.Command @ B,layB %%,layer.h*ndDisplay @ videoscreen.h*nd !nd Sub ,rivate Sub stop?Clic 12 If %%,layer.%ode @ A9J Then !-it Sub If %%,layer.%ode RD A9A Then %%,layer.*ait @ True %%,layer.Command @ BStopB !nd If %%,layer.*ait @ True %%,layer.Command @ BCloseB !nd Sub

Lesson 1I: Creatin data&ase a""lications in VB! %art I


+isual basic allo#s us to manage databases created #ith different database program such as %S Access$ Dbase$ ,arado- and etc. In this lesson$ #e are not dealing #ith ho# to create database files but #e #ill see ho# #e can access database files in the +B environment. In the follo#ing e-ample$ #e #ill create a simple database application #hich enable one to bro#se customers' names. To create this application$ insert the data control into the ne# form. ,lace the data control some#here at the bottom of the form. 8ame the data control as data?navigator. To be able to use the data &1

control$ #e need to connect it to any database. *e can create a database file using any database application but I suggest #e use the database files that come #ith +B3. "et select 8*I8D.%DB as our database file. To connect the data control to this database$ double.clic the Database8ame property in the properties #indo# and select the above file$ i.e 8*I8D.%DB. 8e-t$ double.clic on the PecordSource property to select the customers table from the database. 6ou can also change the caption of the data control to anything but I use BClic to bro#se CustomersB here. After that$ #e #ill place a label and change its caption to Customer 8ame. "ast but not least$ insert another label and name it as cus?name and leave the label empty as customers' names #ill appear here #hen #e clic the arro#s on the data control. *e need to bind this label to the data control for the application to #or . To do this$ open the label's DataSource and select data?navigator that #ill appear automatically. One more thing that #e need to do is to bind the label to the correct field so that data in this field #ill appear on this label. To do this$ open the Data;ield property and select Contact8ame. 8o#$ press ;A and run the program. 6ou should be able to bro#se all the customers' names by clic ing the arro#s on the data control. The Design Interface.

The Puntime Interface

&#

6ou can also add other fields using e-actly the same method. ;or e-ample$ you can add adress$ City and telephone number to the database bro#ser.

Lesson 2>: Creatin data&ase a""lications in VB! %art II


In "esson 5G$ you have learned ho# to create a simple database application using data control. In this lesson$ you #ill #or on the same application but use &%

some slightly more advance commands. The data control support some methods that are useful in manipulating the database$ for e-ample$ to move the pointer to a certain location. The follo#ing are some of the commands that you can use to move the pointer around. data?navigator.PecordSet.%ove;irst ' %ove to the first record data?navigator.PecordSet.%ove"ast ' %ove to the last record data?navigator.PecordSet.%ove8e-t ' %ove to the ne-t record data?navigator.PecordSet.,revious ' %ove to the first record Inote: data?navigator is the name of data control In the follo#ing e-ample$ you shall insert four commands and label them as ;irst Pecord$ 8e-t Pecord$ ,revious Pecord and "ast Pecord . They #ill be used to navigator around the database #ithout using the data control. 6ou still need to retain the same data control 1from e-ample in lesson 5G2 but set the property +isible to no so that users #ill not see the data control but use the button to bro#se through the database instead. 8o#$ double?clic on the command button and ey in the codes according to the labels. ,rivate Sub Command9?Clic 12 dtaBoo s.Pecordset.%ove;irst !nd Sub ,rivate Sub Command5?Clic 12 dtaBoo s.Pecordset.%ove8e-t !nd Sub ,rivate Sub Command>?Clic 12 dtaBoo s.Pecordset.%ove,revious !nd Sub ,rivate Sub CommandJ?Clic 12 dtaBoo s.Pecordset.%ove"ast !nd Sub Pun the application and you shall obtain the interface belo# and you #ill be able to bro#se the database using the four command buttons.

&&

Lesson 21: Creatin VB data&ase a""lications usin A#- control


In "esson 5G and "esson 94$ #e have learned to build +B database applications using data control. Co#ever$ data control is not a very fle-ible tool as it could #or only #ith limited inds of data and must #or strictly in the +isual Basic environment. To overcome these limitations$ #e can use a much more po#erful data control in +B no#n as ADO control. ADO stands for Active7 data ob0ects. As ADO is Active7.based$ it could #or in different platforms 1different computer systems2 and different programming languages. Besides$ it could access many different inds of data such as data displayed in the Internet bro#sers$ email te-t and even graphics other than the usual relational and nonrelational database information. To be able to use ADO data control$ you need to insert it into the toolbo-. To do this$ simply press CtrlKT to open the components dialog bo- and select %icrosoft Active7 Data Control 3. After this$ you can proceed to build your ADO.based +B database applications. The follo#ing e-ample #ill illustrate ho# to build a relatively po#erful database application using ADO data control. ;irst of all$ name the ne# form as frmBoo Title and change its caption to Boo Tiles. ADO Application. Secondly$ insert the ADO data control and name it as adoBoo s and change its caption to boo . 8e-t$ insert the necessary labels$ te-t bo-es and command buttons. The runtime interface of this program is sho#n in the diagram belo#$ it allo#s adding and deletion as #ell as updating and bro#sing of data. &5

The properties of all the controls are listed as follo#: -or" 4a"e fr"Boo,Title Boo, Titles -or" Caption *A+6Application A+6 4a"e adoBoo,s 1abel1 4a"e lblApp 1abel1 Caption Boo, Titles 1abel # 4a"e lblTitle 1abel# Caption Title . 1abel% 4a"e lbl9ear 1abel% Caption 9ear 0ublished. 1abel& 4a"e lblI/B4 1abel& Caption I/B4. 1abe5 4a"e lbl0ubI+ 1abel5 Caption 0ublisher's I+. 1abel8 4a"e lbl/ubject 1abel8 Caption /ubject . Te tBo 1 4a"e t title Te tBo 1 Title +ata-ield Te tBo 1 adoBoo,s +ata/ource Te tBo # 4a"e t t0ub Te tBo # 9ear 0ublished +ata-ield Te tBo # adoBoo,s +ata/ource Te tBo % 4a"e t tI/B4 &8

Te tBo % I/B4 +ata-ield Te tBo % adoBoo,s +ata/ource Te tBo & 4a"e t t0ubI+ Te tBo & 0ubI+ +ata-ield Te tBo & adoBoo,s +ata/ource Te tBo 5 4a"e t t/ubject Te tBo 5 /ubject +ata-ield Te tBo 5 adoBoo,s +ata/ource Co""and Button1 c"d/ave 4a"e Co""and Button1 C/ave Caption Co""and Button# c"dAdd 4a"e Co""and Button# CAdd Caption Co""and Button% c"d+elete 4a"e Co""and Button% C+elete Caption Co""and Button& c"dCancel 4a"e Co""and Button& CCancel Caption Co""and Button5 c"d0rev 4a"e Co""and Button5 CR Caption Co""and Button8 c"d4e t 4a"e Co""and Button8 CS Caption Co""and Button= c"d$ it 4a"e Co""and Button= $C it Caption To be able to access and manage a database$ you need to connect the ADO data control to a database file. *e are going to use BIB"IO.%DB that comes #ith +B3. To connect ADO to this database file $ follo# the steps belo#: a2 Clic on the ADO control on the form and open up the properties #indo#. &=

b2 Clic on the ConnectionString property$ the follo#ing dialog bo- #ill appear.

#hen the dialog bo- appear$ select the 'se Connection String's Option. 8e-t$ clic build and at the Data "in dialog bo-$ double.Clic the option labeled %icrosoft =et >.A5 O"! DB provider.

After that$ clic the 8e-t button to select the file BIB"O.%DB. 6ou can clic on Te-t Connection to ensure proper connection of the database file. Clic O( to finish the connection. ;inally$ clic on the PecordSource property and set the command type to adCmd Table and Table name to Titles. 8o# you are really to use the database file. &?

8o#$ you need to #rite code for all the command buttons. After #hich$ you can ma e the ADO control invisible. ;or the Save button$ the program codes are as follo#: ,rivate Sub cmdSave?Clic 12 adoBoo s.Pecordset.;ields1BTitleB2 @ t-tTitle.Te-t adoBoo s.Pecordset.;ields1B6ear ,ublishedB2 @ t-t,ub.Te-t adoBoo s.Pecordset.;ields1BISB8B2 @ t-tISB8.Te-t adoBoo s.Pecordset.;ields1B,ubIDB2 @ t-t,ubID.Te-t adoBoo s.Pecordset.;ields1BSub0ectB2 @ t-tSub0ect.Te-t adoBoo s.Pecordset.'pdate !nd Sub ;or the Add button$ the program codes are as follo#: ,rivate Sub cmdAdd?Clic 12 adoBoo s.Pecordset.Add8e# !nd Sub ;or the Delete button$ the program codes are as follo#: ,rivate Sub cmdDelete?Clic 12 Confirm @ %sgBo-1BAre you sure you #ant to delete this recordUB$ vb6es8o$ BDeletion ConfirmationB2 If Confirm @ vb6es Then adoBoo s.Pecordset.Delete %sgBo- BPecord DeletedVB$ $ B%essageB !lse %sgBo- BPecord 8ot DeletedVB$ $ B%essageB !nd If !nd Sub ;or the Cancel button$ the program codes are as follo#: ,rivate Sub cmdCancel?Clic 12 t-tTitle.Te-t @ BB &@

t-t,ub.Te-t @ BB t-t,ubID.Te-t @ BB t-tISB8.Te-t @ BB t-tSub0ect.Te-t @ BB !nd Sub ;or the ,revious 1R2 button$ the program codes are ,rivate Sub cmd,rev?Clic 12 If 8ot adoBoo s.Pecordset.BO; Then adoBoo s.Pecordset.%ove,revious If adoBoo s.Pecordset.BO; Then adoBoo s.Pecordset.%ove8e-t !nd If !nd If !nd Sub ;or the 8e-t1D2 button$ the program codes are ,rivate Sub cmd8e-t?Clic 12 If 8ot adoBoo s.Pecordset.!O; Then adoBoo s.Pecordset.%ove8e-t If adoBoo s.Pecordset.!O; Then adoBoo s.Pecordset.%ove,revious !nd If !nd If !nd Sub In this sample$ you #ill create a ADO database application to manage your home library. ;irst of all$ create a database in %S Access and name home?"ibrary. In this database$ create a table #ith the follo#ing field names< Title: Author: ,ublisher: 6ear: Category: and save the table as boo title.mdb Design the Interface as follo#:

5>

(ey in the codes as follo#s: ,rivate Sub cmdCancel?Clic 12 t-tTitle.Te-t @ BB t-tAuthor.Te-t @ BB t-t,ublisher.Te-t @ BB t-t6ear.Te-t @ BB t-tCategory.Te-t @ BB !nd Sub ,rivate Sub cmdDelete?Clic 12 Confirm @ %sgBo-1BAre you sure you #ant to delete this recordUB$ vb6es8o$ BDeletion ConfirmationB2 If Confirm @ vb6es Then ado"ibrary.Pecordset.Delete %sgBo- BPecord DeletedVB$ $ B%essageB !lse %sgBo- BPecord 8ot DeletedVB$ $ B%essageB !nd If !nd Sub ,rivate Sub cmd!-it?Clic 12 !nd !nd Sub ,rivate Sub cmd8e#?Clic 12 ado"ibrary.Pecordset.Add8e# !nd Sub 51

,rivate Sub cmd8e-t?Clic 12 If 8ot ado"ibrary.Pecordset.!O; Then ado"ibrary.Pecordset.%ove8e-t If ado"ibrary.Pecordset.!O; Then ado"ibrary.Pecordset.%ove,revious !nd If !nd If !nd Sub ,rivate Sub cmd,revious?Clic 12 If 8ot ado"ibrary.Pecordset.BO;Nelco"e Then ado"ibrary.Pecordset.%ove,revious If ado"ibrary.Pecordset.BO; Then ado"ibrary.Pecordset.%ove8e-t 'egistration !nd If !nd If !nd Sub 1ogin ,rivate Sub cmdSave?Clic 12 ado"ibrary.Pecordset.;ields1BTitleB2 @ t-tTitle.Te-t ado"ibrary.Pecordset.;ields1BAuthorB2 @ t-tAuthor.Te-t ado"ibrary.Pecordset.'pdate +atabase !nd Sub

'egistered Hsers

Lesson 22: Creatin an Advance VB data&ase a""lication usin A#- control


In previous lessons$ you have learned to design database applications using data control and ADO control. Co#ever$ those are very simple and plain applications. In this lesson$ you #ill learn to create a more advance database application using ADO control. The application you are going to create is no#n as an electronic library. This electronic library #ill be able to accept users' registration as #ell as handling login command that re/uire the use of pass#ord$ thus enhancing the security aspect of the database. Basically$ the application #ill constitute a #elcome menu$ a registration menu$ a "ogin menu and the main database menu. The se/uence of the menus are illustrated as follo#: ;irst of all$ you need to design the *elcome menu. 6ou can follo# the e-ample as follo#: 5#

In this form$ you need to insert three command buttons and set their properties as follo#: -or" na"e "ainG"enu co""and button 1 c"d'egister 4a"e co""and button 1 'egister Caption co""and button # c"d1ogin 4a"e co""and button # 1ogin Caption co""and button % c"dCancel 4a"e co""and button % Cancel Caption The codes are as follo#: ,rivate Sub cmdCancel?Clic 12 !nd !nd Sub ,rivate Sub cmd"ogin?Clic 12 main?menu.Cide "ogin?form.Sho# !nd Sub ,rivate Sub cmdPegister?Clic 12 main?menu.Cide Pegister.Sho# !nd Sub If a ne# user clic the Pegister button$ the registration form #ill appear. An e-ample is illustrated as follo#:

5%

This registration forms consist of t#o te-t bo-es $ three command buttons and an ADO control. Their properties are set as follo#: -or" na"e 'egister te tbo 1 na"e t t4a"e te tbo # na"e t tpassword te tbo # I 0asswordChar co""and button 1 c"dConfir" na"e co""and button 1 Confir" Caption co""and button # c"dClear na"e co""and button # Clear Caption co""and button % c"dCancel na"e co""and button % Cancel Caption A+6 control na"e HserInfo note that the ,ass#ordChar of te-tbo- 9 is set as I #hich means users #ill not be able to see the actual characters they enter$ they #ill only see the I symbol. The codes are as follo#: ,rivate Sub cancel?Clic 1 2 !nd !nd Sub ,rivate Sub cmdClear?Clic 1 2 t-t8ame.Te-t @ BB t-tpass#ord.Te-t @ BB !nd Sub 5&

,rivate Sub cmdConfirm?Clic 12 'serInfo.Pecordset.;ields1BusernameB2 @ t-t8ame.Te-t 'serInfo.Pecordset.;ields1Bpass#ordB2 @ t-tpass#ord.Te-t 'serInfo.Pecordset.'pdate Pegister.Cide "ogin?form.Sho# !nd Sub ,rivate Sub ;orm?"oad12 'serInfo.Pecordset.Add8e# !nd Sub The "ogin menu is illustrated as follo#:

There are t#o te-t bo-es and a command button$ their properties are set as follo#: Te tbo 1 na"e t t4a"e Te tbo # na"e t tpassword Co""and button 1 c"d1ogin na"e Co""and button 1 1ogin Caption -or" na"e 1oginGfor" The codes are as follo#: ,rivate Sub cmd"ogin?Clic 12 Dim usrname As String Dim ps#ord As String Dim usernam As String Dim pss#ord As String Dim %sg As String 55

Pegister.'serInfo.Pefresh usrname @ t-t8ame.Te-t ps#ord @ t-tpass#ord.Te-t Do 'ntil Pegister.'serInfo.Pecordset.!O; If Pegister.'serInfo.Pecordset.;ields1BusernameB2.+alue @ usrname And Pegister.'serInfo.Pecordset.;ields1Bpass#ordB2.+alue @ ps#ord Then "ogin?form.Cide frm"ibrary.Sho# !-it Sub !lse Pegister.'serInfo.Pecordset.%ove8e-t !nd If "oop %sg @ %sgBo-1BInvalid pass#ord$ try againVB$ vbO(Cancel2 If 1%sg @ 52 Then "ogin?form.Sho# t-t8ame.Te-t @ BB t-tpass#ord @ BB !lse !nd !nd If !nd Sub The main database menu is illustrated as follo#:

58

The properties of all controls are listed in the table belo#: -or" na"e fr"1ibrary A+6 control na"e ado1ibrary A+6 visible -alse Te tBo 1 na"e t tTitleA Te tBo # na"e t tAuthor Te tBo %na"e t t0ublisher Te tBo & na"e t t9ear Te tBo 5 na"e t tCategory Co""and button 1 c"d/ave na"e Co""and button 1 C/ave caption Co""and button # c"d4ew na"e Co""and button # C4ew caption Co""and button % c"d+elete na"e Co""and button % C+elete caption Co""and button & c"dCancel na"e Co""and button & CCancel caption Co""and button 5 c"d4e t 5=

na"e Co""and button 5 4Ce t caption Co""and button 8 c"d0revious na"e Co""and button 8 C0revious caption Co""and button = c"d$ it na"e Co""and button = $C it caption The codes are as follo#: ,rivate Sub cmdCancel?Clic 12 t-tTitle.Te-t @ BB t-tAuthor.Te-t @ BB t-t,ublisher.Te-t @ BB t-t6ear.Te-t @ BB t-tCategory.Te-t @ BB !nd Sub ,rivate Sub cmdDelete?Clic 12 Confirm @ %sgBo-1BAre you sure you #ant to delete this recordUB$ vb6es8o$ BDeletion ConfirmationB2 If Confirm @ vb6es Then ado"ibrary.Pecordset.Delete %sgBo- BPecord DeletedVB$ $ B%essageB !lse %sgBo- BPecord 8ot DeletedVB$ $ B%essageB !nd If !nd Sub ,rivate Sub cmd!-it?Clic 12 !nd !nd Sub ,rivate Sub cmd8e#?Clic 12 ado"ibrary.Pecordset.Add8e# !nd Sub ,rivate Sub cmd8e-t?Clic 12 If 8ot ado"ibrary.Pecordset.!O; Then ado"ibrary.Pecordset.%ove8e-t If ado"ibrary.Pecordset.!O; Then ado"ibrary.Pecordset.%ove,revious !nd If !nd If 5?

!nd Sub ,rivate Sub cmd,revious?Clic 12 If 8ot ado"ibrary.Pecordset.BO; Then ado"ibrary.Pecordset.%ove,revious If ado"ibrary.Pecordset.BO; Then ado"ibrary.Pecordset.%ove8e-t !nd If !nd If !nd Sub ,rivate Sub cmdSave?Clic 12 ado"ibrary.Pecordset.;ields1BTitleB2.+alue @ t-tTitle.Te-t ado"ibrary.Pecordset.;ields1BAuthorB2.+alue @ t-tAuthor.Te-t ado"ibrary.Pecordset.'pdate !nd Sub

5@

Вам также может понравиться