Академический Документы
Профессиональный Документы
Культура Документы
06/23/11 1
Excel401MacroExerciseWorkbook
ClassFiles>ICExercises>Excel401Advanced>Excel401Exercises
Contents
Introduc ontoExcelMacros..........................................4 TheDeveloperTab...........................................................6 Crea ngVBASubProcedureMacrosbyRecording........8 StepsforAssigning/Edi ngYourMacroShortcutKey....9 ExaminingandTes ngYourMacro.................................10 AbsolutevsRela veRecording.......................................11 AssigningaMacrotoaBu on.........................................11 SavingWorkbooksthatContainMacros.........................12 StoringMacrosinYourPersonalMacroWorkbook........12 Dele ngMacros...............................................................12 RecordingMacroExercises..............................................13 ReadingYourVBACode...................................................20 UnderstandingVBACodethroughPrac ce....................21 DebuggingYourVBACode ...............................................22 Crea ngandReadingCommentsinVBACode...............23 Prac cingwithVBA ..........................................................24 VBAFunc onProcedures................................................26
MacroDeni on: Amacroisasequenceofinstruc onsthatautomatessomeaspectofExcel sothatyoucanworkmoreecientlyandwithfewererrors. Theexampleattherightinsertsandformatstodaysdate. ProgramLanguage:InMicroso Oce,macrosarecomposedusingaprogrammingtool calledVisualBasicforApplica ons,orVBAforshort. ThereareTwoTypesofMacros: VBASubProcedures ASubprocedureisagroupofVBAstatementsthatperformsanac onwithExcel.Itisaseriesofcommandsthateithertheuser oranothermacrocanexecute. VBAFunc onProcedures AVBAFunc onprocedureisagroupofVBAstatementsthatperformsacalcula onandreturnsasinglevalue. CanbeexecutedbyanotherVBAprocedureorusedinworksheetformulas Func onprocedurescanonlybecreatedmanually
They automate repetitive tasks, thus saving time and improving efficiency. Make difficult tasks easier Provide a means of extending the usefulness of applications Can assist people in completing forms
Insert boiler plate text Automate a procedure you perform frequently Create custom commands Create a simplified front end for users who do not know much about Excel Expand formulas and worksheet functions
On the File tab, choose Options to open the Excel Options dialog box. Click Customize Ribbon on the left side of the dialog box. Under Choose commands from on the left side of the dialog box, select Popular Commands. Under Customize the ribbon on the right side of the dialog box, select Main tabs, and then select the Developer check box. Click OK.
DeveloperTabFunc ons
VisualBasic: Macros: OpenstheVisualBasicEditor Opensmacrodialogueboxcontaininglistofmacros Ini atesthemacrorecordingprocess Causesmacrosbeingrecordedtofunc onineitherabsoluteorrela vemode Ac vatesTrustCenterinwhichvariouslevelsofsecuritycanbeselected Addsarangeoftoolsandfunc ons Allowsforinterac onwithotherapplica ons Insertsbu ons,lists,boxes,labels,etc,forcrea ngformsandAc veXcontrols Usedfordesigningformsandmedia Listsofpresetproper esforuseinVBAcode DisplayscodeinVBAEditor Notper nenttothisclass Storesinforma onabouttheac vedocument
RecordMacro:
COMAddIns: Insert:
ViewCode: RunDialog:
DocumentPanel:
Crea ngVBASubProcedureMacrosbyRecording
1. 2. 3. 4. 5. 6. 7. 8. 9. SelectDeveloperTab ClickonRecordMacro RecordMacroDialogueBoxOpens Enteraname(noSpacesornonalphanumericcharacters) EnteraShortcutKey(le erfromAZ) StoreMacroin: Descrip onofmacro PressOK Performthefunc onsthatyouwantthe macrotoperform(seeAFatright) 10.ClickonStopRecording 11.Toini atethemacropressCtrl > Shi > Shortcut Key
1
StepsinCrea ngMacroInsertDate
HerearetheStepsweusedtoinsertandformatthecur rentdateandthecorrespondingcode: A. Selectrightadjacentcell B. OntheFormulasinDate & Timecategory,Insertcur rentdateusingToday() formula(SeeBbelow) C. Centertextincell D. Changebackgroundcolortoblue E. Changefontcolortowhite F. ChangefonttoArielRoundedMTBold
3 2 5 6
10 9 8
B 11
StepsforAssigning/Edi ngYourMacroShortcutKey
Whenyourecordamacro,Excelwillautoma callygiveyoutheop ontoassigna shortcutkeyforyourmacro.Onceyouveassignedyourshortcutkey,youwillseeinyour VBAcodeacommentthattellsyouwhattheassignedshortcutkeyis(picturedintheim ageonthebo omright).Changingthekeyboardshortcutinthecommentcodewillnot makeanyactualchangetotheini allyassignedkeyboardshortcut. Also,whencrea ngyourownmacrowithVBAcode,thisshortcutkeyassignmentdialog boxwillnotpopupandgiveyoutheop ontoassignashortcutkey. Ifthereisevera meyouneedtoassignoredityourshortcutkey,youwillneedtodo thefollowingsteps: 1. GototheDeveloperTab 2. ClicktheMacroBu on 3. Selectthenameofthemacroyoueitherwantto1.assignashortcutkeyto,or2.edit itsexis ngshortcutkey 4. ClicktheOp onsbu onintheMacrodialogbox 5. AssignoredityourshortcutkeyintheMacroOp onsdialogbox
Examining&Tes ngYourMacro
FromtheDevelopertabselectView Macro, andtheboxpicturedbelowwillappear
HerearetheStepsweusedtoinsertandformat thecurrentdateandthecorrespondingcode: Selectrightadjacentcell InsertcurrentdateusingToday() formulafrom presetformulasinDate & Timecategory,For mularibbon Centertextincell ChangebackgroundcolortoYellow ChangefonttoArielRounded MT Bold ChangecoloroffonttoLight Blue EndMacro
Tes ng
Totestyourmacro,usethekeyboardshortcutyouspecied,inthiscase:Ctrl+Shi +G.Ifthemacrofailstorun,reexamineyourmacroinordertondtheerrorin thecode.
10
AbsolutevsRela veRecording
YoucaneitherrecordamacroinAbsolutemode,meaningonlythecellsyous pulatewillbe includedinthemacro,oryoucanrecordyourmacroinRela vemode,whichmeansthat whereverthestar ngcellhappenstobeiswherethemacrowillbegin. Absoluteisthedefault.ToswitchfromAbsolutetoRela ve,clickontheUse Absoluteicon intheCodesec onoftheDeveloper ribbon.ClickonitagaintoreturntoAbsolute mode. UsetheRela vemodewhenyouwantyourmacrotostartfromanywhereinyourworkbook; usetheAbsolutemodewhenyouwantyourmacroonlytostartfromapar cularcellevery meyourunit.
AssigningaMacrotoaBu on
Youcanini ateamacrousingabu onandothertypesofgraphics thataremainlydesignedasformcontrols.Toassignamacrotoa bu on: FromtheInsertbu on,underFormControls,selectthebu on Drawthebu onwhereyouwantitsituated TheAssignMacrodialogueboxappears Selectthemacroyouwantthebu ontoini ate ClickOK Revisethenameonthetopofthebu onandmodifyfont proper esasnecessary Deselectandtest
YoucanalsorecordanewmacrofromtheAssignMacrobu on dialoguebox.
11
SavingWorkbooksthatContainMacros
Workbooksthatcontainoneormoremacrosneedtobe savedasXLSMlesratherthanthedefaultXLSX.Ifyousave theleintheusualformat,themacrowillnotbesaved. Whenrstsavingalethatcontainsamacro,Excelwillpro videamessageadvisingyoutosavetheleasanXLSM. ClickontheSave as type listandselectExcel MacroEnabled Template,thenpressOK.
StoringMacrosinyourPersonalMacroWorkbook
Whenyouwanttouseamacroinmorethanoneworkbook,you canstoreitinyourPersonalMacroWorkbook. WhenyoupresstheRecord Macrobu onandtheRecord Macro dialogueboxappears,underStore Macro In,selectPersonal Mac ro Workbook.
Dele ngMacros
Todeleteamacro,
opentheMacrodialogbox(Developer tab > Macros), selectthemacroyouwanttodelete,thenpresstheDelete bu on (secondfrombo ominbu onlist) Inresponsetotheques on,answerYes
12
RecordingMacroExercises
Onthefollowingpagesareaseriesofexercisesdesignedtoprovideprac ceintheprinciplesandmeth odsofrecordingmacros.ThesemacrosshouldbeperformedusingtheExcelmacroworksheetswhich maybefoundintheExcel401directory. Eachexerciseprovidesstepbystepdirec onsalongwithanillustra onofthecompleteddialogbox, thecodewhichcomprisesthemacro,andanimageoftheresultsofthemacro,thewayinwhichthe nishedproductshouldlook. Ifthemacrodoesntrunorlookliketheillustra on,comparethecodeofyourmacro,withthatonthe pageand/orgotoPage23andfollowthestepsfordebuggingmacrocode.
13
Example1
InsertandFormatUCSDNameText
SelecttheRecord Macrosbu onintheDeveloper Tab. FillintheRecord Macro boxaspertheexampletotheright andpressOK SelectRange=A1E1 Select=Merge & Center SelectTypeface=Ariel SelectFontSize=16 pt SelectFontColor=White SelectBackgroundColor=Blue InsertText=University of California ~ San Diego ClickontheStop Macro bu onintheDeveloper Tab PressCtrl > Shi andtheShortcut Key totestyourmacro Ifyourmacrodoesntrunproperly,seePage22
14
Example2
InsertandFormatCurrent
SelecttheRecord Macrosbu onintheDeveloper Tab. FillintheRecord Macro boxaspertheexampleto therightandpressOK SelectCurrentDateFormula=TODAY() SelectCell=Centertext SelectFont=TektonProExt SelectFontSize=11pt SelectBackgroundcolor=Burgandy SelectFontColor=White SelectFont=Bold Selectborder=Medium Movecursor=2cells ClickontheStop Macro bu onintheDeveloper Tab PressCtrl > Shi andtheShortcut Key totestyourmacro Ifyourmacrodoesntrunproperly,seePage22
15
Example3
ChangeNumbertoDate
SelecttheRecord Macrosbu onintheDeveloper Tab. FillintheRecord Macro boxaspertheexampletotherightand pressOK Selectcellinwhichnumberislocated RightclickandselectFormat SelectDateFormat Formattextandbackground ClickontheStop Macro bu onintheDeveloper Tab PressCntrl > Shi andtheShortcut Key totestyourmacro Ifyourmacrodoesntrunproperly,seePage22
16
Example4
EliminateDecimalPlaces
SelecttheRecordMacrosbu onintheDeveloper Tab. FillintheRecord Macro boxaspertheexampletotheright andpressOK SelectNumberwithdecimal Rightclickonnumber SelectFormat SelectNumber Setnumberofdecimalplacesto0 PressOK Centerandboldnumber ClickontheStopMacrobu onintheDeveloperTab PressCntrl>Shi andtheShortcutKeytotestyourmacro Ifyourmacrodoesntrunproperly,seePage22
17
Example5
ChangeDecimaltoaPercentage
SelecttheRecord Macrosbu onintheDeveloper Tab. FillintheRecord Macro boxaspertheexampletotheright andpressOK Selectdecimal Rightclickondecimal SelectFormat Selectpercentage PressOK Center,colorandboldpercentage ClickontheStopMacrobu onintheDeveloperTab PressCntrl>Shi andtheShortcutKeytotestyourmacro Ifyourmacrodoesntrunproperly,seePage22
18
Example6
Selec ngandColoringLines
SelecttheRecord Macrosbu onintheDeveloperTab. FillintheRecordMacroboxaspertheexampletotherightand pressOK SelectFindandReplace SelectGoToSpecial SelectBlanks PressOK SelectFillColorGreen SelectColumnD SelectGoToSpecial SelectFormulas SelectOK SelectFillColorGreen SelectColumnF SelectCondi onalForma ngfromHomeTab SelectManageRules SelectNewRule SelectOnlyCellsThatContain SelectSpecicText SelectContaining TypeTotal SelectFormat SelectFill SelectGreen PressOK PressOK ClickontheStopMacrobu onintheDeveloperTab PressCntrl>Shi andtheShortcutKeytotestyourmacro Ifyourmacrodoesntrunproperly,seePage22
19
ReadingYourVBACode
ThebasicstructureofaVBAcodeis:
Object.Method
or Object.MethodParameter
VBACommandsYouWillSee
BelowaresomebasicVBAcommands.Take metoreviewthesecommandssothatyoumaygetabe erunderstandingofVBAcode.Asyou reviewthesecommands,remembertokeepinmindtheObject.MethodorObject.MethodParameterstructureofVBAcoding.Ifyouwanta be erunderstandingofwhateachmethodorparameterdoes,youcanclickfunc onkeyF1(explainedindetailonpage20). Howitswri enincode:
Whatitdoes:
20
UnderstandingVBACodethroughPrac ce
PressingF1onyourkeyboardopenstheExcelHelpscreen(picturedintheimagetothe right).InVBA,thishelpscreenwilldetailalltheinforma onyouwillneedtobe erun derstandyourcode.ExcelsHelpscreenwilltellyouwhattype ofcodeitis(i.e.method, func on,parameter,orproperty),anddisplaythehelpinforma onaccordingly. Thehelpwindowwillprovidethecodessyntax,walkyouthroughallofitsavailable arguments,andgiveyouseveralsamplecodesatthebo omofthewindow,underthe Exampleheading.
HowtoAccessExcelsHelpWindow:
OpentheVBAEditor
ToopentheVBAEditor,gototheDeveloperTab>Macro
Bu on>SelectthenameofyourMacro>Edit
Prac ceUsingF1withTheseCodes:
JusttypethesecodesintotheVBAEditor,placeyourcursorinsidethemethod,func on,parameter,orpropertycommands,andhitF1to analyzetheirdataintheExcelHelpwindow. Workbooks.OpenText Range(B4).End Basic **The help screen does not display Fori=2To10 ForEachcellinRange(A1).CurrentRegion.Resize(,1) Loops any informa on for VBA objects. Nexti Nextcell
Ifcell.Value=TotalThen cell.Resize(1,8).Font.Bold=True EndIf IfAc veCell.Value=FruitThen Ac veCell.Resize(1,3).Font.ColorIndex=3 ElseIfAc veCell.Value=VegetableThen Ac veCell.Resize(1,3).Font.ColorIndex=50 EndIf 21
IF
R1C1ReferenceStyleandWhatitMeansinCode
Whenyoubeginworkingwithmacros,youwillbeginno cingcodethatusesR1C1referencestyles.R1C1 isthestandardreferencingcodeusedinExcelmacrosbecauseitiswhatExcelwasini allydevelopedwith beforeit R1C1allowsforrela vereferencethereforemorebenecialtouseinmacrocodevsa1refstyle
22
FindOutWhatsGoingOninYourCodeUsingthe DEBUGGINGMODEtoStepThroughEachLine
Youcanac vatethedebugmodeby: 1.GoingtotheDEBUGmenuintheVBAEditorWindowandclickingStepIntoor 2.Hi ngtheF8func onkeyonyourkeyboard
Onceyoustepintoyourcode,youwillseethelinethatwill be executed, highlightedinyellow(asshown below);whenyouhityourF8hotkey,orgotoDebugandStepIntoagain,youwillseethislineofcode execute,andtheyellowhighlightwillmovetoyournextlineofcode. Whenyoustepthroughyourcode,youwillquicklyrealizethatalotofthecodeyouhaverecordedusing yourMacroRecorderisscrapcodethatdoesnothing,andcontributesnothingtoyourmacrosendresult. Whenyoundthesetypesofcodes,youcandeletethembyhighligh ngthelineandhi ngthedelete orbackspacebu ononyourkeyboard. Onceyoudeleteyourcode,youwillseeapopupsuchastheimage totheright.ClickOK.OnceyouclickOK,youwillneedtorestart yourdebuggingprocessagainbyhi ngF8orbygoingtoDebug> StepInto. Tip:IfyouhaveyourExcelwindowopenonthele halfofyourmonitor,andyourVBAEditorwindow openontherighthalfofyourmonitor,youcanviewwhateachlineofcodeisdoing,andndoutalso whichlinesofcodedonothing.
23
Crea ngandReadingCommentsinVBACode
Whencrea ngcode,itiso enagoodideatoincludecommentsnextto,above, orbelowthecodeyouhavejustcreated.Makingthiscommonprac cewill: 1. Helpyoureviewyourcodeatalaterdateandunderstandwhatishappening sothatyoumaytweakitifneeded 2. Helpthecolleaguesyousendyourmacrotounderstandwhatyourmacrois doing,andallowthemtolocateaspeciccodelinetochange,ifdesired Commentsarecreatedbyrsttypingintheapostrophekey.Forexample:
ThisisacommentinVBACode ThisisnotacommentinVBACode
24
Prac cingwithVBATotalValuesGreenSubProcedure
Beforeyoucanmakechangestoyourcode,youneedtoopentheVBAEditorWindow.Thestepstoopenthe VBAEditorWindowaredescribedonpage7.
SuggestedChange 1 2 Change the ColorIndex to something of your choosing Change the column number in the IF command to 4 and the test value from 0 to 100 Change the values of the Resize command to 2 (row) and 8 (column) ChangeinCode Cells(i,1).Resize(1,6).Interior.ColorIndex=32 IfCells(i,4).Value=100Then
Original Code:
Cells(i,1).Resize(2,8).Interior.ColorIndex=4
Add or delete rows of information to get a clearer understanding of the FinalRow command
The56ColorCodesofVBA
25
Original Code:
2 3
SubForma ngMacro() Range("A1").Select Selec on.End(xlDown).Select Range("A14").Select Selec on.FormulaR1C1="'Total" Range("E14").Select Selec on.FormulaR1C1="=SUM(R[12]C:R[1]C)" Selec on.AutoFillDes na on:=Range("E14:G14"),_ Type:=xlFillDefault Rows("1:1").Font.Bold=True Rows("14:14").Font.Bold=True Cells.Select Selec on.Columns.AutoFit Fori=2To10 IfCells(i,6).Value>0Then Cells(i,8).Value="ServiceRevenue" Cells(i,1).Resize(1,8).Interior.ColorIndex=4 EndIf Nexti
EndSub
26
VBAFunc onProcedures
VBAFunc onProcedures(VBAFunc ons) AFunc onprocedureisaseriesofVisualBasicstatementsenclosedbythe wordsFunc onandEndFunc on(seebelow). DierencebetweenSubandFunc onProcedures: Func oncanonlyreturnasinglevalue(numericalortextstring) Func onstartswiththewordFunc oninsteadofSub Func onprocedurescanonlybecreatedmanually Func onscanbeexecutedby TheInsertFunc oncommand AnotherVBAprocedureor Beingincludedinaworksheetformula
Func onproceduresdonotappearinmacrolist,butmay befoundintheInsertFunc onlistunderUserDened Macros
Intheexampleabove,aVBAFunc onProcedurecalledNumSignhasbeencodedandwillinsertthe wordzerowhennum=0,posi vewhennumisaposi venumber,andthewordnega vewhen num=anega venumberisentered.ThemacroisexecutedwhentheInsertFunc oncommandin theFormularibbonisinvokedandanumberisentered,asabove. 27
VBAFunc onProcedures
AdvantagesofFunc onProcedures Youcangreatlysimplifyyourformulasbymakingthemshorter;shorterformulasaremore readableandeasiertoworkwith Youcanwritefunc onstoperformopera onsthatwouldotherwisebeimpossible. HowtowriteaFunc onalProcedure(UseNumSignasexample) 1. Ac vatetheVBEditor(Developer>VisualBasic) 2. SelecttheModuleorSheet#intheProjectwindow. 3. ChooseInsertModuletoinsertaVBAmodule.Oryoucan useanexis ngcodemodule.However,itmustbeastandard VBAmodule. 4. EnterthekeywordFunc onfollowedbythefunc onsname andalistofthearguments(ifany)inparentheses.Ifthefunc ondoesntuseanargument,theVBEditoraddsasetof emptyparentheses. 5. Insertanapostropheandthenadescrip onofthemacro 6. InserttheVBAcodethatperformstheworkandmake surethatthevariablecorrespondingtothefunc onsname hastheappropriatevaluewhenthefunc onends.Thisisthe valuethatthefunc onreturns.
28
29