VBAANDMACROS
VBAisamajordivisionofthestand-aloneVisualBasicprogramminglanguage.Itis
integratedintoMicrosoftOfficeapplications.ItisthemacrolanguageofMicrosoftOffice
Suite.Previouslyitwasknownasxlm.
HowtoaccessVBAinMS-Excel1. PressALT+F11.
2. GoToDeveloperTab->ClickVisualBasicIcon.Seeimagebelow.
Everyorganizationintoday’sworldreliesuponvariouskindsofdatabasesforstorageof
allkindsofdata.Dataisthebackboneineveryaspectofanorganization,beit
management,marketing,finance,planning,technicalandproductionservices,issues,
environmentetc.Excelcanbeusedasadatabaseorwecancallitaspreadsheet
applicationwhichmanipulatesthedatastoredinitorsomeotherdatabaselikeSQL
Server,Oracledatabase,MySQLetc.Excelhasvariousfeatureslikeimplementing
formulas,developingpivots,charts.Themostimportantfeatureofexcelisthemacro
programminglanguagecommonlyknownasVBAusedwithinexceltodevelopmacros.
VBAmeansvisualbasicforapplications.Officialnameis“VisualBasic,Applications
Edition.VBAisthevastestlanguageamongstallthehighlevellanguages.VBAisan
eventdriven;objectorientedprogramminglanguagefromMicrosoftthatisnowprimarily
usedwithMicrosoftofficeapplicationssuchasMS-Excel,MS-WordandMS-PowerPoint.
SomefeaturesofVBAareasfollows–
1.)VBAisahighlevellanguagewhichanyoneknowingMSapplicationslike
excelorwordcanlearn.Thislanguagehelpsincreatingamacrowhichisnothing
butaseriesofinstructionsforatasktobeperformedautomatically.
2.)VBAenablesusertoautomaterepetitivetaskssoastoreducethemanual
effort.
3.)VBAnotonlyoffersmacrostobecreatedbutalsoallowsusertocreateUDFs
i.e.userdefinedfunctions.Thesefunctionsoncebuiltareincorporatedinthe
librarywithallotherexcelfunctions.
4.)VBAworksonwindowsmachinesoisplatformdependent.
5.)VBAhelpsineliminatingwasteandisbasedonagilemethodology.
6.)VBAisanOOPi.e.objectorientedlanguage.EverythinginVBAistreatedas
anobject.
7.)VBAcanbeusedtoconnecttoanydatabaseotherthanexcelitselflike
MySQL,Oracleetc.Itmakestheconnectionwiththebackenddatabaseand
manipulatesdataasrequired.
8.)VBAcanbeusedwithallMicrosoftapplicationslikeMS-Word,MS-Access,
Outlook,MS-Powerpointetc.
9.)VBAmacrosareuserspecificandnotauthorspecific.Theycanbemodified,
deletedbytheuserwhowantstorunit.
10.)VBAinMS-Officeprovidesmanyinbuiltfunctionsthatausercanusetobuild
codeinExcel.
11.)VBAallowsuserstorecordthemacrosandthentweakthemforspecific
purposes.
12.)VBAisalsousedbydataanalysts,finance&marketanalystsfordata
manipulation,modelingetc.Mathematiciansuseitduetoitsvastlibraryfullof
formulasandfunctions.
13.)VBAallowscodertoswitchoffcalculationsandsheetsupdateduring
executionofcodewhichspeedsuptheprocessing.
14.)VBAisaSelf-interpretedprogramminglanguage.Compilingisveryeasyin
VBA.
15.)VBAcanhelpbuiltPowerfultoolsinMSOfficeusinglogicalprogramming.
16.)ThereisafamousonelineraboutVBAthatthereisnothingwhichcan’tbe
donebyVBA.
VBAEnablesend-userprogrammingandisusedinMSOfficeapplicationsastoldabove.
ItencapsulatesFormulaeandmacrosforeasytasks.Followingarethecontentswhichwill
becoveredinthisbook–
1.)ConceptofVariablesandDataTypes.
2.)ConditionalandLogicaloperators.
3.)NestedLoops,SwitchCases,conditionalstatementsetc.
4.)ErrorHandling.
5.)Objecthandling.
6.)ConceptofsingleandmultipledimensionalarraysinVBA.
7.)Stringmanipulation.
8.)MacroRecording.
VBA–Collections
AGroupofSimilarObjectsthatShareCommonProperties,Methodsand
EventsSuchasWorkbooks,Worksheets,etc.arecalledCollections.
WorksheetsareacollectionofalltheWorksheetobjectsintheactive
workbook.
Worksheets(3)refertothe3rdworksheetofcurrentactiveworkbook.
Worksheets(“Sheet1”)refertotheworksheetnamed“Sheet1”.
VBA–Objects
VBAobjectsareWorksheet,Workbook,Range,Cell,Chart,Name,etc.
Worksheets(Sheet1)isanObjectReferringtotheFirstSheet
Range(“A1:A5”)isanObjectReferringtoaRangefromRow1,Column1
toRow5,Column1
Range(“A1:B5”)isanObjectReferringtoaRangefromRow1,Column1
toRow5,Column2.
Cells(1,1)orRange(“A1”)isanObjectReferringtoRange“A1”.Cells(2,
1)orRange(“A2”)isanObjectReferringtoRange“A2”.
VBA–Properties,MethodsandEvents.
PropertiesarethePhysicalCharacteristicsofobjects–Forexample
Worksheets.Count,Worksheets.Visible=False,Range(“A1:B15”).Rows.
Count,Range(“A1:A50”).Font.Bold=True.
MethodsaretheActionsthatCanbePerformedbyObjectsoronObjects
ForExampleWorksheets.Save,Worksheets.Calculate,
Range(“A1:A50”).ClearContents,ActiveCell.CopySpecial.
ObjectsCanRespondtoEvents,SuchasMouseClick,DoubleClickona
Cell,ActiveaWorksheet,Open/Close/SaveaWorkbook,etc.
VBA–Macro
VBAMacrostartswith‘sub’keywordandendswith‘EndSub’
Theformatisasfollows–
SubAny_Name()
‘YourCodehereinbetween
EndSub
VBAmacrocanbeassignedtoanyformcontrolforexampleabuttonoritcanbe
executedindependentlyviasomecommandoptionassignedtoit.
VBAmacrocanalsobeexecutedfromtheMacroswindowintheviewtabofthe
menubar.
OnceVBAcodeiswrittenintheexcelfileitshouldbesavedwith.xlsmextension.
SomeVBAShortcutsareasfollows–
ALT+F11-ToviewVBAEditor
ALT+F8-Todisplayallmacros
ALT+Q-TocloseVBAEditorandreturntoExcel
F5-TorunaMacro
F2-DisplayObjectBrowser
F7-Displaycodeeditor
F1-Displayhelp
Ctrl+G–ImmediateWindow
F4–Propertieswindow
Ctrl+R–ProjectExplorer.
Seebelowfortheshortcutsdescribedabove.
GetStarted–
1.)EnableDeveloperTabFirst–GoToFileTab->
2.)GoToOptions->AWindowwillappearlikethis->
3.)GoToCustomizeRibbonandcheckDeveloperTabasshownbelowandthen
pressOK->
4.)Developertabwillbeshownasbelowonyourexcelsheet.The
developertabappearsonthemenubar.
BeforeCreatingyourfirstmacromakesuretodofollowingthings–
1.)PressALT+F11-VBAIDEwillgetopened.
2.)NowclickToolstabinthemenubaronthetopoftheIDE.Select
Optionsfromthedropdownasshownbelowinthesnapshot.
3.)Awindowwillappear.Justcheckwhetherthethingsshowninthe
snapshotbelowarecheckedornot.
LetUsWriteOurFirstVBACodebyinsertingFormcontrol.
1.)Onceyouhavedevelopertabonyourmenubarclickitandthengoto
Insertinsidethedevelopertabandclickitasshownbelow.
2.)Formcontrolswindowappearsasshownabove,Nowclickonthe
buttonandInsertasshownbelow.
3.)RightClicktheButton1andassignanewmacro.VBAIDEwillget
opened.WriteasimpleVBACodeisasfollows–
SubButton1_Click()
MsgBox“Hi,IhaveinsertedthismoduletowritemyfirstVBACode”
EndSub
4.)Seebelowforthecodeincodewindowandtheoutputinthemessageboxthat
appears.
HowtoaccessVBAEditorwithoutinsertingformcontrol–
1.)PressALT+F11inyourexcelfile.Awindowwillopenasshownbelow.
2.)NowInsertamoduleinitasshownbelow.Module1isthenameofthe
firstmoduleinsertedasshownbelowwithredarrows.
3.)NowintheabovemodulewindowwriteapieceofVBAcodeasfollows.
Subfirst_Program()
MsgBox“Hi,IhaveinsertedthismoduletowritemyfirstVBACode”
EndSub
Seebelowforthecodeincodewindowandtheoutputinthemessageboxthatappears.
TheCommentsinVBA
StatementsorsentencesinVBAcodestartingwithsinglequoteorREMkeywordis
acomment.SeebelowinVBAIDE.
TheConceptofVariables
ThefollowingaretheruleswhennamingthevariablesinExcelVBATheymustnotexceed40characters
Theymustcontainonlyletters,numbersandunderscorecharacters
Nospacingisallowed
Itmustnotbeginwithanumber
Examples–var1,my_varetc.
SeebelowinVBAIDE
DataTypes
1.)Numeric
2.)NonNumeric(String,Date,Boolean,Object,variant)
Declarationofvariables
1.)Implicit(Variableisinitializedandisvariantbydefault)
2.)Explicit(Example–DimvarasInteger)
ConditionalandLogicalOperators
1.)Conditional–(=,<,>,>=,<=,<>etc.)
2.)Logical(AND,OR,XORandNOT)
ControlStructures
1.)IfthenElse
1. IfIndex=0Then
MsgBox‘HiZero’
ElseIfIndex=1Then
MsgBox‘HiOne’
Else
MsgBox‘HiNone’
EndIf
2.)Switchcase
1. SelectCaseIndex
Case0
MsgBox‘HiZero’
Case1
MsgBox‘HiOne’
CaseElse
MsgBox‘HiNone
EndSelect
SeebelowinVBAIDE
LoopStructuresinVBA
1.)Theloopstructuresareusedwhenrepetitiveworkisbeingdone.
2.)Loopsmaketheexecutionsequentiallygiventhejump.Forexampleif
aprocessisrequiredtoberun10timesthenweuse1to10.Ifaprocessisrequired
tobedoneonlyoddtimesthenwefo1to10instepsof2.
3.)TherearevariouskindsofloopstatementsinVBA.
1. ForNextLoop
2. WhileWendLoop
3. Dowhileloop
4. Etc
4.)SeebelowforcodeinIDE.
Displayingtableof5
Workingwithworksheets
1.)AsalreadyexplainedearliereverythinginVBAisanobjectfor
exampleworksheet,Range,Celletc.
2.)Worksheets(“Sheet1”).cells(1,2).valuereferstotheB1inSheet1of
excelworkbook.
ErrorHandling–Followingarethewaysforit
1.)OnErrorGoToLineNumber(Goestothespecifiedlinenumberand
Coderesumesfrom)
2.)OnErrorGoTo0(Disablesenablederrorhandlerinthecurrent
procedureandresetsittoNothing.)
3.)OnErrorGoTo-1(Disablesenabledexceptioninthecurrentprocedure
andresetsittoNothing.)
4.)OnErrorresumeNext(Controlgoestothestatementimmediatelyafter
theerroredstatement)
ArraysManipulationinVBA
1.)Arraysareasignificantpartofanyprogramminglanguagewhichacts
asfrontendprocessingdatabase.
2.)UnlikevariablesArraysareusedtostoremultiplevaluesofsamedata
type.Arraysstorehomogeneousdata.
3.)Arraystoresthevaluesonthebasisofkeyvaluepairi.e.arrayindexes
thevaluesstoresinit.TheLowerBoundandUpperboundcanbesetmanuallyfor
anarray.
4.)Ifyoutrytoaccessanyindexofthealreadybuiltarraythatdoesnot
existanerrornamed“SubscriptoutofRange”occurs.
5.)ArrayscanbeoftwotypeswhichareStaticandDynamic.Theformer
isusedwhenthesizeofanarrayremainsthesamethroughoutintheprocedure
whilethelatterpermitstheusertoregulatethesizeofanarrayatruntime.
6.)MostlyinVBAsingledimensionalarrayisusedalthoughVBA
providesthefunctionalityofmulti-dimensionalarrays.
7.)AusercanonlypassanarraytoaprocedureusingByReferenceanda
usercanreturnanarrayfromafunctionbutthearray,itisassignedto,mustnotbe
currentlyallocated.
8.)AnyworksheetinaworkbookhasdataintheformofRowsand
columns.Sobasicallythedatastoredistwodimensional.Anydatafromexcel
sheetcanbedirectlytransferredtoatwodimensionalarrayandviceversafor
manipulationpurposes.
RecordingaVBAMacro
1.)Let’srecordamacro.
2.)Gotoexcelwhileyouareworkingon.ClickViewinmenubarandthen
clickMacrosontheextremeright.Adropdownwillappear.ClickontheRecord
MacrojustbelowViewMacros.Seebelow.
3.)Nowonceyouhaveclickedtherecordmacro,whateveractivityyou
willdointhatexcelfilewillberecorded.
4.)TheMacrorecordingisusefulwhenyouaredoingsomerepetitivetask
onthedailybasis.
5.)TheMacrorecordedcanbetweakedfurtheraspertheuser’sneed.
AnExampleVBA
SubButton1_Click()
DimmyValueAsVariant
‘Displaying‘AMessage’
MsgBox“Hi!IamaVBAcoder”
‘Addingtwovalues
MsgBox2+3
‘Addingtwovaluesinworksheet
Worksheets(“Sheet1”).Cells(1,3)=Worksheets(“Sheet1”).Cells(1,1)+Worksheets
(“Sheet1”).Cells(1,2)
‘InputBoxandAssigningvaluetoRangeA2
MyValue=InputBox(“Givemesomeinput”)
Range(“A2”)=MyValue
‘Copyandpasterange
Range(“A1:A2”).Select
Selection.Copy
Range(“L1”).Select
ActiveSheet.Paste
EndSub
CodeinIDE–VBAWindow.
Outputisasfollows-
SAMPLEVBACODESFORYOURUSAGE–
1.)VBAcodeforsimplemathematicalcalculationsusingvaluesinworksheet’s
cells.Somecodelinesareasfollows–
1. Worksheets(“Sheet1”).cells(1,1).value=900
2. Worksheets(“Sheet1”).cells(1,1).value=100
3. Worksheets(“Sheet1”).Cells(4,2).Value=Worksheets(“Sheet1”).Cells(1,
2).Value+Worksheets(“Sheet1”).Cells(2,2).Value
4. Completecodeisshownbelowinthesnapshot.
Outputisasfollows–
2.)CheckingifaNumberenteredbytheuserisEvenorOdd.SeeCode–
Output–
3.)CodeforSortingacolumn–
Output–
4.)CodetosendamailfromExcelviaOutlook.Justpastethecodeasshownin
thesnapshotbelowandchangeyourfieldsaccordingly.
Output–
5.)ConcatenatingTwoStringsinVBA.Seecodebelow-
6.)SomeStringmanipulationFunctionsinVBA.Seecodeandoutputasshown
below.
7.)WorkingwithDocfile–
8.)SheetManipulation.AddingnewSheet,Deletinganexistingsheet,
renamingasheetandcleaningthewholesheetetc.
9.)WorkingwithArrays
SubArrays_Manipulation()
DimCombineArrayAsString
‘WorkingWithArrays,Storingvalues1to10intheArraynamedArray1
CombineArray=””
DimArray1(1To10)AsInteger
Fori=1To10
Array1(i)=i
CombineArray=CombineArray&CStr(Array1(i))&“,”
Nexti
MsgBoxCombineArray
‘Storingtableofsay17inArray1
CombineArray=””
Fori=1To10
Array1(i)=17*i
CombineArray=CombineArray&CStr(Array1(i))&“,”
Nexti
MsgBoxCombineArray
‘DispalyingLowerBoundandUpperBoundofArray
MsgBoxLBound(Array1)
MsgBoxUBound(Array1)
‘Summingthearrayelements
DimsumArrayAsInteger
sumArray=0
Fori=1To10
sumArray=sumArray+Array1(i)
Nexti
MsgBoxsumArray
‘Erasingthecontentsofanarray
EraseArray1
‘WorkingwithTwodimesionalArray
DimArray2(1To5,1To5),counterAsInteger
counter=1
Fori=1To5
Forj=1To5
Array2(i,j)=counter
counter=counter+1
Nextj
Nexti
EndSub
CodeinVBAIDE