Sie sind auf Seite 1von 48

Introduction to Visual Programming Language Visual programming language is a programming language that uses graphical elements and figures

s to develop a program. Employs techniques to design a software program in two or more dimensions, and includes graphical elements, text, symbols and icons within its programming context. A programming language that uses a visual representation (such as graphics, drawings, animation or icons, partially or completely) A visual language manipulates visual information or supports visual interaction, or allows programming with visual expressions. A visual language is a set of spatial arrangements of text graphic symbols with a semantic interpretation that is used in carrying out communication actions in the world. Visual programming language enables the development of software programs by eliminating textual software code with a series of visual graphics elements. !ncorporates these graphical elements as the primary context of the language arranged in a systematic order. "he graphics or icons included within a visual program serve as input, activities, connections and#or output of the program. Visual language has a few types, such as icon based languages, diagramming languages and form based language. Visual languages should not be confused with $%! based programming language as they only provide graphical program authoring services. &owever, their code#context is completely textual. Examples of visual programming languages Visual basic Visual '(( )elphi Software considerations for visual programming Ease of learning Ease of understanding *peed of development &elp with enforcement of correct code +erformance of compiled code *upported platform environments +ortability ,it for purpose

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Ease of Learning 'learly, the easier that the programming language is to learn, the quic.er that programmers become productive. /ava is a lot easier to learn than '((0 ' is probably even easier. 1ut you learn once and program for a long time, so that ease of learning is of only limited value. Ease of Understanding 2ost code is written once and read many times usually, to focus on a particular point. "hus, it is important that the reader quic.ly grasp the essence of what3s happening. Speed of Development !f you loo. at speed of development in the round, you must consider not only how long it ta.es you to write code, but also how long it ta.es you to find a solution to the problem at hand and find the bugs. Help with Enforcement of Correct Code "he ideal programming language should turn logic errors into syntax errors. A powerful means to this end is type chec.ing. 2ost standard languages, such as /ava and '4145, have good type chec.ing. 1ut some languages have an escape clause. Performance of Compiled Code Supported Platform Environments 1y platform environment, ! mean not only the operating system facilities, but also the middleware facilities, database facilities, and system management facilities. Porta ilit! "it#for#Purpose Hardware considerations for visual programming %ser friendly 'ompatibility +ortability

Description of visual environment Visual 1asic is a programming language and development environment created by 2icrosoft 'orporation. !t is an extension of the 1A*!' programming language that combines 1A*!' functions and commands with visual controls. Visual 1asic provides a graphical user interface 6
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

($%!) that allows the developer to drag and drop ob7ects into the program as well as manually write program code. Visual 1asic is an event driven programming language. "his simply means that the applications that are developed using Visual 1asic, much li.e any other windows applications, will act upon the users actions (event procedures) such as 'lic., )ouble'lic., )rag)rop, 2ouse)own. 8henever you want the control in your application to respond to an event, you put the instructions in the appropriate event procedure. 4f course the user does not initiate all the events. *ometimes events are consequence of other events. ,or example as you start an application the main ,orm is loaded in the memory and shows up on the screen. "his is a ,orm95oad event, which simply means that the 5oad event procedure is activated on the ,orm control.

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

$he Integrated Development Environmen

!)E is a term commonly used in the programming world to describe the interface and environment that we use to create our applications. !t is called integrated because we can access virtually all of the development tools that we need from one screen called an interface. "he !)E is also commonly referred to as the design environment, or the program. +rograms ;
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

written in visual basic are done in an !ntegrated )evelopment Environment (!)E). "he !)E allows a programmer to< 'reate#design a user interface. 'ode the program. *et the properties for the controls. =un#compile the program. )ebug the program.

Integrated Development Environment Elements "he Visual 1asic integrated development environment (!)E) consists of the following elements. %enu &ar )isplays the commands you use to wor. with Visual 1asic. 1esides the standard ,ile, Edit, View, 8indow, and &elp menus, menus are provided to access functions specific to programming such as +ro7ect, ,ormat, or )ebug.

Context %enus 'ontain shortcuts to frequently performed actions. "o open a context menu, clic. the right mouse button on the ob7ect you>re using. "he specific list of shortcuts available from context menus depends on the part of the environment where you clic. the right mouse button. $ool ars +rovide quic. access to commonly used commands in the programming environment. ?ou clic. a button on the toolbar once to carry out the action represented by that button.

$ool ox +rovides a set of tools that you use at design time to place controls on a form. @
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Controls in tool ox

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Pro'ect Explorer (indow 5ists the forms and modules in your current pro7ect. A project is the collection of files you use to build an application.

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Properties (indow 5ists the property settings for the selected form or control. A property is a characteristic of an ob7ect, such as siCe, caption, or color.

"orm La!out (indow "he ,orm 5ayout window allows you to position the forms in your application using a small graphical representation of the screen. ) 'ect &rowser 5ists ob7ects available for use in your pro7ect and gives you a quic. way to navigate through your code. ?ou can use the 4b7ect 1rowser to explore ob7ects in Visual 1asic and other applications, see what methods and properties are available for those ob7ects, and paste code procedures into your application.

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

"orm Designer *erves as a window that you customiCe to design the interface of your application. ?ou add controls, graphics, and pictures to a form to create the loo. you want. Each form in your application has its own form designer window.

Code Editor (indow *erves as an editor for entering application code. A separate code editor window is created for each form or code module in your application.

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

)thers Immediate* Locals* and (atch (indows "hese additional windows are provided for use in debugging your application. "hey are only available when you are running your application within the !)E. $ool ox Controls with prefix "extbox txt A control for accepting user input. 5abel F lbl A control that displays unedited text to the user. 'ommand button F cmd A control which represents a button. "he user clic.s on it initiate an action. +icturebox F pic A control that displays images. ,rame F fra A control that is used to group ob7ects. 'hec.box F ch. A control that provides user with a toggle choice. 5istbox F lst A control that provides a list of items 'ombobox F cbo A control that provides a short list of items. )ata F dat A control for connecting to a database. -G
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

45E F ole A control for interacting other windows applications. *hape F shp A control that is used to draw circles, rectangles.

Creating visual Environment with o 'ects

--

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Program structure $erms used in visual asic +rogram A set of instructions that are aimed at accomplishing a certain tas.. +roperties "hese are characteristics of ob7ects in a program. 'ontrols "hey are elements that you place inside a form to create the user interface. 2ethods "hese are actions or function associated with the ob7ects in visual basic. Events "hese are responses toE actions performed by programs. V+,I+&LES Variables are memory locations that hold values to be used by the program at execution time. !t is a valid identifier. ,ules for creating varia les Variables cannot be .eywords in visual basic. Variables must begin with letters. "he maximum length of variable names is 6@@ characters. Variable names can contain letters, numbers and underscores. Varia les categories *tatic variables "hey are those variables that don3t change when the program executes. )ynamic variables "hey are those variables that change when the program executes. $!pes of varia les $lobal variables "hese are variables that are accessible through the program when it executes. 5ocal variables "hey are programs that are accessible within the function or procedures in which they are declared. -&. the .eyword )im is used to declare dynamic variables in visual basic. "he .eyword const is used to declare static variables in visual basic. D+$+ $/PES A data type shows the .ind information or data a certain variable stores. -6
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

!nteger *tores whole numbers ie non floating numbers . 1oolean =epresents true or false values. 1yte *tores a byte of information. )ouble =epresents a precision floating numbers. *trings =epresents a single precision floating point numbers. *trings *tores a series of characters. Variant *tores data types of any type. )ate and time. *tores date and time formats. 5ong *tores whole numbers with greater magnitudes. 'urrency *tores monetary valus. 1ytes 6 D D D ; 6 ; ; -G( -A =ange :6BAD to :6BAD G to 6@@ E66::B6G:AD@;BB to E66::B6G:AD@;BB - /anuary -GG to :- )ecember EEEE -.BEBAE:-:;DA6:6E:GD to -.BEBAE:-:;DA6:6E:GD 6-;B;D:A;D to 6-;B;D:A;D "rue or ,alse Any ob7ect type. :.;GD6:E:D to -.;;G-6EEDE ;@ G to 6G,GGG,GGG,GGG Any value within the range listed above.

)ata type !nteger 1yte 'urrency )ate#"ime )ouble 5ong 1oolean 4b7ect *ingle *tring Variant

Example 0 8rite a program that calculates the sum of two integers +lgorithms *tart Enter the integer values. 'ompute the sum the two numbers. +roduce results *top -:
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

"lowchart Start

Enter the two integers

Compute the sum of the two integers

$he sum of the two integers

Stop

Interface

-;

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Code +rivate *ub cmdcompute9'lic.() )im num- As !nteger )im num6 As !nteger )im sum As !nteger num- H Val(txtnum-."ext) num6 H Val(txtnum6."ext) txtsum."ext H Val(txtnum-."ext) ( Val(txtnum6."ext) End *ub

+,I$H%E$ICS I- VISU+L &+SIC Visual basic allows programmers to do mathematical operations using various arithmetic operators. Vb operator Arithmetic operator Algebraic expression Vb expression Addition ( I(y I(y *ubtraction ab xD 2ultiplication J ?b ?Jb )ivision # u#v u#v )ivision(integer) K Lone uKv Exponentiation M qp NMp Legation e e 2odulus 2od Nmodr qmodr ),DE, )" P,ECEDE-CE "hese are visual basic arithmetic rules that determine the sequence of evaluating values in a visual basic expression. =ules -@
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

%se the operators in order of precedence. ,or operators on the same precedence, evaluate from left to right in an expression. )rder of precedence 6 : ; @ A B 5astly S!m ol () M J# K 2od ( O )perator "he value between the brac.ets "he exponentiation Legative (negative values) 2ultiplication and division !nteger division =emainder division Addition and subtraction *tring concatenation

Example 0 Evaluate the expression below "otalH-G(-@J6#;M6 "otalH-G(-@6#-A "otalH-G(:#-A "otalH-G(-.DB@ "otalH--.DB@ Example 1 LumberH (D @)J:M6 LumberH:J:M6 LumberH:JE LumberH6B Example 2 IH (D @J:) M6 IH ( B) M6 IH;E Example 3 LumberH ((D @)J:) M6 -A
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

LumberH (:J:) M6 LumberHEM6 LumberHDVisual asic reserved words AndAlso Auto 1yVal '1ool ')ec 'lass '*hort )ate )elegate )ouble End Event ,or $et"ype !f !nherits Let 5oop 2ust!nherit Lamespace Lothing 4n 4rElse +aramArray +rotected =e)im Ansi 1oolean 'all '1yte ')bl '5ng '*ng )ecimal )im Each Enum Exit ,riend 4oSu !mplements !nteger 5ib 2e 2ust4verride Lew Lot!nheritable 4ption 4verloads +reserve +ublic =E2 As 1y=ef 'ase ''har 'har '4b7 '*tr )eclare )irect'ast Else Erase ,alse ,unction $o"o !mports !nterface 5i.e 2od 2y1ase Lext Lot4verridable 4ptional 4verridable +rivate =aiseEvent =emove&andler -B Assembly 1yte 'atch ')ate '!nt 'onst '"ype )efault )o Else!f Error ,inally $et &andles !n !s 5ong 2odule 2y'lass Lot 4b7ect 4r 4verrides +roperty =ead4nly =esume

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

=eturn *hared *tep *ub "o %nicode 8hile Ior Add AndAlso Asc8 1y=ef 'ase ')ate 'h)rive 'lear 'onst '*tr )ate)iff )ay )elegate )o End Erl Exit ,ile)ate"ime ,ile8idth ,ormat'urrency ,riend $etAttr

*elect *hort *top *ync5oc. "rue %ntil 8ith 'onst Add&andler Ansi Assembly 1yte 'atch ')bl 'hoose '5ng 'ount '"ype )ate+art ))1 )elete*etting )ouble Enum Err External*ource ,ile$et ,ilter ,ormat)ate"im e ,unction $et'har

*et *ingle *tring "hen "ry Variant 8ithEvents External*ource Address4f AppActivate Auto 1yVal '1ool ')ec 'hr 'lose 'reate4b7ect 'ur)ir )ate*erial )ecimal )escription Each Environ Error ,alse ,ile5en ,inally ,ormatLumber ,V $etException -D Alias As 1eep 'all '1yte 'har '!nt '4b7 '*hort )ate

*hadows *tatic *tructure "hrow "ype4f 8hen 8rite4nly P!f..."hen...PElse And Asc 1oolean 'all1yLame ''har 'h)ir 'lass 'ommand '*ng )ateAdd )ateValue )efault )ir Else!f Erase Event ,ile'opy ,ile+ut ,or ,ree,ile $etAll*ettings $et*etting

)ate*tring )eclare )im Else E4, Error"o*tring ,ileAttr ,ile4pen ,ix ,ormat+ercen t $et $et4b7ect

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

$et"ype &ex !mports !nput*tring !nterface !s)ate !s=eference 51ound 5ib 54, 2e 2od 2ust!nherit Lew Lot4verridable 4b7ect 4r +aramArray +rint +ublic =andomiCe =em =eset =nd *criptEngine 1uildVersion *etAttr *ingle *plit *tr'omp *tructure

$o"o &our !n !n*tr !+mt !s)1Lull !tem 5'ase 5i.e 5ong 2id 2odule 2ust4verride Lext Low 4ct 4rElse +artition +rint5ine +V =ate =emove =esume =*et *criptEngine 2a7orVersion *hadows *5L *tatic *tr'onv *ub

&andles !f !nherits !n*tr=ev !== !sError /oin 5eft 5ine!nput 5oop 2inute 2onth 2y1ase Lot L+er 4n 4verloads +mt +rivate N1'olor =ead4nly =emove&andle r =eturn ="rim *criptEngine 2inorVersion *hared *ource *tep *tr)up *witch -E

&elp'ontext !!f !nput !nt !s !sLothing Qill 5en 5oc 5*et 2!== 2onthLame 2y'lass Lothing L+V 4ption 4verridable ++mt +roperty =aise =e)im =ename =$1 *ave*etting *criptEngine *elect *hell *pace *top *tring *?)

&elp,ile !mplements !nput1ox !nteger !sArray !sLumeric 5ast)llError 5et 5oc. 5"rim 2.)ir 2sg1ox Lamespace Lot!nheritable Lumber 4ptional 4verrides +reserve +rotected =aiseEvent =egion =eplace =m)ir *ee. *econd *et *hort *pc *tr *tr=everse *ync5oc.

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

*ystem"ypeLame "imer "oday "ype4f %ntil 8ee.)ay 8ithEvents

"ab "ime*erial "rim %1ound Val 8ee.)ayLame 8rite

"hen "ime*tring "rue %'ase Variant 8hen 8rite5ine

"hrow "imeValue "ry %nicode Var"ype 8hile 8rite4nly

"ime4f)ay "o "ypeLame %nloc. Vb"ypeLame 8ith Ior

Visual asic input output commands %athematics


=ound =ounds a number to a selectable number of decimal places o result H round ( tempvariable,6 ) Val =eturns the numerical content of a string o result H Val (R-6:.;R) !nt =eturns an integer by truncating (different than ,ix) o i H int ( tempvariable ) ,ix =eturns an integer by truncating (different than !nt) o i H fix ( tempvariable ) &ex =eturns the hexadecimal value of any number o tempS H hex ( tempvariable ) 4ct =eturns the octal value of any number o tempS H oct ( tempvariable ) "an =eturns the tangent of an angle o tempvariable- H tan ( tempvariable6 ) =nd =eturns a random number between G and o tempvariable- H rnd =andomiCe !nitialiCes the =nd function so it gives different answers each time o randomiCe *gn =eturns the sign of a number o i H sgn ( tempvariable ) *in =eturns the sine of an angle o tempvariable- H sin ( tempvariable6 ) 'os =eturns the cosine of an angle o tempvariable6 H cos ( tempvariable ) Abs 'onverts a number to a positive value o i H abs ( tempvariable ) *qr =eturns the square root of a number o tempvariable- H sqr ( tempvariable6 ) 6G
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

5og =eturns the base -G logarithm of a number o tempvariable- H log ( tempvariable6 ) Atn =eturns the arctangent of an angle o tempvariable- H atn ( tempvariable ) +artition *ort of an oddball function but segregates values according to ranges
o

"ype 'onversions A variety of conversion functions o '1ool, '1yte, ''ur, ')ate, ')bl, ')ec, '!nt, '5ng, '*ng, '*tr, 'Var

Strings

5eft =eturns the left n characters of a string o tempS H leftS ( teststringS, ; ) =ight =eturns the right n characters of a string o tempS H rightS ( teststringS, ; ) "rim =emoves leading and trailing spaces of a string o tempS H trimS ( teststringS ) 5"rim =emoves only the leading spaces of a string o tempS H ltrimS ( teststringS ) ="rim =emoves only the trailing spaces of a string o tempS H rtrimS ( teststringS ) %'ase 2a.es all characters upper case o tempS H ucaseS ( teststringS ) 5'ase 2a.es all characters lower case o tempS H lcaseS ( teststringS ) 2id =eturns n characters from a string, starting a any position o tempS H midS ( teststringS, -, ; ) 5en =eturns the length of a string (how many characters it has) o tempS H len ( teststringS ) 5*et +ositions a string inside another, flush to the left o tempS H lrset ( teststringS ) =*et +ositions a string inside another, flush to the right o tempS H rsetS ( teststringS ) ,ormat =eturns a string formatted according to a user defined format o tempS H formatS ( teststringS, RPPPP.GR ) *tring o tempS H leftS ( teststringS, ; ) 'hr =eturns the string representation of a number o tempS H strS ( :6 ) Asc =eturns the A*'!! code of a single character o tempS H asc ( RAR ) *pace =eturns n spaces o tempS H spaceS ( -@ ) !nstr )etermines if one string is found within a second string o i H !nstr (starthere, string-, string6) !n*tr=ev )etermine if one string is found in a second, starting at the end 6VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

i H !n*tr=ev (string-, string6, start) *tr'omp 'ompares two strings o result H *tr'omp (string-, string6) *tr'onv 'onverts the case of a string>s characters o *tr'onv (string, vbuppercase) *tr=everse =everses character order in a string o *tr=everse (string-) =eplace =eplaces each occurrence of a string o =eplace (bigstring, searchstring, replacementstring) ,ormat'urrency =eturns a string using a currency format o ,ormat'urrency(var-, 6) ,ormat)ate"ime =eturns a date or time expression o ,ormat)ate"ime(R:#6#EER,vb*hort"ime) ,ormatLumber =eturns a number formatted according to a variety of options o ,ormatLumber(var-, 6) ,ormat+er'ent =eturns a number formated as a percent o ,ormat+er'ent(var-, 6)
o

+rra!s

4ption 1ase )etermines whether the lowest range of an array is G or o option base Erase Erases all values of an array o erase (arrayname) )im 'reates an array o dim arrayname(6@) =edim =esets the bounds of an array (has option to save values) o redim arrayname(6D) %1ound =eturns the upper dimension of an array o i H ubound (arrayname) 51ound =eturns the lower dimension of an array o i H lbound (arrayname) ,ilter =eturns a subset of an array based on a filter o ,ilter (inputarray, searchstring) Array ?es, there is a function called array. !t returns an array that has been filled with data from a list. !t allows you to put the actual data values in the code to avoid having the user input it or to avoid having to read it from a file o ArrayLame H Array (-G, 6G, :G) /oin 'oncatenates strings within an array

"ile Handling 54eneric6


)ir =eturns a filename that matches a pattern o tempS H )ir (RJ.JR) 'ur)ir =eturns the current directory o tempS H 'ur)ir 66
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

2.)ir 'reates a directory o m.dir ( RnewdirectorynameR ) 'h)ir 'hanges the current directory to a new location o chdir ( RnewdirectorynameR ) 'h)rive 'hanges the current drive o 'h)irve RAR =m)ir =emoves the indicated directory o rmdir ( RdirectorynameR ) ,reefile =eturns an unused file handle o i H freefile 4pen 4pens a file for access, loc.ing it from other applications o open RfilenameR for input as P'lose 'loses a file so that other applications may access it o close P54, =eturns the length of a file in bytes o i H lof ( P- ) E4, =eturns a boolean value to indicate if the end of a file has been reached o statusvariable H eof ( P- ) Lame As =enames a file o name Rfilename-R as Rfilename6R Qill )eletes a file o .ill RfilenameR ,ileattr =eturns attribute information about a file o i H int ( tempvariable ) $etAttr =eturns attributes of a file or directory o i H $etAttr(Rc<KwindowsKtempR) *etAttr *ets the attributes of a file o *etAttr pathname, vb&idden =eset 'loses all dis. files opened by the 4+EL statement o =eset ,ile)ate"ime =eturns data file was created or last edited o ,ile)ate"ime ( filename ) ,ile5en =eturns length of file in bytes o ,ile5en ( filename ) ,ile'opy 'opies a file to a new name o ,ile'opy sourcefile, destinationfile 5oc. 'ontrols access to a part or all of a file opened by 4+EL o 5oc. P%n5oc. =estores access to a part or all of a file opended by 4+EL o %n5oc. P8idth P *et the output line width used by the 4+EL statement o 8idth P6, DG

"ile Handling # +SCII#specific

5ine !nput =eads an entire line of A*'!! text 6:


VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

line input P-, tempvariableS 8rite +uts data in a file, with separators for the data o write P-, tempvariableS +rint +uts data in a file with no separators o print P-, tempvariableS *pc %sed in a print statement to move a number of spaces o +rint P6, var-0 spc(-@)0 var6 "ab %sed in a print statement to move to "A1 locations o +rint P6, var-0 "ab(6G)0 var6
o

"ile Handling # &inar!#specific


$et =eads data from a file o get P-, anyvariable +ut +uts data into a file o put P-, anyvariable *ee. 2oves the current pointer to a defined location in a file o see. P-, 6A !nput o input P-, anyvariable 5oc =eturns current position with an open file o i H 5oc(P6)

Declarations

)im %sed to define a variable as a certain type o i H dim i as integer, r as single o ?ou can use the 4ption Explicit to ma.e sure that V1 forces you to declare every variable you use. )!2 is that simplest way to declare a variable =e)im %sed to change the dimensions of a dynamic array o redim arrayname(:B) o )on>t be afraid of this one. ?ou can use =e)im to create an array whose siCe grows by - every time you want to add a number to it. "hen, the %1ound tells you how many numbers you>ve added. *tatic Establishes a procedure variable which .eeps its value between calls o static i as integer o ,or example, if you want to .eep trac. of how many times you>ve been in a procedure, set a counter as *"A"!' and increment it by one for each visit to the procedure. !t will never go away until the program is terminated. +ublic 'reates a variable which can be accessed outside its own procedure o public i as integer o Even if you>re the only programmer writing code in your application, use of +rivate vs +ublic will help catch errors if you inadvertently try to access an out of scope variable +rivate 'reates a variable that can be read only in its own procedure or module, according to where the declaration too. place. 6;
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

private i as integer %se this as often as possible to avoid unnecessary exposure of your variables to coding mista.es. *ub )efines a procedure which can execute a bloc. of code o *ub Lew+rocedure (var- as integer, var6 as string) o 1e sure to chec. out &E5+ for how to handle *ub arguments. "here are more questions and mista.es made concerning the use of arguments than 7ust about anything else !>ve seen. ,unction )eclares a procedure which can return a value o ,unction Lew,unction (var- as integer, var6 as string) as *!L$5E o "his is actually the most versatile of the *ub#,unction procedure types. !t can do anything a *ub can do as well as returning a value for use in an expression. 'all "ransfers control to a *ub or ,unction (is optional) o 'all +rocedure o *ince the use of 'A55 is optional, forget you ever saw it 'all1yLame Executes a method of an ob7ect or set#returns a property o 'all1yLame(form-,procedurename,vb2ethod) o "he really cool thing about this is that you don>t have to hardcode a procedure call. /ust use a string variable with the name of the procedure to call. 4ption Explicit !nstructs V1 to force an explicit declaration of all variables o 4ption Explicit o ?ou>re borderline stupid if you don>t use it to catch typing errors. *et up the V1 !)E to automatically include this in all pro7ects. 4ption 'ompare !nstructs V1 on how to ma.e string comparisons o 4ption 'ompare 1inary o "his can add case insensitivity for those times when you don>t want to hard code it 4ption +rivate +revents a module>s content from being referenced outside a pro7ect. o 4ption +rivate 2odule o $enerally doesn>t apply to most V1 applications. !f you find a good use for it let me .now. +roperty $et )eclares how to get the value of a property o +roperty $et Lame() o ?ou won>t use this much until you get into creating classes of your own +roperty 5et )eclares how to assign a value to a property o +roperty 5et Lame() o ?ou won>t use this much until you get into creating classes of your own +roperty *et )eclares how to set a variable reference to an ob7ect
o o

?ou won>t use this much until you get into creating classes of your own *et Assigns an ob7ect reference to a variable o *et I H form-.txt!nput,rom%ser o Very useful for ma.ing code more readable or simply to cut down on how much typing you have to doT 5et +recedes assignment of a value to a variable o 5et i H : 6@
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

o o

!t>s optional, no one uses, so forget you ever saw it "ype...End "ype 'reates a user defined part type which consists of standard V1 data types o type anytypename o one as string o two as integer o three as boolean o End "ype o "his is a really excellent way to .eep several .inds of data under one variable name. +lus, you can +%" or $E" a user defined type with a single line of code. 'onst 'reates a variable whose value is fixed o const anyname o 1asically, use this to give easy to remember names to values. ,or example, suppose you use the value :B.6 a lot in your code, then if you put '4L*" 2yAge H :B.6 in your code you>ll be able to insert the 2yAge where the :B.6 should have gone. Easier to type and easier to read. Also, you can chane the value of the constant by changing only the declaration line of code, rather than searching out every place the value was usedT )eclare %sed to define a procedure that exists in another file o declare functionname (arg- as integer, arg6 as string) as integer
o o o o o o o o

ArrayLame H Array (-G, 6G, :G) !mplements *pecifies a class to be implemented in a module

,riend Allows procedure to be callable from modules outside the class

$et4b7ect =eturn a reference to an ActiveI component

'reate4b7ect 'reates and returns a reference to an ActiveI ob7ect

$etAuto*erver*ettings =eturns information about the state of an ActiveI component>s registration.

o o o o o o

Enum )eclares a type for an enumeration

Event )eclares a user defined event

"ypeLame =eturns the type of data in a variable

Var"ype =eturns the type of data in a variable

)ef"ype *ets the default data type of variables )ef!nt A U !* A variety of data type or status chec.ing options !sArray, !s1indable, !s1ro.en, !s)ate, !s)irty, !sEmpty, !sError, !s2issing, !sLull, !sLumber, !s4b7ect, !s=eady, !s=oot,older 6A
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Date7$ime )ate $ets the current date "ime $ets the current time Low $ets the current date and time "imer =eturns the number of seconds since midnight )ateAdd Adds a time interval to a date )ate)iff =eturns how many time intervals there are between two dates )ate*erial =eturns the month#day#year )ateValue =eturns the date ?ear =eturns the current year 2onth =eturns the current month (integer) 2onthLame =eturns the text of the name of a month )ay =eturns the current day &our =eturns the current hour 2inute =eturns the current minute *econd =eturns the current second "ime*erial =eturns a date with the hour#minute#second "imeValue =eturns the time 8ee.)ay =eturns the current day of the wee. (integer) 8ee.)ayLame =eturns the text of a day of the wee.

2sg1ox A built in dialog box that gives a message and allows a user input i H msgbox R=ead thisTR, vbo.only, R"est 2essageR )oEvents Allows V1 to complete pending tas.s doevents *hell Executes a 6nd program from within the current program shell Rnotepad.exeR Lote V1 does not wait for the *hell>d program to quit before executing the next line of codeT 'ommand $ives any text that followed a V1 .EIE execution command tempS H command Environ =eturns the system environmental space content tempS H environ 1eep 2a.es the computer beep once. beep !nput1ox A built in dialog box that allows entry of a text string inputbox R!nput a valueTR, @ Address4f +rovides an entry point for an external program to use a procedure Address4f ( procedurename ) AppActivate Activates an applications window AppActivate ( windowtitle ) =aiseEvent ,ires an event declared at module level =aiseEvent +rocedureLame 5oad 5oad an ob7ect VISUAL BASIC 6.0 TUTORIAL 6B
PREPARED BY: KABA N. DANIEL

load form%nload %nload an ob7ect %nload form5oad+icture 5oad a picture into a control property form-.picture H loadpicture (filename) *ave+icture *ave a picture to a file *ave+icture(form-.picture,filename) 5oad=es)ata 5oad the data from a resource file 5oad=es)ata(index,format) 5oad=es*tring 5oad a string from a resource file 5oad=es*tring(index,format) *endQeys *end .eys to another app as though they were from the .eyboard *end.eys V)48LW N1'olor =eturns a value corresponding to the original N1 values G -@ form-.bac.color H N1color (-6) =$1 =eturns a color value by inputting the red, green, and blue parts form-.bac.color H =$1 (-6,-6D,6@A) 2e =efers to the current ob7ect, usually the active form print 2e.caption

$et*etting $et a value from the =egistry tempS H getsetting R"estAppR, R*ectionLameR, RQeyLameR, RdefaultvalueR $etAll*ettings =eturns a list of .ey settings and their values $etAll*ettings(appname,section) *ave*etting *ave a value into the =egistry savesetting R"estAppR, *ectionLame, Qey)ata )elete*etting )eletes an entry from the registry deletesetting R"estAppR, R*ectionLameR, RQeynameR

Program compiling "his involves a process of testing a program in structured programming to chec. if the program is error free. !t is a process of converting a program from course code to its ob7ect equivalent. Program de ugging 6D
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

"his is a process of correcting errors in a program. 8hen a program executes in structured programming, it must produce the expected results. !f it doesn3t give the expected output then it has errors. !n this regard the programmers should start the process of debugging. $esting programs in structured programming "his is a process of running (executing) programs to find errors (bugs). "he process of finding bugs is called debugging as mentioned above. +rogram testing is part of the procedure which ensures that the program corresponds with original program specification and that it wor.s in the intended environment. $est plan "hese are the stages involved in testing the programs. "hey include the following. -. )es.chec.ing

After writing the program the programmer goes through the program on a paper to eliminate any error that might cause extra wor. later.

6.

"ranslator system chec.ing

After coding the program is chec.ed using the compiler or translator to detect any syntax error. "he programmer corrects these errors and then resubmits the program to the compiler until the errors are over. :. +rogram run with test data

"hese re trial runs done with test data that includes all variations and extremes data including data with errors to ensure that program does not grind to an halt if incorrect data is used. ;. )iagnostic procedures ,or complex programs diagnostic procedures are used to find logical errors. A trace routine print the results at each stage to enable errors detected quic.ly. !f the trace routine is not available, the programmer can insert instructions in the program to print out intermediate results at .ey points. @. *ystem test with actual data (full scale) system

%sually new system are run parallel with existing system for a short period so that the results are compared and ad7ustments made. $ES$ D+$+ "his is the information that is used to test the new system or program. "he program tried and executed at least once every routine through the program and the accuracy of the program is verified to meet the original design specification. VISUAL BASIC 6.0 TUTORIAL 6E
PREPARED BY: KABA N. DANIEL

Categories of test data Dumm! data "his is the data input into a system for trial purposes. %sed to test the system for correctness. ,eal data 5normal data6 "his includes the general data for which the system was designed. Exceptional data +rograms are designed to accept certain range of data. !f illegal data is input it should be able to detect and re7ect it rather than try to process it to avoid getting wrong results. Visual operators asic Expressions An operator is a code element that performs an operation on one or more code elements that hold values. Value elements include variables, constants, literals, properties, returns from ,unction and 4perator procedures, and expressions. An expression is a series of value elements combined with operators, which yields a new value. "he operators act on the value elements by performing calculations, comparisons, or other operations. $!pes of )perators Visual 1asic provides the following types of operators<

+rithmetic )perators. perform familiar calculations on numeric values, including shifting their bit patterns. Comparison )perators< compare two expressions and return a 1oolean value representing the result of the comparison. Concatenation )perators< 7oin multiple strings into a single string. Logical )perators< !n Visual 1asic combines &oolean or numeric values and return a result of the same data type as the values. +ssignment operator. assign variables to some values in visual basic for example equal sign (H)

Evaluation of Expressions "he end result of an expression represents a value, which is typically of a familiar data type such as 1oolean, *tring, or a numeric type. :G
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

"he following are examples of expressions. @(; -@ J System.Math.Sqrt (9) + x R'oncatR O RenaR O RtionR BA: X 6: *everal operators can perform actions in a single expression or statement, as the following example illustrates. x H ;@ ( y J C M 6

Error handling in visual asic Error &andling enables programmers to write clearer, more robust, more fault tolerant programs. Error handling enables the programmer to attempt to recover (i.e., continue executing) from infrequent fatal errors rather than letting them occur and suffering the consequences (such as loss of application data). Error handling is designed for dealing with synchronous errors such as an attempt to divide by G (that occurs as the program executes the divide instruction). 4ther common examples of synchronous errors are memory exhaustion, an out of bound array index, and arithmetic overflow. Error handling provides the programmer with a disciplined set of capabilities for dealing with these types of errors. Error handling code is interspersed throughout a program>s code. Errors are dealt with the places in the code where errors are li.ely to occur. "he advantage of this approach is that a programmer reading the code can see the error handling in the immediate vicinity of the code and determine if the proper error handling has been implemented.

:-

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

De ugging # Error $!pes in Visual &asic 8 Y Lo matter how hard we try, errors do creep into our programs. "hese errors can be grouped into three categories< -. 6. :. *yntax errors =un time errors 5ogic errors

Y *yntax errors occur when you mistype a command or leave out an expected phrase or argument. Visual 1asic detects these errors as they occur and even provides help in correcting them. ?ou cannot run a Visual 1asic program until all syntax errors have been corrected. Y =un time errors are usually beyond your program>s control. Examples include< when a variable ta.es on an unexpected value (divide by Cero), when a drive door is left open, or when a file is not found. Visual 1asic allows you to trap such errors and ma.e attempts to correct them.

5ogic errors are the most difficult to find. 8ith logic errors, the program will usually run, but will produce incorrect or unexpected results. "he Visual 1asic debugger is an aid in detecting logic errors.

Logical errors "his is a human error. A programming mista.e that ma.es a program code to output results.

S!ntax error "hese are errors that violate rules and regulations or the syntax of a language.

,untime error "hese are the undiscovered error in a program.

(a!s to minimi9e errors )esign your application carefully. 2ore design time means less debugging time. %se comments where applicable to help you remember what you were trying to do. :6
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

%se consistent and meaningful naming conventions for your variables, ob7ects, and procedures.

,un#$ime Error $rapping and Handling =un time errors are trappable. "hat is, Visual 1asic recogniCes an error has occurred and enables you to trap it and ta.e corrective action. !f an error occurs and is not trapped, your program will usually end in a rather unceremonious manner. Error trapping is enabled with the 4n Error statement< 4n Error $o"o errlabel "his uses the $o"o statement. Any time a run time error occurs following this line, program control is transferred to the line labeled errlabel. =ecall a labeled line is simply a line with the label followed by a colon (<). "he best way to explain how to use error trapping is to loo. at an outline of an example procedure with error trapping. Private Sub Example () Declare variables.. On Error GoTo Han leErrors Proce ure co e Exit Sub Han leErrors Error !an lin" co e En Sub 4nce you have set up the variable declarations, constant definitions, and any other procedure preliminaries, the 4n Error statement is executed to enable error trapping. ?our normal procedure code follows this statement. "he error handling code goes at the end of the procedure, following the &andleErrors statement label. "his is the code that is executed if an error is encountered anywhere in the *ub procedure. Lote you must exit (with Exit *ub) from the code before reaching the &andleErrors line to avoid execution of the error handling code. *ince the error handling code is in the same procedure where an error occurs, all variables in that procedure are available for possible corrective action. !f at some time in your procedure, you want to turn off error trapping that is done with the following statement< 4n Error $o"o G ::
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

4nce a run time error occurs, we would li.e to .now what the error is and attempt to fix it. "his is done in the error handling code. Visual 1asic offers help in identifying run time errors. "he Err ob7ect returns, in its Lumber property (Err.Lumber), the number associated with the current error condition. ("he Err function has other useful properties that we won3t cover here consult on line help for further information.) "he Error() function ta.es this error number as its argument and returns a string description of the error. 'onsult on line help for Visual 1asic run time error numbers and their descriptions. 4nce an error has been trapped and some action ta.en, control must be returned to your application. "hat control is returned via the =esume statement. "here are three options< =esume lets you retry the operation that caused the error. "hat is, control is returned to the line where the error occurred. "his could be dangerous in that, if the error has not been corrected (via code or by the user), an infinite loop between the error handler and the procedure code may result. =esume Lext +rogram control is returned to the line immediately following the line where the error occurred. =esume label +rogram control is returned to the line labeled label. 8hen executing the error handling portion of the code and the end of the procedure is encountered before a =esume, an error occurs. 5i.ewise, if a =esume is encountered outside of the error handling portion of the code, an error occurs. De ugging Visual &asic Programs "hese are errors that don3t prevent an application from running, but cause incorrect or unexpected results. Visual 1asic provides an excellent set of debugging tools to aid in this search. "here are no prescribed processes that you can follow to eliminate all logic errors in your program. "he usual approach is to eliminate them as they are discovered. "he !mmediate 8indow. "he 5ocals 8indow. "he 8atch 8indow.

"hese windows can be accessed from the View menu (the !mmediate 8indow can be accessed by pressing 'trl($). 4r, they can be selected from the )ebug "oolbar (accessed using the "oolbars option under the View menu)<

:;

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

All debugging using the debug windows is done when your application is in brea. mode. ?ou can enter brea. mode by setting brea.points, pressing 'trl(1rea., or the program will go into brea. mode if it encounters an untrapped error or a *top statement.

4nce in brea. mode, the debug windows and other tools can be used to< )etermine values of variables *et brea.points *et watch variables and expressions 2anually control the application )etermine which procedures have been called 'hange the values of variables and properties

De ugging %nli.e other examples, we3ll do this one as a group. !t will be used to demonstrate use of the debugging tools. "he example simply has a form with a single command button. "he button is used to execute some code. 8e won3t be real careful about proper naming conventions and such in this example.

"he code attached to this button3s 'lic. event is a simple loop that evaluates a function at several values.

+rivate *ub 'ommand-9'lic.() )im I As !nteger, ? As !nteger IHG

:@

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

)o ? H ,cn(I) IHI(5oop 8hile I XH 6G End *ub

"his code begins with an I value of G and computes the ? value using the general integer function ,cn. !t then increments I by - and repeats the 5oop. !t continues looping 8hile I is less than or equal to 6G. "he function ,cn is computed using< ,unction ,cn(I As !nteger) As !nteger ,cn H '!nt(G.- J I M 6) End ,unction "his code doesn3t do much, especially without any output, but it ma.es a good example for loo.ing at debugger use. *et up the application and get ready to try debugging. Using the De ugging $ools Y "here are several debugging tools available for use in Visual 1asic. Access to these tools is provided with both menu options and buttons on the )ebug toolbar. "hese tools include brea.points, watch points, calls, step into, step over, and step out. "he simplest tool is the use of direct prints to the immediate window. Printing to the Immediate (indow.

?ou can print directly to the immediate window while an application is running. *ometimes, this is all the debugging you may need. A few carefully placed print statements can sometimes clear up all logic errors, especially in small applications. "o print to the immediate window, use the +rint method< )ebug.+rint Z5ist of variables separated by commas or semi colons[ )ebug.+rint Example< +lace the following statement in the 'ommand-9'lic. procedure after the line calling the general procedure ,cn< :A
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

)ebug.+rint I0 ? and run the application. Examine the immediate window. Lote how, at each iteration of the loop, the program prints the value of I and ?. ?ou could use this information to ma.e sure I is incrementing correctly and that ? values loo. acceptable. =emove the )ebug.+rint statement.

&rea:points.

!n the above examples, the program ran to completion before we could loo. at the debug window. !n many applications, we want to stop the application while it is running, examine variables and then continue running. "his can be done with brea.points. A brea.point is a line in the code where you want to stop (temporarily) the execution of the program that is force the program into brea. mode. "o set a brea.point, put the cursor in the line of code you want to brea. on. "hen, press X,E\ or clic. the 1rea.point button on the toolbar or select "oggle 1rea.point from the )ebug menu. "he line will be highlighted. 8hen you run your program, Visual 1asic will stop when it reaches lines with brea.points and allow you to use the immediate window to chec. variables and expressions. "o continue program operation after a brea.point, press X,@\, clic. the =un button on the toolbar, or choose *tart from the =un menu. ?ou can also change variable values using the immediate window. *imply type a valid 1asic expression. "his can sometimes be dangerous, though, as it may change program operation completely. &rea:point Example. *et a brea.point on the I H I ( - line in the sample program. =un the program. 8hen the program stops, display the immediate window and type the following line< +rint I0? "he values of these two variables will appear in the debug window. ?ou can use a question mar. (]) as shorthand for the command +rint, if you3d li.e. =estart the application. +rint the new variable values. "ry other brea.points if you have time. 4nce done, all brea.points can be cleared by 'trl(*hift(X,E\ or by choosing 'lear All 1rea.points from the )ebug menu. !ndividual brea.points can be toggled using X,E\ or the 1rea.point button on the toolbar. :B
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Viewing Varia les in the Locals (indow.

"he locals window shows the value of any variables within the scope of the current procedure. As execution switches from procedure to procedure, the contents of this window changes to reflect only the variables applicable to the current procedure. =epeat the above example and notice the values of I and ? also appear in the locals window. (atch Expressions.

"he Add 8atch option on the )ebug menu allows you to establish watch expressions for your application. 8atch expressions can be variable values or logical expressions you want to view or test. Values of watch expressions are displayed in the watch window. !n brea. mode, you can use the Nuic. 8atch button on the toolbar to add watch expressions you need. *imply put the cursor on the variable or expression you want to add to the watch list and clic. the Nuic. 8atch button. 8atch expressions can be edited using the Edit 8atch option on the )ebug menu. (atch Expression Example. *et a brea.point at the I H I ( - line in the example. *et a watch expression for the variable I. =un the application. Lotice I appears in the watch window. Every time you re start the application, the value of I changes. At some point in the debug procedure, add a quic. watch on ?. Lotice it is now in the watch window. 'lear the brea.point. Add a watch on the expression< I H ?. *et 8atch "ype to ^1rea. 8hen Value !s "rue.3 =un the application. Lotice it goes into brea. mode and displays the watch window whenever I H ?. )elete this last watch expression.

Call Stac:. :D
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

*electing the 'all *tac. button from the toolbar (or pressing 'trl(5 or selecting 'all *tac. from the View menu) will display all active procedures, that is those that have not been exited. 'all *tac. helps you unravel situations with nested procedure calls to give you some idea of where you are in the application. Call Stac: Example. *et a brea.point on the ,cn H 'int() line in the general function procedure. =un the application. !t will brea. at this line. +ress the 'all *tac. button. !t will indicate you are currently in the ,cn procedure which was called from the 'ommand-9'lic. procedure. 'lear the brea.point.

Single Stepping 5Step Into6.

8hile at a brea.point, you may execute your program one line at a time by pressing X,D\, choosing the *tep !nto option in the )ebug menu, or by clic.ing the *tep !nto button on the toolbar. "his process is single stepping. !t allows you to watch how variables change (in the locals window) or how your form changes, one step at a time. ?ou may step through several lines at a time by using =un "o 'ursor option. 8ith this option, clic. on a line below your current point of execution. "hen press 'trl(X,D\ (or choose =un "o 'ursor in the )ebug menu). the program will run through every line up to the cursor location, then stop; Step into Example. *et a brea.point on the )o line in the example. =un the application. 8hen the program brea.s, use the *tep !nto button to single step through the program. At some point, put the cursor on the 5oop 8hile line. "ry the =un "o 'ursor option (press 'trl(X,D\).

Procedure Stepping 5Step )ver6.

:E

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

8hile single stepping your program, if you come to a procedure call you .now functions properly, you can perform procedure stepping. "his simply executes the entire procedure at once, rather than one step at a time. "o move through a procedure in this manner, press *hift(X,D\, choose *tep 4ver from the )ebug menu, or press the *tep 4ver button on the toolbar. Step over Example. =un the previous example. *ingle step through it a couple of times. 4ne time through, when you are at the line calling the ,cn function, press the *tep over button. Lotice how the program did not single step through the function as it did previously.

"unction Exit 5Step )ut6.

8hile stepping through your program, if you wish to complete the execution of a function you are in, without stepping through it line by line, choose the *tep 4ut option. "he function will be completed and you will be returned to the procedure accessing that function. "o perform this step out, press 'trl(*hift(X,D\, choose *tep 4ut from the )ebug menu, or press the *tep 4ut button on the toolbar. "ry this on the previous example. CL+SSES )" D+$+ $/PES -umeric data t!pes "hese are those data types that will store numbers or numeric values. "hey are computed mathematically. !ntegers F store numbers. 1yte F true or false values between G and 6@@. =eal (double) F store D bytes of numeric data. 'urrency F stores monetary values. )ate and time F store and time format. *ingle F store ; bytes of numeric data. 5ong F stores ; bytes of numeric data. ;G
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

)ecimal F stores -6 bytes of numeric data.

Character data t!pes "hey are data types that stores characters or strings of characters. *tring F fixed length. *tores - to A@,;GG characters. *tring F variable length. *tores G to 6 billion characters. )ate F /anuary -,-GG to )ecember EEEE 1oolean F stores true or false values. 4b7ect F stores any embedded ob7ect. Variant F numeric. Any value as large as double. Variant F text. *ame as variable length.

&oolean data t!pes *tores 1oolean data types. 1oolean is represented by either the .eyword true or false or non Cero or Cero value. 1oolean are stored in two bytes and have no type declaration character. User defined data t!pes Visual basic lets the user create his own data type. "his is done when you wor. with mixed data types. Creating user defined data t!pes 8hen creating user defined data types use the .ey word _ $!pe` statement in declaration section of the form. )eclare variables associated with the new data types. Example 0 Private type employee #ame as strin" Dateo$birt! as ate Hire ate as ate Salary as currency ;VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Gen er as strin" En type $HE VISU+L &+SIC C)-$,)L S$,UC$U,ES A control structure regulates the flow of a visual basic program, given a condition. )etermine the output depending on the conditions used in the program. !t performs an indicated action only when the condition is false or true. $!pes of control structures "here are three main control structures in visual basic< Selection "hey are those control structures that provides options choose from depending on the conditions given for example !f, if#then else, switch, and select case. Iteration "hese are control structures that repeat statements until a given condition turns true of false for example while#wend, do#until, do#loop while, for#next, do#loop until. Se<uence A control structure that executes statements in a program procedurally0 one after another. If7then selection control structure "his is a control structure that is used to choose among alternative action to ta.e. Example 0 )etermining the age of students in a class. Interface

Enter the age 2essage

Displa! the age

Pseudo code7+lgorithms )eclare the variables i.e. age and message ;6


VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

!nitialiCe variable age !f age is greater than or equal to -D then )isplay _you are a grown up. 5earn to be responsible.` End if Code +rivate sub cmddisplay9clic.() )im age as integer )im message as string AgeHvalue(txtage.text) !f txtage.text\H-D then "xtmessage.textH`?ou are a grown up. 5earn to be responsible` End if End sub "lowchart *tart

!f age\H-D

)isplay the message

*top

"he above flowchart represents if#then selection control structure. !t illustrates a single selection control structure. !t performs the indicated action only if the condition is true otherwise it is aborted. ;:
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

If7then7else selection control structure "he if#then#else control structure allows a programmer to specify that a different action can be performed when the condition is true. !t tsts for true statements in a program. Example 0 A student sat for a )!" !! exam an d score the below mar.s0 *A)H BG +!H AG +!!H DG 2athsH ;G ,e<uired. 'reate a visual basic program that calculates the average mar.. %se the average mar. and assign the student the grade according to the grading system below =e! to grading s!stem. A H DG to -GG 1 HBG to BE ' HAG to AE ) H@G to @E E H;G to ;E , HG to :E Interface *ad +! +!! 2aths Average $rade 'alculate Pseudo code7algorithms )eclare variables !nitialiCe the variable that we input 'alculate the average !f average is greater than or equal to DG then )isplay _A` Else if average is greater than or equal to BG then ;;

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

)isplay _1` Else if average is greater than or equal to AG then )isplay _'` Else if average is greater than or equal to @G then )isplay _)` Else if average is greater than or equal to ;G then )isplay _E` Else if average is less than ;G then )isplay _,`

*tart

!nput the mar.s 'ompute average )isplay average

)isplay _A`

)isplay 1`

)isplay '`

;@

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

)isplay _)`

)isplay <`E`

)isplay _,`

*top Code +rivate sub cmdcalculate9clic. () )im *A), +!, +!!, maths as integer )im average as single )im grade as string *A)Hval(txtsad.text) +!Hval(txtpi.text) +!!Hval(txtpii.text) mathsHval(txtmaths.text) txtaverage.textH val(txtsad.text)( val(txtpi.text)( val(txtpii.text)( val(txtmaths.text)#; if txtaverage.text\HDG then ;A
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

txtgrade.textH`A` Else if txtaverage.text\HBG then "xtgrade.textH`1` Else if txtaverage.text\HAG then "xtgrade.textH`'` Else if txtaverage.text\H@G then "xtgrade.textH`)` Else if txtaverage.text\H;G then "xtgrade.textH`E` Else if txtaverage.textX;G then "xtgrade.textH`,` End if End sub Switch selection control structure "his ia s control structure that is related to if#then#else control structure. Each argument passed to switch control structure is either a condition or a value. !f a condition is true the value associated with the condition is returned. Example A student sat for a )!" !! exam an d score the below mar.s0 *A)H BG +!H AG +!!H DG 2athsH ;G =equired< 'reate a visual basic program that calculates the average mar.. %se the average mar. and assign the student the grade according to the grading system below =e! to grading s!stem. A H DG to -GG 1 HBG to BE ' HAG to AE ) H@G to @E E H;G to ;E , HG to :E Interface *ad +! +!! 2aths Average $rade 'alculate ;B
VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Code +rivate sub cmdcalculate9clic. () )im *A), +!, +!!, maths as integer )im average as single )im grade as string *A)Hval(txtsad.text) +!Hval(txtpi.text) +!!Hval(txtpii.text) mathsHval(txtmaths.text) txtaverage.textH val(txtsad.text)( val(txtpi.text)( val(txtpii.text)( val(txtmaths.text)#; txtgrade.textHswitch(txtaverage.text\HDG,`A` txtaverage.text\HBG,`1` txtaverage.text\HAG,`'` txtaverage.text\H@G,`)` txtaverage.text\H;G,`E` txtaverage.textX;G,`E`) end sub

;D

VISUAL BASIC 6.0 TUTORIAL PREPARED BY: KABA N. DANIEL

Das könnte Ihnen auch gefallen