vb6 tutorials

38
Lesson1: Introduction 1.1 A brief description of Visual Basic  VISUAL BASIC is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. It is a fairly easy programming language to learn. he codes loo! a bit li!e "nglish #anguage. Different soft$are companies produced different version of BASIC% such as &icrosoft BASIC% (IC)BASIC% *+BASIC% and IB& BASICA and so on. ,IS(A# BASIC is a ,IS(A# and events driven rogramming #angua ge. hese are the main divergence from the old BASIC. In BASIC% programming is done in a tet-only environment and the program is eecuted 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 actions 1events2.herefore% a ,IS(A# BASIC rogram is made up of many subprograms% each has its o$n program codes% and each can be eecuted indepently and at the same time each can be lin!ed together in one $ay or another. 1.2 The Visual Basic Eniron!ent  On start up% ,i sual Basic 3.4 $ill display the follo$ing dialog bo as sho$n in figure 5.5. 6o u can choose to start a ne$ pro0ect% open an eisting pro0ect or select a list of recently opened programs. A pro0ect is a collection of files that ma!e up your application. here are various types of applications $e could create7 ho$ever% $e shall concentrate on creating Standard "8" programs 1"8" means eecutable program2. 9o$% cl ic! on the Standard "8" icon to go into the actual ,B programming environment.

Upload: romeofatima

Post on 08-Jan-2016

131 views

Category:

Documents


14 download

DESCRIPTION

VB6

TRANSCRIPT

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 1/38

Lesson1: Introduction

1.1 A brief description of Visual Basic 

VISUAL BASIC is a high level programming language evolved from the earlier DOSversion called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code.It is a fairly easy programming language to learn. he codes loo! a bit li!e "nglish#anguage. Different soft$are companies produced different version of BASIC% such as&icrosoft BASIC% (IC)BASIC% *+BASIC% and IB& BASICA and so on.

,IS(A# BASIC is a ,IS(A# and events driven rogramming #anguage. hese are themain divergence from the old BASIC. In BASIC% programming is done in a tet-onlyenvironment and the program is eecuted se/uentially. In ,IS(A# BASIC% programmingis done in a graphical environment. Because users may clic! on a certain ob0ectrandomly% so each ob0ect has to be programmed indepently to be able to response to thoseactions 1events2.herefore% a ,IS(A# BASIC rogram is made up of many subprograms%

each has its o$n program codes% and each can be eecuted indepently and at the sametime each can be lin!ed together in one $ay or another.

1.2 The Visual Basic Eniron!ent 

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 eisting pro0ect or select a list of recentlyopened programs. A pro0ect is a collection of files that ma!e up your application. here

are various types of applications $e could create7 ho$ever% $e shall concentrate oncreating Standard "8" programs 1"8" means eecutable program2. 9o$% clic! on the

Standard "8" icon to go into the actual ,B programming environment.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 2/38

In figure 5.:% the ,isual Basic "nvironment consists of the

• he Blan" #or! $indo$ $hich you can design your application's interface.

• he $ro%ect $indo$ displays the files that are created in your application.

• he $roperties $indo$ $hich displays the properties of various controls and

ob0ects that are created in your applications.

It also includes a Toolbo& that consists of all the controls essential for developing a ,BApplication. Controls are tools such as boes% buttons% labels and other ob0ects dra$ on aform to get input or displa' output. hey also add visual appeal.

#i(ure 1.2: The Visual Basic Eniron!ent 

Lesson 2: Buildin( a Visual Basic Application

2.1 Creatin( )our #irst Application 

In this section% $e are not going into the technical aspect of ,B programming7 0ust have afeel of it. 9o$% you can try out the eamples belo$;

E&a!ple 2.1.1 is a simple program. <irst of all% you have to launch &icrosoft ,isualBasic. 9ormally% a default form #or!1 $ill be available for you to start your ne$

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 3/38

 pro0ect. 9o$% double clic! on form5% the source code $indo$ for form5 $ill appear.Don't $orry about the beginning and the end statements 1i.e. $riate Sub #or!

Load.......End Sub.27 =ust !ey in the lines in bet$een the above t$o statements eactly asare 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 #or!1.sho* statement

li!e in "ample :5.: and "ample :.5.>. ry them out.

"ample :.5.5 

rivate Sub <orm?#oad 

<or i@5 to  print ellonet i

"nd Sub

"ample :.5.: 

rivate Sub <orm?#oad 

<orm5.sho$<or i@5 to

 print ellonet i

"nd Sub

"ample :.5.> 

rivate Sub <orm?#oad 

<orm5.sho$<or i@5 to54 print inet i

"nd Sub

2.2 Steps in Buildin( a Visual Basic Application 

Step 5 Dra$ the interface Step : Set Properties Step > +rite the events code 

E&a!ple 2.1 

his program is a simple program that calculates the volume of a cylinder. #et design theinterface;

<irst of all% go to the properties $indo$ and change the form caption to ,olume ofCylinder. hen dra$ three label boes and change their captions to Base +adius, hei(ht 

and olu!e respectively. After that% dra$ three et Boes and clear its tet contents sothat you get three empty boes. 9amed the tet boes as radius, h(ht -$e cannot usehei(ht as it is the built-in control name of ,B and olu!e respectively. #astly% insert a

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 4/38

command button and change its caption to/.0. And its name to /0. 9o$ save the pro0ect as cylinder.vbp and the form as cylinder.vbp as $ell. +e shall leave out the codesat the moment $hich you shall learn it in lesson>.

E&a!ple 2.2 

Designing an attractive and user friendly interface should be the first step in constructinga ,B program. o illustrate% let's loo! at the calculator program.

 9o$% please follo$ the follo$ing steps to design the calculator interface.

• esiEe the form until you get the siEe you are satisfied $ith.

• *o to the properties $indo$ and change the default caption to the caption you

$ant% such as >: Calculator-----Designed by ,!lie$.• Change other properties of the form% such as bac!ground color% foreground color%

 border style. I recommend you set the follo$ing properties for <orm5 for thiscalculator program;

Border St'le <ied Single

a&Button <alse

!inButton rue

  hese properties $ill ensure that the users cannot resiEe or maimiEe yourcalculator

$indo$% but able to minimiEe the $indo$.• Dra$ the Display anel by clic!ing on the #abel button and and place your mouse

on the form. Start dra$ing by pressing do$n your mouse button and drag it along.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 5/38

• Clic! on the panel and the corresponding properties $indo$ $ill appear. Clear the

default label so that the caption is blan! 1because the display panel is supposed tosho$ the number as $e clic! on the number button2. It is good to set the bac!ground color to a bright color $hile the foreground color should besomething li!e blac!... 1<or easy vie$ing2. Change the name to display as I am

going to use it later to $rite codes for the calculator.•  9o$ dra$ the command buttons that are necessary to operate a calculator. I

suggest you follo$ eactly $hat is sho$n in the image above.• est runs the pro0ect by pressing <. If you are satisfied $ith the appearance% go

ahead to save the pro0ect. At the same time% you should also save the file thatcontains your form.

 9o$% I !no$ you are very !een to !no$ ho$ to $rite the code so that the calculator is$or!ing.lease refer to my sample ,B programs for the source codes.

Lesson : 3ritin( the Codes

 9o$ $e shall attempt to $rite the codes for the cylinder program.

 9o$% double clic! on the O.) button and enter the codes bet$een rivate Sub O)?Clic!12 and "nd Sub

$riate Sub /04Clic" -  r 5 Val -radius.Te&t h 5 Val -h(ht.Te&t $i 5 22 6 7  5 pi 8 -r 9 2 8 h olu!e.Te&t5 ST+- End Sub 

+hen you run the program% you should be able to see the interface as sho$n above. Ifyou enter a value each in the radius bo and the height bo% then clic! O)% the value ofthe ,olume $ill be displayed in the volume bo.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 6/38

I shall attempt to eplain the above source program to ne$comers in ,isual Basic 1If youare a veteran% you can s!ip this part2. #et me describe the steps using pseudo codes asfollo$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  alculate the volume using formula Output the results to the !olume text box   "nd of Procedure 

he synta radius#$ext consists of t$o parts7 radius is the na!e of tet bo $hile

Te&t is the tetual contents of the tet bo. *enerally% the synta is; /b%ect.$ropert' In our eample% the ob0ects are radius% hght and volume% each having text as their property. Ob0ect and property is separated by a period 1or dot2.he contents of atet bo can only be displayed in tetual form% or in programming term% as string.o convert the contents of a tet bo to a numeric value so that mathematicaloperations can be performed% you have to use the function !al# <inally% In order todisplay the results in a tet bo% $e have to perform the reverse procedure% that is%to convert the numeric value bac! to the tetual form% using the function Str. 

I shall also eplain the synta that defines the sub procedure $riate Sub

/04clic".  Private Sub here means that the parameters% values and formulas thatare used here belong only to the O) sub procedure 1an ob0ect by itself2.heycannot be used by other sub procedures or modules. O)?Clic! defines $hat !indof action the sub procedure O) $ill response .ere% the action is mouse clic!.here is other !ind of actions li!e !ey press% !ey up% !ey do$n and etc that I amgoing to due $ith in other lessons. 

Lesson ;<3or"in( *ith Controls

Before $riting an event procedure for a control to response to a user's action% you have toset certain properties for the control to determine its appearance and ho$ it $ill $or!

$ith the event procedure. 6ou can set the properties of the controls in the properties$indo$s. I am not going into the details on ho$ to set the properties. o$ever% I $ouldli!e to stress a fe$ important points about setting up the properties.

•  6ou should set the Caption $ropert' of a control clearly so that a user !no$s

$hat to do $ith that command. <or eample% in the calculator program% all thecaptions of the command buttons such as F% - % &C% & are commonly found inan ordinary calculator% a user should have no problem in manipulating the buttons.

• 6ou should set a meaningful name for the =a!e $ropert' because it is easier for

you to $rite and read the event procedure and easier to debug your program later.• Another property that is important is $hether you $ant your control to be isible 

or not at start up. his property can only set to be true or false.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 7/38

• One more important property is $hether the control is enabled or not.

Lesson >: ana(in( Visual Basic ?ata

There are many types of data $e come across in our daily life. <or eample% $e need tohandle data such as names% addresses% money% date% stoc! /uotes% statistics and etceveryday. Similarly in ,isual Basic% $e are also going to deal $ith these !inds of data.o$ever% to be more systematic% ,B divides data into different types.

>.1 T'pes of Visual Basic ?ata 

>.1.1 =u!eric ?ata 

 9umeric 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 G types% they are summariEed in able 3.5

Table >.1: =u!eric ?ata T'pes

T'pe Stora(e +an(e of Values

Byte 5 byte 4 to :

Integer : bytes ->:%G3H to >:%G3G

#ong bytes -:%5G%H>%3H to :%5G%H>%3H

Single bytes ->.4:H:>"F>H to -5.45:JH"- for negative values5.45:JH"- to >.4:H:>"F>H for positive values.

Double H bytes

-5.GJG3J>5>H3:>:eF>4H to -.J433H5:G"->: for negativevalues.J433H5:G"->: to 5.GJG3J>5>H3:>:eF>4H for positivevalues.

Currency H bytes -J::%>>G%:4>%3H%GG.H4H to J::%>>G%:4>%3H%GG.H4G

Decimal 5: bytesFK- GJ%::H%53:%5%:3%>>G%J>%>%J4%>> if no decimal is useFK- G.J::H53:5:3>>GJ>>J4>> 1:H decimal places2.

>.1.2 =on<nu!eric ?ata T'pes 

he nonnumeric data types are summariEed in able .:

Table >.2: =onnu!eric ?ata T'pes

?ata T'pe Stora(e +an(e

String1fiedlength2

#ength of string 5 to 3%44 characters

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 8/38

String1variablelength2

#ength F 54 bytes

4 to : billion characters

Date H bytes =anuary 5% 544 to December >5% JJJJ

Boolean : bytes rue or <alse

Ob0ect bytes Any embedded ob0ect

,ariant1numeric2 53 bytes Any value as large as Double,ariant1tet2 #engthF:: bytes Same as variable-length string

>.1. Suffi&es for 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 eample% $ecan use num@5.>4HJL for a Double type data. Some of the suffies are displayed in able.>.

Table >.

Suffi& ?ata T'pe

M #ong

N Single

L Double

Currency

In addition% $e need to enclose string literals $ithin t$o /uotations and date and time

literals $ithin t$o L sign. Strings can contain any characters% including numbers. hefollo$ing are fe$ eamples;

&ember 9ame@urban% =ohn.el9umber@5H44-J44-HHH-GGG#ast Day@L>5-Dec-44L"pime@L5:;44 amL

>.2 ana(in( Variables 

,ariables are li!e mail boes in the post office. he contents of the variables changes

every no$ and then% 0ust li!e the mail boes. In term of ,B% variables are areas allocated by the computer memory to hold data. #i!e the mail boes% each variable must be given aname. o name a variable in ,isual Basic% you have to follo$ a set of rules.

>.2.1 Variable =a!es 

he follo$ing are the rules $hen naming the variables in ,isual Basic

• It must be less than : characters

•  9o spacing is allo$ed

• It must not begin $ith a number

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 9/38

• eriod is not permitted

"amples of valid and invalid variable names are displayed in able .

Table >.;

Valid =a!e Inalid =a!e

&y?Car &y.Car

his6ear 59e$Boy

#ong?9ame?Can?be(S" eMis<ather PM is not acceptable

 

>.2.2 ?eclarin( Variables 

In ,isual Basic% one needs to declare the variables before using them by assigning names

and data types. hey are normally declared in the general section of the codes' $indo$susing the ?i! statement.he format is as follo$s;

Dim variable9mae as Dataype

"ample .5

Dim pass$ord As StringDim your 9ame As StringDim firstnum As Integer

Dim secondnum As IntegerDim total As IntegerDim doDate As Date

6ou may also combine them in one line% separating each variable $ith a comma% asfollo$s;

Dim pass$ord As String% your 9ame As String% firstnum As Integer...

If data type is not specified% ,B $ill automatically declare the variable as a ,ariant.<or string declaration% there are t$o possible formats% one for the variable-length

string and another for the fied-length string. <or the variable-length string% 0ust use thesame format as eample .5 above. o$ever% for the fied-length string% you have to usethe format as sho$n belo$;

 Dim VariableName as String * n% $here n define the number of characters the string canhold.

"ample .:;

Dim your9ame as String P 54

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 10/38

your9ame can holds no more than 54 Characters.

Lesson @: 3or"in( *ith Variables

@.1 Assi(nin( Values to Variables 

After declaring various variables using the Dim statements% $e can assign values to thosevariables.he general format of an assignment is

,ariable@"pressionhe variable can be a declared variable or a control property value. he epression could be a mathematical epression% a number% a string% a boolean value1true or false2 and etc.he follo$ing are some eamples;

first9umber@544

second9umber@first9umber-JJuser9ame@=ohn #yanuserpass.et @ pass$ord#abel5.,isible @ rueCommand5.,isible @ false#abel.Caption @ tetbo5.ethird9umber @ ,al1usernum5.et2total @ first9umber F second9umberFhird9umber

@.2 /perators in Visual Basic

In order to compute inputs from users and to generate results% $e need to use variousmathematicaloperators. In ,isual Basic% ecept for F and -% the symbols for the operators are differentfrom normal mathematical operators%as sho$n in able 3.5.

able 3.5

/perator athe!atical function E&a!ple

Q "ponential :Q@53P &ultiplication P>@5:

K Division 5:K@>

&od&odulus1return theremainder from aninteger division2

5 &od @>

RInteger Division1discardsthe decimal places2

5JR@

F or M String concatenation,isualMBasic@,isualBasic

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 11/38

 

"ample 3.5;

[email protected]@et:.etyour9ame@first9ameFsecond9amenumber5@val1et>.et2number:@val1et.et2number>@num5P1num:Q>2number@number> &od :number@numberRnumber5otal@number5Fnumber:Fnumber>FnumberFnumberAverage@otalK

In lesson% $e $ill see ho$ do $e use operators in $riting the ,B programs codes.

Lesson 7 : Controllin( $ro(ra! #lo*

7.1 Conditional /perators

o control the ,B program flo$% $e can use various conditional operators. Basically%they resemble mathematical operators. Conditional operators are very po$erful tools%they let the ,B program compare data values and then decide $hat action to ta!e%$hether to eecute a program or terminate the program and etc. hese operators aresho$n in able G.5.

able G.5; Conditional Operators

/perator eanin(

@ "/ual to

&ore than

T #ess han

@ &ore than and e/ualT@ #ess than and e/ual

T 9ot "/ual to

P 6ou can also compare strings $ith the above operators. o$ever% there are certain rulesto follo$s; (pper case letters are less than lo$ercase letters% ATBTCTD.......TUand number are less than letters.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 12/38

7.2 Lo(ical /perators

In addition to conditional operators% there are a fe$ logical operators $hich offer added po$er to the ,B programs. here are sho$n in able G.:.

able G.:

/perator eanin(

And Both sides must be true

or One side or other must be true

8or One side or other must be true but not both

 9ot 9egates truth

 

7. Usin( If.....Then.....Else State!ents *ith /preatorso effectively control the ,B program flo$% $e shall use If...hen..."lse statementtogether $ith the conditonal operators and logical operators.he general format for the if...then...else statement isIf   conditions Then 

,B epressions

Else 

,B epressions

End If 

P any If..hen.."lse statement must end $ith "nd If. Sometime it is not necessary to use"lse.

"ample;

rivate Sub O)?Clic!12

firstnum @ ,al1usernum5.et2

secondnum @ ,al1usernum:.et2total @ ,al1sum.et2If total @ firstnum F secondnum And ,al1sum.et2 T 4 hencorrect.,isible @ rue$rong.,isible @ <alse"lsecorrect.,isible @ <alse$rong.,isible @ rue"nd If

"nd Sub

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 13/38

#or !ore e&a!ple on If...Then...Else, Clic" on the

Sa!ple1 andsa!ple2 pro(ra! here.

Lesson : ore /n $ro(ra! Control8.1 Select Case

If you have a lot of conditional statements% using If..hen.."lse could be very messy. <ormultiple conditional statements% it is better to use Select Case 

he format is ;

Select Case epression

Case value5

Bloc! of one or more ,B statementsCase value:

Bloc! of one or more ,B StatementsCase value>

Bloc! of one or more ,B statementsCase value

.

.

.Case "lse

Bloc! of one or more ,B Statements

"nd Select 

P he data type specified in epression must match that of Case values.

8.2 Examples

"ample H.5 

' "amination *rades

Dim grade As String

rivate Sub Compute?Clic!1 2

[email protected]

Select Case grade

Case Aresult.Caption@igh Distinction

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 14/38

  Case A-result.Caption@Distinction

Case Bresult.Caption@Credit

Case C

result.Caption@assCase "lseresult.Caption@<ail

"nd Select

Please note that grade is a string% so all the case values such as A are of String datatype.

"ample H.: 

Dim mar! As Singlerivate Sub Compute?Clic!12'"amination &ar!s

mar! @ mr!.et

Select Case mar!

Case Is @ H

comment.Caption @ "cellence

Case Is @ G4

comment.Caption @ *ood

Case Is @ 34

comment.Caption @ Above Average

Case Is @ 4

comment.Caption @ Average

Case "lse

comment.Caption @ 9eed to $or! harder

"nd Select

"nd Sub

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 15/38

P 9ote $e use the !ey$ord Is here to impose the conditions. his is generally used fornumeric data.

"ample H.> 

"ample H.: could be re$ritten as follo$s;

Dim mar! As Singlerivate Sub Compute?Clic!12'"amination &ar!s

mar! @ mr!.et

Select Case mar!

Case 4 to J

comment.Caption @ 9eed to $or! harder

Case 4 to J

comment.Caption @ Average

Case 34 to 3J

comment.Caption @ Above Average

Case G4 to H

comment.Caption @ *ood

Case "lse

comment.Caption @ "cellence

"nd Select

"nd Sub

Lesson D: Loopin(

,isual Basic allo$s a procedure to be repeated as many times as long as the processorcould support. his is generally called looping .

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 16/38

9.1 Do Loop

he format are

a2 Do +hile condition

Bloc! of one or more ,B statements

#oop

 b2 DoBloc! of one or more ,B statements

#oop +hile condition

c2 Do (ntil conditionBloc! of one or more ,B statements

#oop

d2 DoBloc! of one or more ,B statements

#oop (ntil condition

"ample J.5

Do $hile counter T@5444

num.et@counter

counter @counterF5

#oop

P he above eample $ill !eep on adding until counter 5444.

he above eample can be re$ritten as

Do

num.et@countercounter@counterF5

#oop until counter5444

9.2 For....Next Loop

he format is;

<or  counter@start9umber to end9umber 1Step increment2

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 17/38

  One or more ,B statements

 9et 

"ample;

1a2 <or counter@5 to 54

display.et@counter

 9et

1b2 <or counter@5 to 5444 step 54

counter@counterF5

 9et

1c2 <or counter@5444 to step -

counter@counter-54

 9et

Lesson 1: Introduction to VB #unctions< $art I

<unctions are similar to normal procedures but the main purpose of the functions is toaccept certain inputs and pass them on to the main program to finish the eecution. heyare t$o types of function% the built-in functions1or internal functions2 and the functionscreated by the programmers.

he general format of a function is

function9ame1arguments2 $here arguments 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&sgBo1 2 and InputBo 1 2 functions.

10.1 MsgBox ( ) Fuct!o

he ob0ective of &sgBo is to produce a pop-up message bo and prompt the user toclic! on a command button before he Kshe can continues. his message bo format is asfollo$s;

your&sg@&sgBo1rompt% Style ,alue% itle2

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 18/38

 he first argument% rompt% $ill display the message in the message bo. he Style,alue $ill determine $hat type of command buttons appear on the message bo% pleaserefer able 54.5 for types of command button displayed. he itle argument $ill displaythe title of the message board.

Table 1.1: St'le Values

St'le Value =a!ed Constant Buttons ?ispla'ed

4 vbO!Only O! button

5 vbO!Cancel O! and Cancel buttons

: vbAbortetryIgnore Abort% etry and Ignore buttons.

> vb6es9oCancel 6es% 9o and Cancel buttons

vb6es9o 6es and 9o buttons

vbetryCancel etry and Cancel buttons

+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 namesconstant $here you can select one of them.

eample; your&sg@&sgBo1 Clic! O) to roceed% 5% Startup &enu2

and your&sg@&sg1Clic! O) to roceed. vbO!Cancel%Startup &enu2

are the same.

your&sg is a variable that holds values that are returned by the &sgBo 1 2 function. hevalues are determined by the type of buttons being clic!ed by the users. It has to bedeclared as Integer data type in the procedure or in the general declaration section. able54.: sho$s the values% the corresponding named constant and buttons.

Table 1.2 : +eturn Values and Co!!and Buttons

 Value =a!ed Constant Button Clic"ed

5 vbO! O! button

: vbCancel Cancel button

> vbAbort Abort button vbetry etry button

vbIgnore Ignore button

3 vb6es 6es button

G vb9o 9o button

"ample 54.5

i. he Interface;

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 19/38

  6ou dra$ three command buttons and a label as sho$n in <igure 54.5

ii. he procedure for the test button;

rivate Sub est?Clic!12 Dim testmsg As Integertestmsg @ &sgBo1Clic! to test% 5% est message2If  testmsg @ 5 hen Display.Caption @ esting Successful"lse Display.Caption @ esting fail

"nd If  

"nd Sub 

+hen a user clic! on the test button% the image li!e the one sho$n in <igure 54.: $illappear. As the user clic! on the O) button% the message esting sucessful $ill bediplayed and $hen heKshe clic!s on the Cancel button% the message esting fail $ill bedisplayed.

<igure 54.:

o ma!e the message bo loo!s more sophisticated% you can add an icon besides themessage. he are four types of icons available in ,B as sho$n in able 54.>

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 20/38

 able 54.>

Value =a!ed Constant Icon

53 vbCritical

>: vbuestion

H vb"clamation

3 vbInformation

"ample 54.:

In this eample% the follo$ing message bo $ill be displayed;

<igure 54.>

6ou could dra$ the same Interface as in eample 54.5 but modify the codes as follo$s;

rivate Sub test:?Clic!12Dim test&sg: As Integertest&sg: @ &sgBo1Clic! to est% vb6es9oCancel F vb"clamation% est &essage2If test&sg: @ 3 hen display:.Caption @ esting successful

"lseIf  test&sg: @ G hen display:.Caption @ Are you sureV"lse display:.Caption @ esting fail"nd If  

"nd Sub 

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 21/38

10.2 "#e $putBox( ) Fuct!o

An InputBo1 2 function $ill display a message bo $here the user can enter a value or amessage in the form of tet. he format is

my&essage@InputBo1rompt% itle% default?tet% -position% y-position2

my&essage is a variant data type but typically it is declared as string% $hich accept themessage input bu the users.he arguments are eplained as follo$s;

• rompt - he message displayed normally as a /uestion as!ed.

• itle - he title of the Input Bo.

• default-tet - he default tet that appears in the input field $here users can use it

as his intended input or he may change to the message he $ish to !ey in.• -position and y-position - the position or the coordinate of the input bo.

"ample 54.>i. he Interface <igure 54.

ii. he procedure for the O) button

rivate Sub O)?Clic!12Dim user&sg As Stringuser&sg @ InputBo1+hat is your messageV% &essage "ntry <orm% "nter yourmessge here% 44% G442If  user&sg T hen message.Caption @ user&sg"lse message.Caption @ 9o &essage"nd If  

"nd Sub

+hen a user clic! the O) button% the input bo as sho$n in <igure 54. $ill appear. After user entering the message and clic! O)% the message $ill be displayed on the caption% ifhe clic! Cancel% 9o message $ill be displayed.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 22/38

Lesson 11: Introduction to VB #unctions< $art II

11.1 Creatin( )our /*n #unctions 

he general format of a function is as follo$s;

ublic <unction function9ame 1Arg As dataype%..........2 As dataype

or

rivate <unction function9ame 1Arg As dataype%..........2 As dataype

P ublic indicates that the function is applicable to the $hole program andrivate indicates that the function is only applicable to a certain module or procedure.

"ample 55.5

In this eample% a user can calculate future value of a certain amount of money he hastoday based on the interest rate and the number of years from no$1supposing he $illinvest this amount of money some$here2. he calculation is based on the compoundinterest rate.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 23/38

ublic <unction <,1, As ,ariant% i As ,ariant% n As ,ariant2 As ,ariant'<ormula to calculate <uture ,alue1<,2', denotes resent ,alue<, @ , P 15 F i K 5442 Q n

"nd <unction

rivate Sub compute?Clic!12'his procedure $ill calculate <uture ,alueDim <uture,al As ,ariantDim resent,al As ,ariantDim interest As ,ariantDim period As ,ariantresent,al @ ,.etinterest @ rate.et period @ years.et

<uture,al @ <,1resent,al% interest% period2&sgBo 1he <uture ,alue is M <uture,al2"nd Sub

"ample 55.:

he follo$ing program $ill automatically compute eamination grades based on themar!s that a student obtained.

ublic <unction grade1mar! As ,ariant2 As StringSelect Case mar!Case Is @ H4grade @ ACase Is @ G4grade @ BCase Is @ 34

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 24/38

grade @ CCase Is @ 4grade @ DCase Is @ 4grade @ "

Case "lsegrade @ <"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 #unctions #or S E&cel

12.2 The =eeds to Create User<?efined #unctions in S<E&cel 

6ou can create your o$n functions to supplement the built-in functions in &icrosoft"cel spreadsheet $hich are /uite limited. hese functions could be very useful and po$erful if you !no$ ho$ to program them properly. One main reason $e need to createuser defined functions is to enable us to customiEe our spreadsheet environment forindividual needs. <or eample% $e might need a function that could calculatecommissions payment based on the sales volume% $hich is /uite difficult if notimpossible by using the built-in function alone. #ets loo! at the table belo$;

Table 12.1: Co!!issions $a'!ent Table

Sales ,olume1W2 Commissons

T44 >X

T5444 3X

T:444 JX

T444 5:X

444 5X

In the above table% if a saleman attain a sale volume of W3444% he $ill be paidW34445:X@WG:4.44. A visual basic function to calculate the commissions could be$ritten asfollo$s;

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 25/38

<unction Comm1Sales?, As ,ariant2 as ,ariantIf Sales?, T44 henComm@Sales?,P4.4>"lseif Sales?,@44 and Sales?,T5444 henComm@Sales?,P4.43

"lseif Sales?,@5444 and Sales?,T:444 henComm@Sales?,P4.4J"lseif Sales?,@:44 and Sales?,T444 henComm@Sales?,P4.5:"lseif Sales?,@444 henComm@Sales?,P4.5"nd If"nd <unction

12.2 Usin( icrosoft E&cel Visual Basic Editor 

o create (ser Defined functions in &S "cel% you can clic! on tools% select macro andthen clic! on ,isual Basic "ditor as sho$n in <igure 5:.5

#i(ure 12.1: Insertin( s4E&cel Visual Basic Editor

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 26/38

(pon clic!ing the ,isual Basic "ditor% the ,B "ditor $indo$s $ill appear as sho$n infigure 5:.:. o create a function% type in the function as illustrated in section 5:.5 above

After typing% save the

  file and then return to the "cel $indo$s.

#i(ure 12.2 : The VB Editor

In the "cel $indo$s% type in the titles Sales ,olume and Commissions in any t$o cells.By refering to figure 5:.>% !ey-in the Comm function at cell C and by referencing thevalue in cell B% using the format Comm1B2. Any value appear in cell B $ill pass thevalue to the Comm function in cell C. <or the rest of the ro$s% 0ust copy the formula bydraging the bottom right corner of cell C to the re/uired cells% and a nice and neat table

that sho$ the commisions $ill automatically appear. It can also be updated anytime

#i(ure 12.: S E&cel 3indo*s< Sales Volu!e

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 27/38

Lesson 1: Arra's

1%.1 $tro&uct!o to 'rras

By definition% an array is a list of variables% all $ith the same data type and name. +hen$e $or! $ith a single item% $e only need to use one variable. o$ever% if $e have a listof items $hich are of similar type to deal $ith% $e need to declare an array of variablesinstead of using a variable for each item. <or eample% if $e need to enter one hundrednames% instead of declaring one hundred different variables% $e need to declare only onearray. +e differentiate each item in the array by using subscript% the inde value of eachitem% for eample name152% name1:2%name1>2 .......etc.

1%.2 Declar!g 'rras+e could use ublic or Dim statement to declare an array 0ust as the $ay $e declare asingle variable. he ublic statement declares an array that can be used throughout anapplication $hile the Dim statement declare an array that could be used only in a local procedure.

he general format to declare an array is as follo$;

Dim array9ame1subs2 as dataype

$here subs indicates the last subscript in the array.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 28/38

E&a!ple 1.1 

Dim Cus9ame1542 as String

$ill declare an array that consists of 54 elements if the statement Option Base 5 appear in

the declaration area% starting from Cus9ame152 to Cus9ame1542. Other$ise% there $ill be55 elements in the array starting from Cus9ame142 through to Cus9ame1542

E&a!ple 1.2 

Dim Count1544 to 442 as Integer

declares an array that consists of the first element starting from Count15442 and ends atCount1442

1%.% Sample rograms1i2

The Interface 

The codes 

Dim student9ame1542 As String Dim num As Integer  

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 29/38

rivate Sub add9ame12 <or num @ 5 o 54 student9ame1num2 @ InputBo1"nter the student name% "nter 9ame% % 544% 442 If student9ame1num2 T hen <orm5.rint student9ame1num2 

"lse "nd "nd If  

 9et "nd Sub 

rivate Sub "it?Clic!12 "nd "nd Sub 

rivate Sub Start?Clic!12 <orm5.Cls add9ame 

"nd Sub 

he above program accepts data entry through an input bo and displays the entries in theform itself. As you can see% this program $ill only allo$s a user to enter 54 names eachtime he clic! on the start button.

1ii2

he Interface

The Codes 

Dim student9ame1542 As String Dim num As Integer  

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 30/38

rivate Sub add9ame1 2 <or num @ 5 o 54 student9ame1num2 @ InputBo1"nter the student name2 #ist5.AddItem student9ame1num2  9et 

"nd Sub 

rivate Sub Start?Clic!12 add9ame 

"nd Sub 

The aboe pro(ra! accepts data entries throu(h an

InputBo& and displa's the ite!s in a list bo&.

Lesson 1;: 3or"in( *ith #iles

1;.1 Introduction

(p until lesson 5> $e are only creating programs that could accept data at runtime% $hena program is terminated% the data also disappear. Is it possible to save data accepted by a,B program into a storage device% such as a hardis! or dis!ette% or even CD+V he ans$eris possible. Is this chapter% $e $ill learn ho$ to create files by $riting them into a storagedevice and then retrieve the data by reading the contents of the files using customiEed,B programs.

1;.2 Creatin( files

o create a file % use the follo$ing command

/pen Ffile=a!eF #or /utput As Gfile=u!ber 

"ach file created must have a file name and a file number for identification. As for filename% you must also specify the path $here the file $ill reside.

<or eample

/pen Fc:H' ?ocu!entsHsa!ple.t&tF #or /utput As G1 

$ill create a tet file by the name of sample.tt in the &y Document folder. heaccompany file number is 5. If you $ish to create and save the file in A drive% simplychange the path% as follo$s

/pen FA:Hsa!ple.t&tF #or /utput As G1 

If you $ish to create a &# file % simple change the etension to .html

/pen Fc:H' ?ocu!entsHsa!ple.ht!lF #or /utput As G 2 

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 31/38

1;.2.1 Sa!ple $ro(ra! : Creatin( a te&t file 

rivate Sub create?Clic!12Dim int&sg As String Dim Student9ame As String 

Open c;R&y DocumentsRsample.tt <or Output As L5int&sg @ &sgBo1<ile sample.tt opened2Student9ame @ InputBo1"nter the student 9ame2rint L5% Student9ameint&sg @ &sgBo1+riting a M Student9ame M to sample.tt 2

Close L5

int&sg @ &sgBo1<ile sample.tt closed2"nd Sub 

P he above program $ill create a file sample.tt in the &y Documents' folder and readyto receive input from users. Any data input by users $ill be saved in this tet file.

1;. +eadin( files

o read a file created in section 5.:% you can use the input L statemment. o$ever% $ecan only read the file according to the format $hen it $as $ritten. 6ou have to open thefile according to its file number and the variable that hold the data. +e also need todeclare the variable using the DI& command.

1;..1 Sa!ple $ro(ra!: +eadin( file 

rivate Sub eading?Clic!12Dim variable5 As String Open c;R&y DocumentsRsample.tt <or Input As L5Input L5% variable5et5.et @ variable5Close L5

"nd Sub 

P his program $ill open the sample.tt file and display its contents in the et5 tetbo.

Lesson 1>: Creatin( ulti!edia Applications

6ou can create various multimedia applications in ,B that couold play audio CD%audiofiles% ,CD % video files and etc.o be able to play multimedia files or multimedia devices% you have to insert &icrosoft&ultimedia Control into your ,B applicationsthat you are going to create. o$ever% &icrosoft &ultimedia Control is not normally

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 32/38

included in the startup toolbo% therefore you needto add the && control by pressing CtrlF and select it from the components dialog bothat is displayed.

5.5 Creating a CD player

1a2 he Interface.

rivate Sub <orm?#oad12'o position the page at the center

#eft @ 1Screen.+idth - +idth2 R :op @ 1Screen.eight - eight2 R :'Open the CDmyCD.Command @ Open

"nd Subrivate Sub myCD?Status(pdate12'(pdate the trac! numbertrac!9um.Caption @ myCD.rac!"nd Sub

rivate Sub 9et?Clic!12myCD.Command @ 9et"nd Sub

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 33/38

rivate Sub lay?Clic!12myCD.Command @ lay

"nd Sub

rivate Sub revious?Clic!12myCD.Command @ rev"nd Sub

rivate Sub Stop?Clic!12myCD.Command @ Stop"nd Subrivate Sub "it?Clic!12"nd"nd Sub

Lesso 1*+ Creat!g Mult!me&!a 'ppl!cat!os,art2

In previous lesson, we have programmed a CD player. Now, with somemodifications, we will transform the CD player into an audio file player. Thisplayer will be created in such a way that it could search for wave and midi files inyour drives and play them.

In this project, you need to insert a ComboBo, a Drive!istBo, a Dir!istBo, a

TetBo and a "ile!istBo into your form.I #hall briefly discuss the function ofeach of the above controls. Besides, you must also insert $icrosoft $ultimediaControl%$$Control& in your form , you may ma'e it visible or invisible. In myprogram, I choose to ma'e it invisible so that I could use the command buttonscreated to control the player.

• ComboBo( to display and enable selection of different type of files. 

• Drive!istBo( to allow selection selection of different drives available on

your )C. • Dir!istBo ( To display directories 

• TetBo ( To display selected files 

"ile!istBo( To display files that are available 

*elevant codes must be written to coordinate all the above controls so that theapplication can wor' properly. The program should flow in the following logicalway+

#tep + -ser choose the type of files he wants to play.

#tep+-ser selects the drive that might contains the relevant audio files.

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 34/38

#tep /+-ser loo's into directories and subdirectories for the files specified instep. The files should be displayed in the "ile!istBo.

#tep 0+ -ser selects the files from the "ile!istBo and clic' the )lay button.

#tep 1+ -ser clic' on the #top to stop playing and 2it button to end theapplication.

"#e $ter-ace

"#e Co&e

)rivate #ub Combo3Change%&4 to determine file type

If !istInde 5 6 Then"ile.)attern 5 %78.wav7&2lseIf !istInde 5 Then"ile.)attern 5 %78.mid7&

2lse"iel.)attern 5 %78.87&2nd If 

2nd #ub

)rivate #ub Dir3Change%&

4To change directories and subdirectories%or folders and subfolders&

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 35/38

"ile.)ath 5 Dir.)athIf Combo.!istInde 5 6 Then"ile.)attern 5 %78.wav7&2lseIf Combo.!istInde 5 Then

"ile.)attern 5 %78.mid7&2lse"ile.)attern 5 %78.87&2nd If 2nd #ub

)rivate #ub Drive3Change%&

4To change drives

Dir.)ath 5 Drive.Drive

2nd #ub

)rivate #ub "ile3Clic'%&If Combo.!istInde 5 6 Then"ile.)attern 5 %78.wav7&2lseIf Combo.!istInde 5 Then"ile.)attern 5 %78.mid7&2lse"ile.)attern 5 %78.87&2nd If 

If *ight%"ile.)ath, & 9: 7;7 Thenfilenam 5 "ile.)ath < 7;7 < "ile."ileName2lsefilenam 5 "ile.)ath < "ile."ileName2nd If Tet.Tet 5 filenam

2nd #ub

)rivate #ub "orm3!oad%&

4To center the =udioplayer startup page

!eft 5 %#creen.>idth ( >idth& ; Top 5 %#creen.?eight ( ?eight& ; Combo.Tet 5 78.wav7Combo.=ddItem 78.wav7Combo.=ddItem 78.mid7Combo.=ddItem 7=ll files7

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 36/38

2nd #ub

)rivate #ub =udio)layer3Clic'%&

2nd #ub

)rivate #ub play3Clic'%&

4To play >ave=udio file or $idi "ile

Comma&2Cl!c/$- Como1.L!st$&ex 0 "#e

'u&!olaer.De!ce"pe 34ae'u&!o3Else$- Como1.L!st$&ex 1 "#e'u&!olaer.De!ce"pe 3Se5uecer3E& $- 'u&!olaer.F!leName "ext1."ext'u&!olaer.Comma& 36pe3'u&!olaer.Comma& 3la3

E& Su

r!ate Su stopCl!c/()$- 'u&!olaer.Mo&e 72 "#e Ex!t Su$- 'u&!olaer.Mo&e : 727 "#e'u&!olaer.4a!t "rue'u&!olaer.Comma& 3Stop3E& $- 'u&!olaer.4a!t "rue'u&!olaer.Comma& 3Close3E& Su

r!ate Su Ex!tCl!c/()

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 37/38

E&E& Su Lesso 1;+ Creat!g Mult!me&!a

'ppl!cat!os,art %In lesson @, we have created an audio player. Now, with some modifications, wewill transform the audio player into a picture viewer. This player will be created insuch a way that it could search for all types of graphics your drives and playthem.

#imilar to the previous project, in this project, you need to insert a ComboBo, aDrive!istBo, a Dir!istBo, a TetBo and a "ile!istBo into your form. I #hallbrieflyeplain again the function of each of the above controls.

ComboBo( to display and enable selection of different type of files. • Drive!istBo( to allow selection selection of different drives available on

your )C. • Dir!istBo ( To display directories 

• TetBo ( To display selected files 

• "ile!istBo( To display files that are available 

*elevant codes must be written to coordinate all the above controls so that theapplication can wor' properly. The program should flow in the following logicalway+

#tep + -ser choose the type of files he wants to play.

#tep+-ser selects the drive that might contains the relevant graphic files.

#tep /+-ser loo's into directories and subdirectories for the files specified instep. The files should be displayed in the "ile!istBo.

#tep 0+ -ser selects the files from the "ile!istBo and clic' the #how button.

#tep 1+ -ser clic' on 2it button to end the application.

 

"#e $ter-ace

7/17/2019 Vb6 Tutorials

http://slidepdf.com/reader/full/vb6-tutorials 38/38