vba and macros - freemonsieurgael.free.fr/docs/prateekagnihotri.pdfvba and macros vba is a major...
Post on 28-May-2020
35 Views
Preview:
TRANSCRIPT
VBAANDMACROS
VBAisamajordivisionofthestand-aloneVisualBasicprogramminglanguage.ItisintegratedintoMicrosoftOfficeapplications.ItisthemacrolanguageofMicrosoftOfficeSuite.Previouslyitwasknownasxlm.
HowtoaccessVBAinMS-Excel-
1. PressALT+F11.2. GoToDeveloperTab->ClickVisualBasicIcon.Seeimagebelow.
Everyorganizationintoday’sworldreliesuponvariouskindsofdatabasesforstorageofallkindsofdata.Dataisthebackboneineveryaspectofanorganization,beitmanagement,marketing,finance,planning,technicalandproductionservices,issues,environmentetc.ExcelcanbeusedasadatabaseorwecancallitaspreadsheetapplicationwhichmanipulatesthedatastoredinitorsomeotherdatabaselikeSQLServer,Oracledatabase,MySQLetc.Excelhasvariousfeatureslikeimplementingformulas,developingpivots,charts.ThemostimportantfeatureofexcelisthemacroprogramminglanguagecommonlyknownasVBAusedwithinexceltodevelopmacros.
VBAmeansvisualbasicforapplications.Officialnameis“VisualBasic,ApplicationsEdition.VBAisthevastestlanguageamongstallthehighlevellanguages.VBAisaneventdriven;objectorientedprogramminglanguagefromMicrosoftthatisnowprimarilyusedwithMicrosoftofficeapplicationssuchasMS-Excel,MS-WordandMS-PowerPoint.
SomefeaturesofVBAareasfollows–
1.)VBAisahighlevellanguagewhichanyoneknowingMSapplicationslikeexcelorwordcanlearn.Thislanguagehelpsincreatingamacrowhichisnothingbutaseriesofinstructionsforatasktobeperformedautomatically.
2.)VBAenablesusertoautomaterepetitivetaskssoastoreducethemanualeffort.
3.)VBAnotonlyoffersmacrostobecreatedbutalsoallowsusertocreateUDFsi.e.userdefinedfunctions.Thesefunctionsoncebuiltareincorporatedinthelibrarywithallotherexcelfunctions.
4.)VBAworksonwindowsmachinesoisplatformdependent.
5.)VBAhelpsineliminatingwasteandisbasedonagilemethodology.
6.)VBAisanOOPi.e.objectorientedlanguage.EverythinginVBAistreatedasanobject.
7.)VBAcanbeusedtoconnecttoanydatabaseotherthanexcelitselflikeMySQL,Oracleetc.Itmakestheconnectionwiththebackenddatabaseandmanipulatesdataasrequired.
8.)VBAcanbeusedwithallMicrosoftapplicationslikeMS-Word,MS-Access,Outlook,MS-Powerpointetc.
9.)VBAmacrosareuserspecificandnotauthorspecific.Theycanbemodified,deletedbytheuserwhowantstorunit.
10.)VBAinMS-OfficeprovidesmanyinbuiltfunctionsthatausercanusetobuildcodeinExcel.
11.)VBAallowsuserstorecordthemacrosandthentweakthemforspecificpurposes.
12.)VBAisalsousedbydataanalysts,finance&marketanalystsfordatamanipulation,modelingetc.Mathematiciansuseitduetoitsvastlibraryfullofformulasandfunctions.
13.)VBAallowscodertoswitchoffcalculationsandsheetsupdateduringexecutionofcodewhichspeedsuptheprocessing.
14.)VBAisaSelf-interpretedprogramminglanguage.CompilingisveryeasyinVBA.
15.)VBAcanhelpbuiltPowerfultoolsinMSOfficeusinglogicalprogramming.
16.)ThereisafamousonelineraboutVBAthatthereisnothingwhichcan’tbedonebyVBA.
VBAEnablesend-userprogrammingandisusedinMSOfficeapplicationsastoldabove.ItencapsulatesFormulaeandmacrosforeasytasks.Followingarethecontentswhichwillbecoveredinthisbook–
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.
WorksheetsareacollectionofalltheWorksheetobjectsintheactiveworkbook.
Worksheets(3)refertothe3rdworksheetofcurrentactiveworkbook.
Worksheets(“Sheet1”)refertotheworksheetnamed“Sheet1”.
VBA–Objects
VBAobjectsareWorksheet,Workbook,Range,Cell,Chart,Name,etc.
Worksheets(Sheet1)isanObjectReferringtotheFirstSheet
Range(“A1:A5”)isanObjectReferringtoaRangefromRow1,Column1toRow5,Column1
Range(“A1:B5”)isanObjectReferringtoaRangefromRow1,Column1toRow5,Column2.
Cells(1,1)orRange(“A1”)isanObjectReferringtoRange“A1”.Cells(2,1)orRange(“A2”)isanObjectReferringtoRange“A2”.
VBA–Properties,MethodsandEvents.
PropertiesarethePhysicalCharacteristicsofobjects–ForexampleWorksheets.Count,Worksheets.Visible=False,Range(“A1:B15”).Rows.Count,Range(“A1:A50”).Font.Bold=True.
MethodsaretheActionsthatCanbePerformedbyObjectsoronObjectsForExampleWorksheets.Save,Worksheets.Calculate,Range(“A1:A50”).ClearContents,ActiveCell.CopySpecial.
ObjectsCanRespondtoEvents,SuchasMouseClick,DoubleClickonaCell,ActiveaWorksheet,Open/Close/SaveaWorkbook,etc.
VBA–Macro
VBAMacrostartswith‘sub’keywordandendswith‘EndSub’Theformatisasfollows–
SubAny_Name()
‘YourCodehereinbetween
EndSub
VBAmacrocanbeassignedtoanyformcontrolforexampleabuttonoritcanbeexecutedindependentlyviasomecommandoptionassignedtoit.VBAmacrocanalsobeexecutedfromtheMacroswindowintheviewtabofthemenubar.
OnceVBAcodeiswrittenintheexcelfileitshouldbesavedwith.xlsmextension.SomeVBAShortcutsareasfollows–
ALT+F11-ToviewVBAEditorALT+F8-TodisplayallmacrosALT+Q-TocloseVBAEditorandreturntoExcelF5-TorunaMacroF2-DisplayObjectBrowserF7-DisplaycodeeditorF1-DisplayhelpCtrl+G–ImmediateWindowF4–PropertieswindowCtrl+R–ProjectExplorer.
Seebelowfortheshortcutsdescribedabove.
GetStarted–
1.)EnableDeveloperTabFirst–GoToFileTab->
2.)GoToOptions->AWindowwillappearlikethis->
3.)GoToCustomizeRibbonandcheckDeveloperTabasshownbelowandthenpressOK->
4.)Developertabwillbeshownasbelowonyourexcelsheet.Thedevelopertabappearsonthemenubar.
BeforeCreatingyourfirstmacromakesuretodofollowingthings–
1.)PressALT+F11-VBAIDEwillgetopened.
2.)NowclickToolstabinthemenubaronthetopoftheIDE.SelectOptionsfromthedropdownasshownbelowinthesnapshot.
3.)Awindowwillappear.Justcheckwhetherthethingsshowninthesnapshotbelowarecheckedornot.
LetUsWriteOurFirstVBACodebyinsertingFormcontrol.
1.)OnceyouhavedevelopertabonyourmenubarclickitandthengotoInsertinsidethedevelopertabandclickitasshownbelow.
2.)Formcontrolswindowappearsasshownabove,Nowclickonthe
buttonandInsertasshownbelow.
3.)RightClicktheButton1andassignanewmacro.VBAIDEwillgetopened.WriteasimpleVBACodeisasfollows–
SubButton1_Click()
MsgBox“Hi,IhaveinsertedthismoduletowritemyfirstVBACode”
EndSub
4.)Seebelowforthecodeincodewindowandtheoutputinthemessageboxthatappears.
HowtoaccessVBAEditorwithoutinsertingformcontrol–
1.)PressALT+F11inyourexcelfile.Awindowwillopenasshownbelow.
2.)NowInsertamoduleinitasshownbelow.Module1isthenameofthefirstmoduleinsertedasshownbelowwithredarrows.
3.)NowintheabovemodulewindowwriteapieceofVBAcodeasfollows.
Subfirst_Program()
MsgBox“Hi,IhaveinsertedthismoduletowritemyfirstVBACode”
EndSub
Seebelowforthecodeincodewindowandtheoutputinthemessageboxthatappears.
TheCommentsinVBA
StatementsorsentencesinVBAcodestartingwithsinglequoteorREMkeywordisacomment.SeebelowinVBAIDE.
TheConceptofVariables
ThefollowingaretheruleswhennamingthevariablesinExcelVBA-
Theymustnotexceed40charactersTheymustcontainonlyletters,numbersandunderscorecharactersNospacingisallowedItmustnotbeginwithanumberExamples–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=0ThenMsgBox‘HiZero’ElseIfIndex=1ThenMsgBox‘HiOne’ElseMsgBox‘HiNone’EndIf
2.)Switchcase
1. SelectCaseIndexCase0MsgBox‘HiZero’Case1MsgBox‘HiOne’CaseElseMsgBox‘HiNoneEndSelect
SeebelowinVBAIDE
LoopStructuresinVBA
1.)Theloopstructuresareusedwhenrepetitiveworkisbeingdone.
2.)Loopsmaketheexecutionsequentiallygiventhejump.Forexampleifaprocessisrequiredtoberun10timesthenweuse1to10.Ifaprocessisrequired
tobedoneonlyoddtimesthenwefo1to10instepsof2.
3.)TherearevariouskindsofloopstatementsinVBA.
1. ForNextLoop2. WhileWendLoop3. Dowhileloop4. Etc
4.)SeebelowforcodeinIDE.
Displayingtableof5
Workingwithworksheets
1.)AsalreadyexplainedearliereverythinginVBAisanobjectforexampleworksheet,Range,Celletc.
2.)Worksheets(“Sheet1”).cells(1,2).valuereferstotheB1inSheet1ofexcelworkbook.
ErrorHandling–Followingarethewaysforit
1.)OnErrorGoToLineNumber(GoestothespecifiedlinenumberandCoderesumesfrom)
2.)OnErrorGoTo0(DisablesenablederrorhandlerinthecurrentprocedureandresetsittoNothing.)
3.)OnErrorGoTo-1(DisablesenabledexceptioninthecurrentprocedureandresetsittoNothing.)
4.)OnErrorresumeNext(Controlgoestothestatementimmediatelyafter
theerroredstatement)
ArraysManipulationinVBA
1.)Arraysareasignificantpartofanyprogramminglanguagewhichactsasfrontendprocessingdatabase.
2.)UnlikevariablesArraysareusedtostoremultiplevaluesofsamedatatype.Arraysstorehomogeneousdata.
3.)Arraystoresthevaluesonthebasisofkeyvaluepairi.e.arrayindexesthevaluesstoresinit.TheLowerBoundandUpperboundcanbesetmanuallyforanarray.
4.)Ifyoutrytoaccessanyindexofthealreadybuiltarraythatdoesnotexistanerrornamed“SubscriptoutofRange”occurs.
5.)ArrayscanbeoftwotypeswhichareStaticandDynamic.Theformerisusedwhenthesizeofanarrayremainsthesamethroughoutintheprocedurewhilethelatterpermitstheusertoregulatethesizeofanarrayatruntime.
6.)MostlyinVBAsingledimensionalarrayisusedalthoughVBAprovidesthefunctionalityofmulti-dimensionalarrays.
7.)AusercanonlypassanarraytoaprocedureusingByReferenceandausercanreturnanarrayfromafunctionbutthearray,itisassignedto,mustnotbecurrentlyallocated.
8.)AnyworksheetinaworkbookhasdataintheformofRowsandcolumns.Sobasicallythedatastoredistwodimensional.Anydatafromexcelsheetcanbedirectlytransferredtoatwodimensionalarrayandviceversaformanipulationpurposes.
RecordingaVBAMacro
1.)Let’srecordamacro.
2.)Gotoexcelwhileyouareworkingon.ClickViewinmenubarandthenclickMacrosontheextremeright.Adropdownwillappear.ClickontheRecordMacrojustbelowViewMacros.Seebelow.
3.)Nowonceyouhaveclickedtherecordmacro,whateveractivityyouwilldointhatexcelfilewillberecorded.
4.)TheMacrorecordingisusefulwhenyouaredoingsomerepetitivetaskonthedailybasis.
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’scells.Somecodelinesareasfollows–
1. Worksheets(“Sheet1”).cells(1,1).value=9002. Worksheets(“Sheet1”).cells(1,1).value=1003. Worksheets(“Sheet1”).Cells(4,2).Value=Worksheets(“Sheet1”).Cells(1,
2).Value+Worksheets(“Sheet1”).Cells(2,2).Value4. Completecodeisshownbelowinthesnapshot.
Outputisasfollows–
2.)CheckingifaNumberenteredbytheuserisEvenorOdd.SeeCode–
Output–
3.)CodeforSortingacolumn–
Output–
4.)CodetosendamailfromExcelviaOutlook.Justpastethecodeasshowninthesnapshotbelowandchangeyourfieldsaccordingly.
Output–
5.)ConcatenatingTwoStringsinVBA.Seecodebelow-
6.)SomeStringmanipulationFunctionsinVBA.Seecodeandoutputasshownbelow.
7.)WorkingwithDocfile–
8.)SheetManipulation.AddingnewSheet,Deletinganexistingsheet,renamingasheetandcleaningthewholesheetetc.
9.)WorkingwithArraysSubArrays_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
Theabovecodedescribestwokindsofarrays.SingledimensionalandDoubledimensional.Itshowshowtoentervaluesinthesekindsofarrays,howtoaccesstheelementsofmulti-dimensionalarray,howtoperformoperationslikesum,sort,eraseetc.
10.)DisplayingNameofeachworksheetandusageofForEach.
11.)Hidingasheet,copyandpasteintosamesheetandanothersheet.
12.)Removingduplicatesfromacolumninexcelworksheet.
SeetheInputandOutputasshownbelow–
13.)HowtogenerateaRandomNumber?
Outputisasfollows–
14.)CreatingGraphUsingVBA.Seethecodebelow–
Let’sSaywehavethefollowingdata.Wewillmakeacodetorepresentthiswithagraph.
Code-Bychangingthedesiredvaluesinthecodebelowyoucancreateagraphforanydata.
Output–
15.)Createapatternusingnestedloops–Thecodebelowwillteachyouhowtousenestedloopsandcreatingpatternsofvariouskindsbyjustmanipulatingtheseloops.
Output–
16.)Creatingpivotbyrecordingandthentweakitasperyourrequirement.
Let’stakethesameolddata–
RecordedcodeinVBA–
Output–
17.)Codetoswapvaluespresentincells.
InputandOutputaftercodeexecution–
18.)VBAcodetodeletealldatafromthesheetandremovingthefiltersifthey
exist.
InputSheetwithDataandfiltersapplied
Outputafterthecodeisexecuted–
Allthedatahasbeendeletedandfiltershavebeenremoved.
19.)VBAcodetocreateanExamspreadsheetofstudentsandtheirgradesubmissions.
InputSheetcontainingstudentnamesandmarksobtainedinvarioussubjects.
GradeCriteria–
VBACodeforcalculations–
Submarks_calculator()
Dimstudents(1To6)AsString
DimmaxmarksAsInteger
DimmarksobtainedAsLong
maxmarks=0
marksobtained=0
Fori=4To10
maxmarks=maxmarks+Worksheets(“Sheet1”).Cells(i,3).Value
Nexti
Worksheets(“Sheet1”).Cells(i,3).Value=maxmarks
Forj=1To6
Fori=4To10
marksobtained=marksobtained+Worksheets(“Sheet1”).Cells(i,j+3).Value
Nexti
Worksheets(“Sheet1”).Cells(i,j+3).Value=marksobtained
If((marksobtained*100)/maxmarks)<40Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“F”
EndIf
If((marksobtained*100)/maxmarks)>=40Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“E”
EndIf
If((marksobtained*100)/maxmarks)>=55Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“D”
EndIf
If((marksobtained*100)/maxmarks)>=70Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“C”
EndIf
If((marksobtained*100)/maxmarks)>=75Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“C+”
EndIf
If((marksobtained*100)/maxmarks)>=80Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“B”
EndIf
If((marksobtained*100)/maxmarks)>=85Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“B+”
EndIf
If((marksobtained*100)/maxmarks)>=90Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“A”
EndIf
If((marksobtained*100)/maxmarks)>=95Then
Worksheets(“Sheet1”).Cells(i+1,j+3).Value=“A+”
EndIf
marksobtained=0
Nextj
EndSub
SnapshotofcodeinIDE
SeeOutputinBoldRedbelow–
20.)Generatingdifferenttypesofgraphfromagivendata.
Let’sseethedatafirst.LookBelowforthedataandthecontrolbuttonswhichwillshowdifferenttypesofgraphsonclicking.
CodeforGeneratingBarGraphisasfollows–
Output–
CodeforGeneratingLineGraphisasfollows–
Outputisasfollows–
CodeforChartTypeofGraph–
Outputisasfollows–
21.)Codetodisplayfactorialofanumber.Subfact()
Dima,factAsInteger
a=InputBox(“Enteranynumberforitsfactorialcalculation”)
fact=a
Fori=a-1To1Step-1
fact=fact*i
Nexti
MsgBoxfact
EndSub
Output–
top related