Sunteți pe pagina 1din 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
http://www.minich.com/education/racc/visualbasic/cis230ch4/ch4notes1.htm 1/6
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

inwhichcase,noEndIflineisnecessary.InthiscaseyouwouldnotconsidertheIfstatementtobeablockofcode.Thisshouldonlybedone
forverysimpleIfstatementsthatwouldbeeasyforfellowprogrammerstounderstand.
http://www.minich.com/education/racc/visualbasic/cis230ch4/ch4notes1.htm 2/6
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.

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

Objective#4:Evaluateconditionsusingtherelationaloperators.

Conditionscanbemorecomplicatedthanthoseusedasexamplesabove.Onecanusefamiliaralgebraicoperatorssuchas+,,/,and*.Onecan
alsouse6differentrelationaloperatorscanbeusedwithintheBooleanexpressionsthatmakeupconditions.Relationaloperatorsare
sometimescalledcomparisonoperators.The6relationaloperatorsare:
http://www.minich.com/education/racc/visualbasic/cis230ch4/ch4notes1.htm 3/6
1/29/2017 VisualBasicCh.4Notes,page1

<lessthan
>greaterthan
=equalto(inthiscontextthe=symbolisusedasarelationaloperator,notasanassignmentoperator)
<>notequalto
>=greaterthanorequalto(thereisnospacebetweenthetwosymbols)
<=lessthanorequalto

Whenyouuserelationaloperators,youshouldmakesurethatthetwooperands(variablesorvalues)thatyouarecomparinghavethesamedata
type.Forexample,thecondition(intTotal<100)isvalidbecausethevariableintTotalisanIntegerdatatypewhichcanbecomparedtothe
wholenumber100.Becareful,thoughnottouseaconditionlike(txtUserEntry<100)eveniftheuserwasaskedtotypeanumerical
valueintothetextbox,UserEntry.SinceVBtreatstheTextpropertyofatextboxasText,VBwouldmakethepossiblecomparison"99"<100
whichmaycausearuntimeerror.

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

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)

Theorderofoperationsamongthelogicaloperatorsis:Not,And,Orbutyoucanuseparenthesestooverridethisorder.

Objective#6:TesttheValuepropertyofoptionbuttonsandcheckboxes.

http://www.minich.com/education/racc/visualbasic/cis230ch4/ch4notes1.htm 4/6
1/29/2017 VisualBasicCh.4Notes,page1

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

Bysimplyusingcodelike:IfchkColor.Value=CheckedThen....youcanperformanactionifindeedthecheckbox,chkColoris
checkmarked.

TheValuepropertyofanoptionbuttoncanbeusedtodetermineiftheuserhasselectedthatparticularoption.Thevaluepropertyforan
optionbuttoniseitherTrueorFalse.

TheIfstatementIfoptYear.Value=TrueThen....canbeusedtoperformanactioniftheoptionbuttonoptYearisselected.

SincetheValuepropertiesofbothcheckboxesandoptionbuttonsarethedefaultpropertiesofthosecontrols,theIfstatementsgivenabove
couldbeshortenedtoIfchkColor=CheckedThen...andIfoptYear=TrueThen....

Objective#7:Performvalidationonnumericfields.

Youshouldcheckusers'inputintotextboxestomakesurethatthedatatheyenterisvalid.Ifauserentersanumberthatisnotintherangethat
youareexpecting,itcouldcauselogicorruntimeerrors.Makingsurethattheuserentersvaliddataiscalledvalidation(orerrorchecking).
SinceweoftenusetextboxestoobtainuserinputandtheTextpropertyofatextboxisconsideredastext(astring)byVB,itisawiseideato
validatethisdatawhenyouexpecttheusertoenternumericdata.

Ifyousimplywishtomakesurethatauser'sentryisavalidnumber,youcanusetheIsNumericfunction.IsNumericreturnsatrueifits
argumentisavalidnumericalvalueandcanbeusedinanarithmeticexpression.Forexample,IsNumeric("13")=Truewhereas
IsNumeric("3754031")=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.

ThegeneralformoftheMsgBoxstatementwhichproducesamessageboxisMsgBox"Messagestringdirectedtotheuser"[,
Buttons/icon][,"Captionofthetitlebar"]
The"Messagestringdirectedtotheuser"isawordorphrasethatyouwanttheusertobesuretoread.

http://www.minich.com/education/racc/visualbasic/cis230ch4/ch4notes1.htm 5/6
1/29/2017 VisualBasicCh.4Notes,page1

TheButtons/iconareVBconstantsthatyoucanusetomakegettheattentionoftheuser.AnexampleistheOKbuttonwhichusesthe
VBconstantvbOKOnly.
TheCaptionofthetitlebaristhewordorphraseyouwishtoappearinthetitlebaratthetopofthewindow.

Objective#10:Applythemessageboxconstants.

SeetheHandsOnprogrammingexampleinthechaptertousethemessageboxconstantswhicharelistedonp.140.

Objective#11:Debugprojectsusingbreakpoints,steppingprogramexecution,anddisplayingintermediateresults.

Followthe"DebuggingStepbyStepTutorial"onpp.155+topracticedebuggingprograms.

CIS230HomePage|Mr.Minich'sEducationHomePage|Minich.comWebDesign

http://www.minich.com/education/racc/visualbasic/cis230ch4/ch4notes1.htm 6/6

S-ar putea să vă placă și