You are on page 1of 8

VISUALBASICFORAPPLICATIONS

VisualBasicforApplications(VBA)isapowerfulbuteasytouseprogramming
languageavailableinMicrosoftExcelversion5.0orlater.Forscientificandengineering
purposesitissimilartoBASICandFORTRAN.VBAisactuallyashortenedversionof
theVisualBasicprogramminglanguage.Thelanguagealsohasotherfeaturesthatmake
itusefulforautomatingcertaintasksonExcelworksheets,includingsuchthingsas
buttonsandmenus.ThisdocumentintroducesthereadertosomeofthefeaturesofVisual
BasicinExcel.MoredetailedinformationcanbefoundinExcelwrittendocumentation
andhelpfiles.
VBAcommandsareenteredintotwotypesofprocedures.Thefirsttypeofprocedureis
sometimescalledmacroorsub(function)procedures.Macrosgenerally(butnotalways)
performactionsonworksheet(s)butdonotreturnvalues.Macrosaregenerallyexecuted
throughmenusorbuttons.Afunctionprocedure,ontheotherhand,returnsavalue(or
values)toaspreadsheetoranotherprocedure(althoughitmayalsobeusedtomanipulate
worksheetsaswell).
Macros
AmacroisasetofVisualBasiccommandsthatcanbeusedtomanipulateaworksheet
automatically,forexampleformattingcells,typinginrepeatedtext,etc.Excelhasa
shorthandwaytoentermacros.Itincludesarecordingprocessthatwillautomatically
recordactionstakenonaworksheetandconverttheactionsintoVisualBasiccode.
RecordingamacrostartswiththepulldownmenusequenceTools>Macro>RecordNew
Macrocommand.Eachmacroisassignedanameandoptionsthroughdialogboxes.The
pulldownmenusequenceTools>Macro>StopRecordingendstheprocessofmacro
recording.
Onceamacrohasbeencreated,itcanbeexecutedinavarietyofways:1)usingthe
Tools>Macromenu,2)addingareferenceintheToolsmenu,3)assigningamacrotoa
buttononasheet,4)assigningamacrotoanitemonatoolbar,5)assigningamacrotoa
graphicobject.Thesemodesofexecutingaresetasapartofthemacrooptions.Further
informationcanbefoundintheExcelmanualandhelpfiles.
UserDefinedFunctions
Userdefinedfunctionsaregenerallyusedtoautomaticallyperformmathematical
calculationsandreturnthemtoaworksheet.Userdefinedfunctionsaresimilarto
functionsbuiltintoExcel,excepttheyarecreatedbytheuser.Userdefinedfunctions
willappearonaModulesheetthesameasarecordedmacro.Thedifferenceisthata
macrowillstartwiththekeywordSubandendwiththekeywordsEndSub,whilea
VisualBasicforApplications(MAM23.Nov.98)

userdefinedfunctionwillstartwiththekeywordFunctionandendwiththekeywords
EndFunction.Auserdefinedfunctionisalsomanuallytypedontoamodulesheetrather
thaninputusingtherecordingprocedure.Auserdefinedfunctionhasthefollowing
elements:
1. FunctionandEndFunctionstatementsmarkingthebeginningandendofthe
function.
2. Anamethatidentifiesthefunction.ThenameimmediatelyfollowstheFunction
keyword.Therearesomerestrictionsonwhatsymbolscanbeusedinthenames,and
ingeneralfunctionnamesshouldnotconflictwithfunctionsalreadybuiltintoExcel.
3. Arguments.Thesearethevaluessuppliedtothefunctionfromaspreadsheetor
anotherfunction.Theremaybeanynumberofarguments,includingnone.Argument
namesareenclosedinparenthesesfollowingthefunctionname.Argumentsare
separatedbycommas.Argumentscaneitherbesinglevaluesorarrays.
4. VisualBasiccode.Thesearetheinstructionsthattellthefunctionwhichcalculations
toperform.Itisacombinationofnumbers,variables,controlstatements,and
mathematicaloperatorsthatyieldavalue.
5. Thereturnvalue.Thisisthevaluethefunctionreturnsafterperformingthe
calculations.Thewaythisisspecifiedistoenterthenameofthefunctionfollowedby
anequalsignfollowedbyanexpression.
Example:
Tocreateauserdefinedfunction,firstgototheVBAeditorwiththemenusequence
Tools>Macro>VisualBasicEditorcommand.Tostartanewmodulesheetusethe
menusequenceInsert>Module.Typeinthefunctionstatementsontheeditingsheetthat
comesup.Belowisanexampleofafunctionthatreturnsthecuberootofavariable.
Function Cube_Root (x)
Cube_Root = x ^ (1/3)
End Function
Tocallauserdefinedfunctionfromacellonaworksheet,simplytypetheequalsign
followedbythenameofthefunctionandtheargumentsenclosedinparentheses(justas
youwouldanyotherfunction).Aswiththebuiltinfunctions,argumentscaneitherbe
numbers,cellreferences,orformulas.
Userdefinedfunctionscanalsobeaccessedthroughthefunctionwizardbylooking
underUserDefinedFunctions.ThereaderisreferredtotheVBAmanualformore
detailedinformation.

VisualBasicforApplications(MAM23.Nov.98)

Variables
VariablesaretheplacekeeperswhereVBAstoresdata.Althoughthefunctionname
andargumentsappearasvariables,theyareactuallystorageplaceswheredatais
transmittedtoandfromworksheetsorotherprocedures.
AvariableinVBAcanbethoughtofinthesamemannerasacellonaworksheet,except
thatithasanamedreferenceinsteadofacellreference(namedreferences,ofcourse,can
alsobeusedonaworksheet).Variableshavethreeattributes:a)type,b)scope,andc)
dimensionality.
Variabletypereferstokindofdatathatcanbestoredinthevariable.Excelhasthe
followingvariabletypes:
Integer
Long
Single
Double
Currency
Date
String
Boolean
Object
Variant

16bitinteger
32bitinteger
32bitfloatingpointnumber
64bitfloatingpointnumber
64bitinteger
Dateandtimeinformation
Textinformation
LogicalTrueorFalse
32bitaddressesthatrefertoobjectswithinanapplication
Generaltypethatissetaruntime,i.e.,whendataisputintoavariable

Variablescopereferstotherangeofproceduresand/ormodulesoverwhichthevalueof
thevariableisavailable.Therearethreelevelsofscope:a)local,b)module,andc)
public.
Localvariablesareonlyavailablewithinaspecificprocedure.Statementsdeclaringthe
variable(eitherDimorStatic)aremadewithinthedesiredprocedure.Localvariables
declaredwithDimremaininexistenceonlyaslongastheprocedureisexecuting,while
thosedeclaredwithStaticremaininexistencetheentiretimeVBisrunning.
Modulelevelvariablesareavailabletoallproceduresonagivenmodulesheet,butnotto
proceduresonothermodulesheetsorinotherworkbooks.Statementsdeclaringthe
variable(eitherDim,Static,orPrivate)aremadeoutsideofprocedures,usuallyatthe
topofthemodulesheet.AtthemodulelevelthereisnodifferencebetweenPrivateand
Dim,butPrivatemightbeabetterstatementtousetocontrastagainstthePublic
statementusedforpublicvariables.
Publicvariablesareavailabletoeveryprocedureineverymoduleintheworkbook(and
canalsobemadeavailabletoallworkbooksselectedintheAvailableReferencesboxof
theReferencesdialogbox,Toolsmenu,ifdesired).Publicvariablescannotbedeclared

VisualBasicforApplications(MAM23.Nov.98)

withinaprocedure.Likemodulelevelvariables,theyaregenerallydeclaredina
declarationssectionofamodule(usuallyatthetop).ThePublicstatementisusedforall
publicvariables.
Variablescanhavedimensionalityfromzeroto60differentdimensions.Azero
dimensionvariablehasonlyasinglevalue.Aonedimensionalvariablehasasingle
index,twodimensionalvariabletwoindexes,etc.Multidimensionalarraysarereferredto
inadeclarationstatementasvariablename(n1,n2,...),wherethevaluesn1,n2,etc.referto
thenumberofvariablesinthatdimension.ForexampleCounters(5)referstoavariable
calledCountersthathasfiveelements,andSums(2,3,7)referstoavariablecalledSums
thatisa237array.
TheOptionBasestatementdeclareswhetherthefirstindex(lowerbound)startswith
zeroorone.ForexampleOptionBase1meansthatnumberingstartsatone.TheOption
Basestatementisusuallygivenatthetopofthemodulesheetorwithinaprocedure.
AnotherwaytospecifythelowerboundistoprovideitexplicitlyusingtheTokeyword.
Forexample,Counters(101To105)wouldhavetheindexforcountersrunningfrom
101to105.
Goodprogrammingpracticeistorequirethatallvariables(otherthanthosethatappearin
aFunctionstatement)tobedeclared.ThisallowsVBAtogenerateanerrormessageifa
variablenameismistypedornotexplicitlydeclared.ThestatementOptionExplicitat
thetopofthemodulesheetwilldothis.OptionExplicitcanalsobeaddedtoevery
modulecreatedusingthemenusequenceTools>Options>ModuleGeneral>Require
VariableDeclaration.
Declarationstatementsforvariableshavetheform:
DimvariablenameAstype
Dim,ofcourse,couldalsobeStatic,PrivateorPublic.Astypeisoptional.Ifthisis
leftoffthedeclarationstatement,thevariabletypeisassumedtobevariant.
Oftenitmaybeusefultohaveconstantvaluesinthecode.Althoughaconstantresembles
avariable,itcannotbemodified.ConstantsaredeclaredwithaConstantstatementofthe
type:
ConstPi=3.14159

VisualBasicforApplications(MAM23.Nov.98)

ProgramControl
ProgramcontrolreferstostatementswithintheVBAcodethatdirectthesequenceof
statementstobeexecuted.Thetwogeneraltypesofprogramcontrolarebranchingand
looping.
Branching
Branchingisusedtoselectalternativepathswithinacodebasedonsomespecified
condition(s).Therearetwotypesofbranchingstatements,IfstatementsandSelectCase
statements.
Ifsequenceshavethefollowingformat:
If(logicalcondition1)Then
Statements
ElseIf(logicalcondition2)Then
Statements
Else
Statements
EndIf
TheIfstatementfirsttestslogicalcondition1.Iftrue,thenextseriesofstatementsis
executed.Ifnot,thenextseriesofstatementsarebypassedandprogramexecutionmoves
ontotheElseIfstatement.Ifthelogicalcondition2istrue,thenextsetofstatementsis
executed.Iflogicalcondition2isfalse,thestatementsaftertheElsekeywordareskipped.
EndIfdefinestheendoftheIfsequence.
ThissequencecanhaveanynumberofElseIfstatements(includingnone).TheElse
keywordcanbealsoeliminated.Ifthisisdone,thestatementsinsidetheIfsequenceare
onlyexecutediflogicalcondition1istrue,otherwisethewholesequenceissimply
skipped.
Logicalconditionsareexpressionsthatcanbetested.Thesearegenerallyoftheform
lhexpression{<=>}rhexpression

VisualBasicforApplications(MAM23.Nov.98)

Inthisstatementthelhexpressioniscomparedtotherhexpressionwithatestoperator
(<,=,or>).Thesymbols<,=,and>canbecombinedtoformotheroperatorsaswell.
Forexample,<=meanslessthanorequaltoand<>meansnotequalto
TheSelectCasestatementisusedwhenthereareanumberofdifferentspecificcases
tobeselectedfrom,asopposedtomakingabranchbasedonalogicalcondition.Select
Casestatementshavethefollowingformat.
SelectCasetestexpression
Caseexpressionlist1
Statements
Caseexpressionlist2
Statements
CaseElse
Statements
EndSelect
Thetestexpressionisevaluatedoncetodeterminewhichcaseistobeselected.Selection
isbasedonwhichexpressionlistthetestexpressionequals.Ifitequalsnoneofthe
expressionlists,thentheCaseElsestatementsareexecuted.
Looping
Loopingisusedtoexecuteagivensequenceofcoderepetitively,perhapswhilechanging
somecounterwithintheloopsothatthecodeisexecutedoverarangeofvariables.In
VBAtherearetwokindsofloops,For/NextandDo/Loop.For/Nexthasaformof:
Forcounter=startToendStepstepsize
Statements
Nextcounter
Anothersimilartypesequence,calledtheForEach/Nextsequencecanbeusedfora
collectionofobjects.ThereaderisreferredtotheExcelVBAmanualformore
informationonthis.
Counteristhevariablethatischangedduringeachsubsequentexecutionoftheloop
sequence.Counterstartsoffwithavalueofstart,endswithavalueofendandis
VisualBasicforApplications(MAM23.Nov.98)

incrementedineachsubsequentexecutionbyavalueofstepsize.TheNextstatement
definestheendoftheexecutedstatements.TheFor/Nextsequenceisexecutedafixed
numberoftimes,andisusefulfordoingrecurringcalculationsoverarangeofcounter
values.
TheDo/Loopsequence,ontheotherhand,ismoregenerallyusedforloopswherea
logicaltestdefineswhenaloopshouldbeterminated.Do/Loopsequenceshavethe
followingformat.
Do{WhileorUntillogicalcondition}
Statements
Loop{WhileorUntillogicalcondition}
OneandonlyoneWhileorUntilkeyword(alongwithitsassociatedlogicalcondition)
shouldbeusedinagivenDo/Loop.ThekeywordWhilemeansthattheloopwillbe
executedsolongasthegivenlogicalconditionremainstrue.Inthissituationthe
logicalconditionwouldgenerallystartouttrueandthenswitchtofalseatsome
subsequentexecutionoftheloop.ThekeywordUntil,ontheotherhand,meanstheloop
willbeexecuteduptothetimethelogicalconditionbecomestrue,havinggenerally
startedoutasfalse.
WhethertheWhileorUntilkeywordisplacedwiththeDoortheLoopstatement
dependsonwhetheryoudesirethelogicalconditiontobecheckedbeforetheloopis
executedorafter.Thischoiceiscasespecific,andisgenerallymadeonthebasisof
whetheryouwantthelooptobeexecutedatleastonceornot.Manyprogrammingtasks
canbeconstructedtouseanyoftheabove.
NotethatitispossibleforDo/Loopsequencestogetintoaninfiniteloop.Thisrefers
tothesituationwhenthedesiredconditionisneversatisfied.This,ofcourse,shouldbe
avoided(butisoftentheresultofaprogrammingerror).Ifthishappens,simplypressthe
EsckeytoterminatetheVBAprocedure,andthenproceedtodebugyourcode.
Loopingsequencescanalsobeexitedifsomeconditionismetpriortodoingallofthe
specifiedloops.TheExitForstatementisusedtoexitdirectlyfromaFor/Nextloopand
theExitDoisusedtoexitaDo/Loop.
Loopsequencesofanytypemaybenested,thatis,oneloopedmaybecalledinsideof
anotherloop.Asmanynestinglevelsasdesiredcanbeused.Itiscommoncoding
practicetoindentnestedstructurestomakethemmorereadable.
References
VisualBasicUsersGuide,MicrosoftCorporation(199394).
VisualBasicforApplications(MAM23.Nov.98)

VisualBasicOnlineMagazine:http://www.vbonline.com/vbmag/

VisualBasicforApplications(MAM23.Nov.98)