Sei sulla pagina 1di 6

1/29/2017

VisualBasicCh.4Notes,page1

CIS230,VisualBasic

Ch.4Notes,page1

Objective#1:UseblockIfstocontroltheflowoflogic.

Conditionalstatementsareusedinmostprogramminglanguagestoallowaprogramtofollowdifferentcontrolpaths.Thatis,yourprogram

canrespondtouserinputsorarithmeticexpressionsindifferentwayswhenyouuseaconditionalstatement.TheIfstatementisanexampleof

aconditionalstatement.

ThegeneralformfortheIfstatementis

If (condition) Then statement(s) [ElseIf (condition) Then statement(s)] [Else statement(s)] EndIf

Notethatthereisnospaceinthekeyword,ElseIf,andthatthereisaspaceinthelastline,EndIf.

Inthegeneralformabove,bracketsindicatethatthesectionisoptional.

Therefore,anIfstatementcouldbeassimpleasthefollowingexample:

If(condition)Then

X=50

EndIf

Thelastline,EndIf,isNOToptionalthough.ThislineindicatesthattheIfstatementhasended.

Ontheotherhand,thefollowingIfstatementcouldbeusedfollowingthegeneralform:

If(condition)Then

X=50

ElseIf(condition)Then

If(condition)Then X=50 ElseIf(condition)Then

1/29/2017

VisualBasicCh.4Notes,page1

X=60

EndIf

AnotherexampleofamildlycomplicatedIfstatementis:

If(condition)Then

X=50

ElseIf(condition)Then

X=60

Else

X=100

EndIf

YetanotherexampleofavalidIfstatementis:

If(condition)Then

X=50

ElseIf(condition)Then

X=60

ElseIf(condition)Then

X=70

ElseIf(condition)Then

X=80

ElseIf(condition)Then

X=90

Else

X=100

EndIf

Thatis,youmayhaveasmanyElseIfportionsasyouneedbutyoucanonlyuseone(ifany)Elseportion.Eitherwayyoumustendthe

wholeIfstatementwithanEndIfline.

TheIfstatementsabovearecalled"blocks"becausetheyhavemultiplelinesofcodebutyettheyeachconsistofonlyoneexecutablestatement.

Also,itisproper(butnotabsolutelynecessary)toindentthestatementsundertheThenandElseclauses.Thismakesiteasierforothersto

understandyourcode.

ItispossibletowriteanIfstatementononelineofcodeasinthefollowingexample:

If(condition)ThenX=50

If(condition)ThenX=50

inwhichcase,noEndIflineisnecessary.InthiscaseyouwouldnotconsidertheIfstatementtobeablockofcode.Thisshouldonlybedone

forverysimpleIfstatementsthatwouldbeeasyforfellowprogrammerstounderstand.

1/29/2017

VisualBasicCh.4Notes,page1

TheconditionsreferredtointhegeneralformoftheIfstatementandtheexamplesaboveareBooleanexpressions.ABooleanexpressionis

onethatevaluatestoaBooleanTRUEvalueoraBooleanFALSEvalue.Anexampleofaconditionis(Total<100).IfthevariableTotalis

lessthan100,thentheBooleanexpressionevaluatestoTRUE.IfthevariableTotalisequalto100,theBooleanexpressionevaluatesto

FALSE.IfTotalisgreaterthan100,thentheexpressionevaluatestoFALSEaswell.

Writingconditionsthatreflectthelogicnecessarytomakeyouralgorithmworkcorrectlyisthedifficultpart.Havingonesymbolmisplacedor

reversedcaneasilycauseyourIfstatementtoworkincorrectly.

WhileyoumayuseasmanyElseIfclausesasyouwouldlikeinoneIfblock,thefirstconditiontoevaluatetoTRUEwillcausethenext

statementtoexecute.BasicwillthensendtheflowoftheprogramtothenextstatementaftertheEndIf.IfneithertheinitialIfconditionnor

anyoftheElseIfconditionsevaluatetoTRUEthentheElsestatementwillexecuteifthereisone.TheElsestatementcanbeconsidereda

defaultstatementwhichevaluatesifnootherstatementsexecute.

Objective#2:UnderstandandusenestedIfs.

IfanIfstatementisentirelycontainedbetweentheThenandtheEndIfofanotherIfstatement,thestatementisconsideredtobeanestedIf

statement.

statement. Example: If(condition)Then [statement(s)] If(condition)Then

Example:

If(condition)Then

[statement(s)]

If(condition)Then

statement(s)

EndIf

[statement(s)]

EndIf

BecarefultouseIfstatementsthatcanbeunderstoodbythosewhoreadyourcode.Often,thecorrectlogiccanberepresentedmanywaysIf

(andIf/ElseIf)statementsbutitisyourresponsibilitytomakesurethatyouralgorithmisintelligible.

Objective#3:Readandcreateflowchartsindicatingthelogicinaselectionprocess.

Carefullyreadabouttheflowchartsinchapter4andunderstandhowtheyareusedtorepresenttheconditionallogic.Wewillnotmakealotof

formaluseofsuchflowchartsthoughinclass.

Diamond­shapesymbolsinflowchartsrefertoconditionsandshowhowtheflowofcontrolcanbranchoneoftwoways.

Objective#4:Evaluateconditionsusingtherelationaloperators.

Conditionscanbemorecomplicatedthanthoseusedasexamplesabove.Onecanusefamiliaralgebraicoperatorssuchas+,­,/,and*.Onecan

alsouse6differentrelationaloperatorscanbeusedwithintheBooleanexpressionsthatmakeupconditions.Relationaloperatorsare

sometimescalledcomparisonoperators.The6relationaloperatorsare:

comparisonoperators .The6relationaloperatorsare:

1/29/2017

VisualBasicCh.4Notes,page1

< lessthan1/29/2017 VisualBasicCh.4Notes,page1 > greaterthan = equalto

> greaterthan1/29/2017 VisualBasicCh.4Notes,page1 < lessthan = equalto

= equalto (inthiscontextthe=symbolisusedasarelationaloperator,notasanassignmentoperator)VisualBasicCh.4Notes,page1 < lessthan > greaterthan <> notequalto >=

<> notequalto>=

>= greaterthanorequalto(thereisnospacebetweenthetwosymbols)<> notequalto <= lessthanorequalto

<= lessthanorequaltogreaterthanorequalto(thereisnospacebetweenthetwosymbols)

Whenyouuserelationaloperators,youshouldmakesurethatthetwooperands(variablesorvalues)thatyouarecomparinghavethesamedata

type.Forexample,thecondition(intTotal<100)isvalidbecausethevariableintTotalisanIntegerdatatypewhichcanbecomparedtothe

wholenumber100.Becareful,thoughnottouseaconditionlike (txtUserEntry<100) eveniftheuserwasaskedtotypeanumerical

valueintothetextbox,UserEntry.SinceVBtreatstheTextpropertyofatextboxasText,VBwouldmakethepossiblecomparison"99"<100

whichmaycausearun­timeerror.

Whenstringsarecomparedasopposedtonumericalvalues(Integers,Singles,etc.),VBcomparesthetwostringscharacterbycharacter,leftto rightasalibrarianwouldcomparebooktitles.Fortheletters'A'to'Z',itisobviousthat'A'wouldbeconsideredlessthan'Z'.Buttodetermine thecorrectorderofotherkindsoflegalkeyboardcharacterssuchas'*'and'~',VBusestheASCIIcodes.ASCIIstandsforAmerican StandardCodeforInformationInterchangeandanASCIIchartcanbefoundintheAppendixofmanyreferencemanualsandtextbooks.

ThereisanabbreviatedASCIIchartonp.129ofourtextbook.Tocompare'*'with'~',youneedtolookupthenumericalASCIIcodesforthe

twocharacterswhichare42and126,respectively.Thereforethecondition('*'<'~')evaluatestoTRUE.Notethatsinglequotesareplaced

aroundanysinglecharacter,whichiscommonlycalledacharacterliteral.

NotethatconditionscanbesimplifiedinVBwhere

IfblnFinished=1Then

isequivalentto IfblnFinishedThen

Objective#5:CombineconditionsusingAndandOr.

Sometimesyouneedtousecompoundconditionstorepresentthenecessarylogicinanalgorithm.Compoundconditionsconsistofseveral Booleanexpressions,whicharejoinedbythelogicaloperators,AndandOr.Thethreelogicaloperatorsthatyouarelikelytouseinconditions areOr,And,andNot.OftentheselogicaloperatorsarereferredtoastheBooleanOr,theBooleanAnd,andtheBooleanNotasopposedtothe words"or","and",and"not"asusedintheEnglishlanguage.

Examples: (X<100AndY<50)(Total=4OrTotal=5) (Not(Total=4)OrTotal=5)

(Total=4OrTotal=5)

(Not(Total=4)OrTotal=5)

Theorderofoperationsamongthelogicaloperatorsis: Not,And,Or

butyoucanuseparenthesestooverridethisorder.

Objective#6:TesttheValuepropertyofoptionbuttonsandcheckboxes.

1/29/2017

VisualBasicCh.4Notes,page1

TheValuepropertyofacheckboxcanbeusedtodetermineiftheuserhasplacedacheckmarkinthatcheckbox.TheValuepropertywill

eitherbeChecked(whichequalsthevalueof1),Unchecked(whichequalsthevalueof0),orGrayed(whichequalsthevalueof2).

Bysimplyusingcodelike: IfchkColor.Value=CheckedThen checkmarked.

youcanperformanactionifindeedthecheckbox,chkColoris

TheValuepropertyofanoptionbuttoncanbeusedtodetermineiftheuserhasselectedthatparticularoption.Thevaluepropertyforan

optionbuttoniseitherTrueorFalse.

optionbuttoniseitherTrueorFalse. TheIfstatement IfoptYear.Value=TrueThen

TheIfstatement IfoptYear.Value=TrueThen

canbeusedtoperformanactioniftheoptionbuttonoptYearisselected.

SincetheValuepropertiesofbothcheckboxesandoptionbuttonsarethedefaultpropertiesofthosecontrols,theIfstatementsgivenabove

couldbeshortenedto IfchkColor=CheckedThen

and IfoptYear=TrueThen

Objective#7:Performvalidationonnumericfields.

Youshouldcheckusers'inputintotextboxestomakesurethatthedatatheyenterisvalid.Ifauserentersanumberthatisnotintherangethat

youareexpecting,itcouldcauselogicorrun­timeerrors.Makingsurethattheuserentersvaliddataiscalledvalidation(orerror­checking).

SinceweoftenusetextboxestoobtainuserinputandtheTextpropertyofatextboxisconsideredastext(astring)byVB,itisawiseideato

validatethisdatawhenyouexpecttheusertoenternumericdata.

Ifyousimplywishtomakesurethatauser'sentryisavalidnumber,youcanusetheIsNumericfunction.IsNumericreturnsatrueifits argumentisavalidnumericalvalueandcanbeusedinanarithmeticexpression.Forexample, IsNumeric("13")=True whereas

IsNumeric("375­4031")=False

Youcanvalidateusers'inputtednumbertomakesurethatitfallswithinacertainrangebyusingrelationaloperatorsasin

If(Val(txtUserInputA)>10)And(Val(txtUserInputB)<=100)Then

Objective#8:Calleventproceduresfromotherprocedures.

Youcancallaneventprocedurefromwithinanothereventproceduresimplybytypingthenameoftheeventprocedureonalineofcode.

Objective#9:Createmessageboxestodisplayerrorconditions.

AmessageboxisaspecialVBwindowthatcanbedisplayedtosendanimportantmessagetotheuserthatheorshecannoteasilyignore.It

includesamessage(astring),anoptionaliconnexttothatstring,atitlebarcaptionatthetopofthewindow,andacommandbutton(s)that

requirestheusertoclicktomakethewindowdisappear.

ThegeneralformoftheMsgBoxstatementwhichproducesamessageboxis

Buttons/icon][,"Captionofthetitlebar"]

MsgBox"Messagestringdirectedtotheuser"[,

The"Messagestringdirectedtotheuser"isawordorphrasethatyouwanttheusertobesuretoread.

1/29/2017

VisualBasicCh.4Notes,page1

TheButtons/iconareVBconstantsthatyoucanusetomakegettheattentionoftheuser.AnexampleistheOKbuttonwhichusesthe

VBconstantvbOKOnly.

TheCaptionofthetitlebaristhewordorphraseyouwishtoappearinthetitlebaratthetopofthewindow.

Objective#10:Applythemessageboxconstants.

SeetheHands­Onprogrammingexampleinthechaptertousethemessageboxconstantswhicharelistedonp.140.

Objective#11:Debugprojectsusingbreakpoints,steppingprogramexecution,anddisplayingintermediateresults.

Followthe"DebuggingStep­by­StepTutorial"onpp.155+topracticedebuggingprograms.

CIS230HomePage | Mr.Minich'sEducationHomePage |
| Mr.Minich'sEducationHomePage | Minich.comWebDesign