You are on page 1of 22
Advanced Excel Skills 4.1_ INTRODUCTION _Exceisa software appicition ofalmost unlimited depth and complexity. Theres 0 ‘way to count the numberof features ies, bt they must ran into the thousands. i ‘ot tens of thousands. Fortunately, most business analysts donot nce to bocome experts inallaspocs of Excl, but they often find that they need to develop expertise {na fw specialized domains within Excel Which domains are relevant depends on th jb they perform aswell as on tel ove of intrest in Excel and spreadsheet ‘modeling generally "The previous chapter presented the Eucel features we elev the great morty ‘of business analyte should now. Even tere our coverage was not exhaustive. For ‘uample, every analjt should know th basis of cel formating, but oly few wl eed to learn andrea al th various ways to customize formats ina workbook. Tinthis chapter, we pursue soveral specialized topics ia more depth. These are {atures of Excel that intermediate and advanced spreadsheet modelers to make their work more efficient, 10 make their spreadsheets easier 1 use, of torake them ‘more powerful. We suggest that novice modelers skip this chapter unt they have ‘developed at least a basi fansiliarity withthe sls covered in Chapter 3. More vanced wsers can skim this chapter, focusing on topics of particular inteest or relevance to ther work “The chapter covers the following topics: + Keyboard shortcuts + Controls + Cell comments + Naming cells and ranges + Advanced formulas snd functions + Recording macros and using Visual Basic for Applications (VBA) 4.2_KEYBOARD SHORTCUTS. the Reytemal aleve ‘selecting commands oF tos with the mouse. In Word, fr example, sing ony the mouse to copy and paste portion of text requires highlighting te text selecng the Copy icon rom the Homo tab, clicking oa the new location fr the ext, and seleeting the Paste ion from the Home tab. Alternatively and posibly more quickly, we can replace the fist selection withthe keystroke combation Cnt + Cand te second ‘seoction with he keystroke combination Cat +V. These keystroke combinations ae ‘examples of keyboard sharteutsSinco Ctl + Cand Cell + Vcan be executed with (wo fingers ofthe lft hand, we can keep the right hand on the mouse and us both hands ‘alot simultancously (Most keyboardshorteutsare not case sense so upper and Tower cass give the same results) n 7H cuerens move excess Excl shores many keyboard shortcuts with other Windows aplication. For example, we can wie Ci + Cand Crt» Vin Excel to copy and paste the contents of {ndvial cells or ranges of ells jus ss we copy txt in Word. Other shortcuts for ‘aia actions include cute Otic Button New culo Ottce Button» Open cies Ofce Button Save cule (tice Button Print cu +X Home Clipboard Cut cut F Homie Eating Find & Select Find cul +H Home Editing Find & Select» Replace cul Home) Edtingb*Find & Selet>Go To “These familiar shortcuts are oly a small mpl ofthe shortcuts available in [Excel Mot ofthese asthe speci he abalodFI-F12, Ct, Alor Shift Here isa further sample Format cells cuted Display Help FL Insert new worksheet shit + FIL ‘Mave cursor to cell AL Ct + Home Display the Find and Replace dialog box shin + FS ‘Switch tothe next nonadjacent seleson to the left Cis + Left Arrow In Figure 4.1 we ist for handy reference some ofthe most useful of these keyboard shortcuts, (An exhaustive int savniabl Under Help:searchon “keyboard shorts” and select the topic Exeel shortcut and function keys.) We recom ‘mend scanning this st fr shoctts hat may have been forgotten or pew ones for ‘operations that have become routine. Whenever we regularly encounter a tedious ‘and slow opeatog, it makes sens to search fora Keyboard shorcut to sve time, 3_ CONTROLS Excl controle allow the use 19 change the contents or behavior of spreadsheet without interacting directly with individual calls. Costas such as boxes an buttons tre familinr because they sppeat frequently in commonly sed windows inthe Exel ‘seinterface, Amongthe Excel Options, forexample,the window forFormulzoptions ‘scr button select Workbook Calculation mex (oaly one ofthe three available choices is allowed) and a check box (on oF oto Enable erative Calculation. ‘Controls can be inserted ito spreadsheet to sist users in choosing para- meter ips and tose the anna in performing senstity analysis Te controls tvilable are dxplyed by selecting Developer ContolsbInsei, asin Figure 42. (tthe Developer tab doce not appear, choose Oifice Button Excel Options Poplar and check the bos Show Developer Tab:in the Ribbon.) Fach con can be ‘ented by holding the cursor shove it For example the fourth con inthe tp 08 (adr Form Conteos) he Spin Button icon. “To lace a contra on aspreadsheet requires sequence of tps. Fis, click on the desired contol con ftom the toolbar. Using the cursor, which now appears as ‘ns, deagand drop the control tothe desire location athe spreadsheet. Indoingso, {se the cursor lose the sizeof the contol as well et oct. With the contral Feooederts sscomos 75 Fee aa area — fuse ns ca ST co sic eae co eis reo oo Weisner ee rece Tes ore a ar soma 5 Ty Bat Yay Fag a eA Tr See tars ar ——_[ cng oy mnogo 7 [er oy FT ——————| me es SSS aR ST a a i sf pha SAB To 2 Sots oes aS a arg a ra ar tas | tora " es be saaisownat ee neler eaar a Sa aaa ee eee re erent or ria ‘Sec ane cu — sin TTR rr aes ee ee se ay — Sco learn a eee es eet bighlighted, right dick and choose Format Control (Grlick Developer Contols> Properties) and eit ‘he inputs in this window to make the contol work as ‘dested. In some cass, preparations will ivolve tentering input daa forth controlinaspecial ection ofthe spreadsheet "AS an illusion, we demonstrate how the List Box and Spin Button coatos workin aversion ‘ofthe Office Building model from Figure 3.1 (Other ‘oatrols work inasimlar fashion.) Figure 43 shows a terion ofthe Office Building spreadsheet to which wre bave adsed a como pana in cells A2BI3, The purpose ofthe control pane isto make it easy to select two parameters the bling fot nol C20 and the sale multiple ia eal C27, The blldng cost iscontroled by 2 Tist Hox aad the sale multiple by a Spin Button. ‘We input the List oft Imagine that we have three quotes from construe tion companies for the cort pet square foot forthe building: $78.50, $80.00, and ‘8575, Because the bllding wil be built by one of these three companies, we know ‘hat he cost wll be one ofthese three numbers. Therefore, we do not want any numbers other than these tes entered int cell C20, s0 we pace a List Box onthe ‘Spueadthoet that offers these three numbers as options. in preparation forthe construction ofthe List Box, enter the thre allowable inpuparametersinto a spar location nthe spreadsheet such as FS, Next choose Developer Contolsb inset and click on the List Box icon under Form Contos (tthe one under ActiveX Controls). Onthe spreadshoct, cle el B4 to place the Control there. With the List Box highlighted, right lick and choose Format Control, fen selec the Control fb in the Format Control window, and enter FAS forthe {nput range and Péfor the Cela tne Thee choices ensure that the options shown {nthe boxcome from PSPS, nd the esl (2,3) appears in 6. Final, enter the formula ~INDEXCE3 25,26) in Ad and revise cell C20 to reference AA. ‘We can text the control by selecting anyone of the thee input inthe Hs box and verifying that the vale in cell C20 changes appropsately. We can set that the lltinate NPV (displayed for convenience in cell ATS) changes very Title asthe boiling costs change. "To intl the Spin Button forthe sales multiple, repeat the same procedure rom the Forms Coatol toolbar ts onthe Spi Button iconand place ton eel BD, sce cours 77 ‘With the Spin Button highlighted, ght click and choose Format Control, select the Control tab, and change Carzent Value to 12, Minimum value to 5, Waxdmin valueto 15/and Increnental change to. Thenchange the Cellink 9. These hoiesallow the sales multiple tobe any integer fom Sto 15, and the esl appears jin AO, Finally, revise cell C27 to reference AY. Byclickingonthe ypand down arows jn the Spin Button, we cance thatthe NPV for his investment ranges trom alow of bout 400,000 high af 16 milion over the allowable range for tesiles mile (with the cost quote at $80), indicating high degre of sensitivity EXCELTP |. enh Cont! bon he scen Deepest Coane ult |. Sct sie ont ade or Cot) 2. Cheon ede aan peo. 4 cack on Coorg riick on eo an et Fmt Cn.) 5. ac pope os nde 4.4 CELL COMMENTS ‘With few exceptions, the spreadsheets we have seen in actual use are poorly documented. Most practicing analysts have experienced the frustration of ying to understand complex formula ofa mode design sx months after they il it oF ‘wo years after someone ese bait But while everyone agrees that spreadshets should be documented, almast no one does it.The reason seems to be that most formsof documentation are too time-consuming. Cllenmments are one cay Wa C0 document the details behing cell or range of cel Inserting Comments To inser commentina particular cll highlight the cll and ‘choose Review» Comments New Commea. Tis opens comment window tthe ‘Sab ofthe cel, aked wo the eel by an arson The comment contains the users ame sa default. also places aed tangle inthe upper ight corner ofthe el which the indiatoe thatthe ell contains comment. “The location or size of a comment can be changed after iti highlighted (oy ‘licking omits border). Iti ood prctce to size the comment Box so thats does no ‘extend beyond the contents andto place itonthe spreadsheet where wl be visible but not coverup other important cells Figure 44shows a comment entered i cell C12 and sized to fit a blank portion ofthe spresdshet. Displaying Comments All ofthe comments in a workbook canbe displayed by choosing Review Comments» Show All Comments. This command toggles Back land forth between showing all ofthe comments and showing none of them, The ‘command Show/Hide Cormment applies ony tothe selected cel, Falting Comments Flt the comment by placing the cursor aywhare within the ‘comment box. All he usul Encl text eiting fetuses ean be used ise comment bores Deleting Comments To delete comment, click on Review Comments Delete, Another way to acces these commands iso solec el with comment and then Fightclick. The menu that appears will contain the commands that manage cell Copying Comments When cell containing a comment is copied, the contents and the comment ae bothcopiedto the new el Tocopy ja the eommentinacel, copy ae 998; the source cell, and then highlight the destination call. Nest, select Home Clipboard Paste Paste Speci, selecting Commencs and cheking OK. Printing Comments Comments on the spreadsheet will be printed just as they fappear onthe sreen I'he comments re extesive, we may want to print them in ‘one pace. Print all comments atthe end of the worksheet by choosing Page LLayouthPage Setup, Sheet tab and selecting Comments: At end of shest trom the pull-down ment. 5_NAMING CELLS AND RANGES ‘Individual cells and ranges of ells can be given names, and these names can be ted in formulas to make them more readable, Named ranges are also used ‘occasionally in other contents, such as Mentfying a database for Mtering or Specifying input data for a Pivot Table (sce Chapter 7). The use of range names is highly recoaumended in corporat settings for models that are used by many people, However, forthe solo modeler, i an open question whether the ‘ditional complesty of range names justifies their use. ‘Some examples ofthe use of range names will make their advantages cleat. ereis atypical forma froma inant Speadsheot wrtteninhe standard manner, with cll addreser pa0=p1a p14 +015, Here i the sme formula When written using ange names ‘Total Expenses = Cost of Goods Sold + Depreciation Interest Hreare two equivalent formulas for calling the atual quantity ofa product sold ‘depending on whether demand is more or es than the quantity available: bis 1012 >m20.010.013) Sales THDemand> Quantity.Available, Quanesty-AvatLable, Demand) Tibothof thes ates, the formulas wth ange names are ey to read and easy totes agains the underlying logic ofthe stuation, In oher words, when we se that {interest isincloded in the alculation of Tote] Expenses, we can mentally check ‘whether hisisthe oeret accounting treatment ofiterestendsItismore diffe to (2/F7),FO'FLO, G9'G10}, [Excel aso allows functions tobe wed within othe functions. Thi is referred fo a5 esting. So, for example, we could nesta SoM function within an 17 function: EF(SUMAL-A1O)> 0, F9"FL0, G'610), {Infact we can nest funetions as many times as we Ike (in most case), as ong asthe resulting calculations canbe performedby the intions themselves For example, we an nes TF funtion within Functions (although theresalimitof seven 3Psin one focus), as in TRD2>03, 67, 1F162>85.68,69)) (Or we can net several erent funtion -MINUAXA: DIO), SUMES: E10) MEN(ES:F10) We demonstrat other waysto nest function in the discussion ofadvanced functions. 464 Parameterization ‘Wediseussedin Chapter? the importance ineffective modeling of wel- parameterized functions, ad we provided a set of useful mathemati functions fortis purpose, ‘A wellparameterzed funcson sone that represeatsthe relationship between two of ‘more variables accurately with parametor tat havea natal meaning inte problem being modeled. Fr example, linear fonction is» natural wa to represents supply ora in which 9 fied charge i lncurse for every order placed and a variable sarge is incurred fr every unt ordered In this eae, the slop ofthe liner fonction Fepresents the variable charge ad the intercept the ed cage, When we vary ether tof these parameters dasing sensitivity analy, theresa ikely fo be meaning bocause the parameters themlves havea natural meaning ‘Mest relationships can be parameterized in alleaatve ways, Choosing the bes parameterization fr the problem athandis part of the art of modeling For extnple, 4 demand relationship between the prie ofa product and the quantity demanded ‘could be modeled using the constant elasticity function =a In this function, the parameter b measures the perentage change in quanti results from a percentage change in price ‘Analterauve isthe linear relaonship Q=c-aP ‘Theparameter dhere represents thountchangein quantity fora unitchangein pice, ‘Yet another damand funtion might be wed in situation in which theres ‘reference price inthe market, perhaps set by our major compettar’s pric. I we st ‘ur price above the reference price, we face one demand cure; if we pice below the reference price, we face another demand curve. One way to mode! his with an TF function, suchas tat Q= tour Prive > Reference, a~ OF, c~ AP) “These three functions represent thee equally usafUl ways 0 relate demand to price. Which one works best in given station depends on the shape of the ‘elationsip we wish to eeate and on the parameters we wish fo vy in sensitiity analysic ‘Another application of parametrization is to ereate Nexible functions for situations that are encountered often. A consulting company repeatedly found ist forecasting the market penetration ofnew products ove ine. After experimenting ith man tfren parameteizations ofthe relationship between marketshare ad ‘ime for new products, it sete on one that required fou inputs the nil share (Share) the final share (FShave), the year i which share fist stars to prow (Change_yeor), andthe number of years of growth (Years growth). The function takes the fllowing form: ‘Share ncrent year =F (Current year < Change.year, Share, TF (Curent year > Change-year + Years-growth,FShare, Shave + (Current.year ~ Change yea) ((FShare— share} Years growth) Before the Change_yer, share isconstant at [Shure After share has reached its limit (at Choige yours Yaar. growth) tisconstantat Phare Inbetween, the shares caleulated by adng to [Share the annuel growth ((FShare—Tohare) Years growth) fimes the mamiber af yearsinee Change sea (or Curent year—Change_ yer) Pie {USshowsaypial onput rom this function, Change any of the four input parameters and see how the function adjusts to show linear growth from IShure to FShare. ‘When we undertake sensitivity analysis wih tisfunction, we canes vary the four parameters that appear explicily: IShave,FShare, Change_year, and Years jgrowth. However, we cinnot perform sensitivity analysis on parameters that appea {mpiily, such asthe growth rae of sare. Ifthe growth rate is an important parameter, we might wa To creat a ciferen parameterization of ths eatonship In hich this parameter appears explicitly. Here i an example of such a function: Share incurrent year = 1F (Curent year < Change year, IShare, IF (Current year > Change year + Years-growth, share + Growth rate)” Years gromth Shar(1 + Growth rate)" (Curren yar — Change year) Neither ofthese altematives i simple function. If we were building only & single model involving goth in share, we Would probably not go tothe trouble of Creating and dehugzing sich 4 foxble function. But in situation where felationshipis needed routinely, itmay wel be worth the effort. 44.5. Advanced Functions AND and OR "The logical functions AxD and OR can be sed to detect the relaton- ‘hipbeweenvaluesin various celsn aspreadsheet asitchangs during analysis For ‘xample inthe Ofce Building model we ean determine whether te building cost is ove $100 andthe NPV is above $10}00,000 by using ‘awo(¢4>200,827>10000000), ‘The opel funetions take on only two values TRUE and FALSE, Thusin this spreadsheet, ‘axD(C4>200,827>10000000) - RUE ‘0R(¢4<100,827<20000000) «FALSE ‘These functions cam also be used o set Alags, which ar els that warn the user when spreadsheet yaluesare outside normal or aseptable ranges. (Flags are covered in more detail in Chapter 5) “Trt tablesare helpful for understanding how these logical functions operate Forexample. the AND function ony tr when bo conditions are tue ay shown in he able below, fae ise fe “The OR function, by cont istuei'on or the other or both conitions ar true, 8 shown inthe following table Tra Table for 8 he Fee “Logical functions are particulary usaflin combination with the 22 funtion ‘When te logical est in an Function depends on two conditions being rue suchas [D351 and Dis, we could wee two TP Functions {¥(D>10, TFDA<5, value sf true, value-if- false) value-if-fa1s0) Cr wo ca simply axing AND: TE(ANDYD3>10,045), value 4€ true, value-4f-fa1se) the logical condition were tu if one or the ther or both conditions were true, we would use the OR funetion: {IFOR(D3=210, Da<5), value Af.t2ve, value-sf-Ealee} [SUMIF and COUNTIE "Two funtion closely related to the 1B funston are Sunt and COUNT, Sint ads all the cells in Yang that sty 9 speciiod fondition, while COURTEY counts al the cells in a range that saisty 4 speciied ‘condition. (COUNT is related othe COUNT function, which counts all he ells a 8 ‘ange that contain numbers) For example, ithe range from DI to DS contains the following values 26 9 3 u a1 then star 02:05, <20") «99 and COUNTTRDI:D5," =22"")~3.(Notethat the condition in the SUMEP and COUNET® functions is enclosed in quotes) LOOKUP and HLOOKUP “The VLOOKUP (and WLOOKUP) funtions wre use for copturing relationships based on tables, Supliers, fr example, typically offer tiscounts for larger onder quantities. Here an example of such a price schedule Onder ot least Unte price 100 $99.0 20 3800 00 31.0) 0 3600 500 350 ‘We could captute this relationship using 1F functions, but it would require nesting five TP functions. A simplor way i to we VLOOKUP, which takes three inputs Lookup. salve, Table_aray and Col-index_numbe. The Lookup. value isthe value inthe frst column ofthe ble Inthiscae,tistheorder quantity fr which we want to ‘etermine the price. The Table arta isthe range in which the table islocate, Ihe twocolumnsof dla inthe above table were incellsOSDS the Tabeatray would be {C#DS. Finally, he Col index-pumber is the numberof the column in the table i ‘which te rest Hs In our example this column 2 So V00KuP(100,c4:08,2)= 39.50 and vipoxuri4as, c#:08, 2) =35.00 ‘Note that the vluesin theft columa ofthe table must he sorted, neither ascending for descending order, When the Lookup vale isnot found inthe fist colums, the ‘Yuoomtr function fds the range in which ties and chooses the next value in the {able Thus al vues above 400but below 500 sre weatedasthey were 500. (Other ‘Option er available; se the Funeion Arguments window or Help) "The .OOKUP function peorme the same function asthe VLOOKUP function except that its dasgned fr horizontal tables. INDEX, SMALL, and MATCH ‘The following xample shows how three pe ‘alized functions, INDEX, SMAI, and AT can be used in combination cary {sophisticated sequence of caleltion. The example arses in power generation, Gehote a Targe st of power plants most be Broupht ito production inorder from Towest ox to highest Figure 49 shows part ofthe data n'a workbook that cntsins {ont and eapacty dat or 50 pants, The plats ate numbered from 10 SOin column B Punt capacities andcosts are given in columps Cand D respectively. Our goal sto ‘cicrmine cumulative capacity when we employ only a certain runiber of plants in ‘rer of cost. Thus, we want tok, for example, how much capacity we haved! we Ue the 35 cheapest plants, “The fis step ito rank the costs from lowest to highest. We do his column F sing the SMALL function. The SMALL funcon calculates the Ath smallest Yalue in 2 range. So” SMALL(SDS6:80355,R6) retums the smallest cos Sunt (8086240855,27) the seoond lowest cox and so on, Next, we need to tnd the elatve postion of erenked costa the cot range, Fo example, ths lowes costs ‘0.5: which plant has hat cost, th 1h lowest, othe 25th Towest? We answer these ‘questions inenlumn G using the MATCH Tuncton, which gives the relative position “Ts camp de ey Gan See Deco Gog csxomnecoronmas oneness 87 eaoueetssuzss| ‘fan item ina sorted range. Thus MATCHCES, $DS6: $0855) ~15, whch aps chat the lowest cost of 05, which appear in cell Fs asociated with the ISth pant. The next stp isto determine the eapacty ofeach plant asit appears in cost oder. Inother words, We know thatthe lowest cost plant is number 15; what isis capacity? Wie calculate this value using the THDEX function. The TRDEX function gives the value at the intersection of a sow and colar index ins given rage. So INDEX($CS6=4CS55, NATCHCFS, $D45:80855,)) = 200. This function =o) in effec. the capacity range, ad the value ofthe 1st entry. Colum H thus gives the apactes of all the plats as they occur in cost order. Column I completes the ‘aculationby adding up cumulative capacity. (Note that column G wasiacuded only {or this explanation i could be omitted from the final spreadsheet.) Text and Date Functions Excel offers a varety of fusctions for working with text and dates, These functions are often needed when working with information from databases For example ithe fist names of eustomersare in column A andthe last names in column B, we ean form thei full names sing the COKCATENATE anction, which joins several text strings into one. Thus CONCATENATE(*"Sue'" Sith") = Suesnien (To insert a space between the to names, We ca Uso CONCATENATEC Su 9). Other useful text felons include EXACT, which compares two test stings, and LEFT, which returns «specified ‘numberof characters from the start ofa sting Date andtime functions gol convert dats fomone format to anther. Excel uses date code in which years are numbered fom 1000999. Ths we enter the Now function and format the ell asa dato, the result isto’ te which happens to bo 22606. However, if we format tas a number, the result i 38774 in Excel's date ‘code, Simiaey, DATEC2008, 2, 26) ~ 226105 a date and 38774 asa numbee ROUND, CEILING, FLOOR, and INT There ae several ways to change the precision with which numbers are mintsined in a spreadsheet. The CEILING function rounds up, andthe FLOGK function rounds down, oth to a given sign cance. The INT function ound down tothe nearest integer and the ROUND funtion rounds tothe specified numberof digits For example, ROUND(23.248,2)= 23-35 Note that these funetons actually change the number that is stored in the cel whereas formating a cell does not change the number atoll wed in clcuaions. So we cam format the maber 23.46 totvo digs andi wil appear as 28.35, but any fakeulations based on this call will We 23386, By ‘contrat, if we Use [ROUNDC23.346,2), then both the displey apd the actual number are 23.35, [RAND and RANDBETWEEN Random numbers ae often useful in modeling Sinple situations involving uncertainty far more complex situations we use Cyst Ball, which is dseueed in Chapters 15 aad 16). The RARDG) function returns 3 ‘uniformly distributed random number between O and {each time the spreadsheet is {aleulted To choos from ist of names randomly we can create random number for each stadem sing this function and then sort students from the lowest tothe highest value ofthe rendom number. RANDEETVEEN) returns a random number between tho limits set by the wer, For example, FANDBETWEEN(S,150) recurs {niformiy dssibuted random integers between 50 and 10. ‘Financial Functions Exce\ provides dozens of function fr nancial ealela- tions, some quite specialized. We have already discussed the NPV fonetion, which is ted frequently in evalsting investments. Some closely related functions are Pv, ‘which ealeultes the present ale of constant steam of payments, FV, which ‘aleulates the future value of » constant stream of payments; and THK, which ‘aleulates the internal ate of return ofa steam of payments, A couple of other fetions hat smpify complex calculations are PRICE, which calculates the pie of bond forgiven settlement date, edemption date, redemption value ratoand yield; fand SYD, which gives the sum-o- years digs depreciation fr given cost, salvage ‘ale, if, and prio. 4,]_ RECORDING MACROS AND USING VBA” ‘Macros are small computer programs that automate frequently performed sass ‘Macros are writen in the Vieul Basie for Application language andstoredin Vistal Basie modules, 3 a deep understanding of macros requires knowledge of VBA, Fortunatcly, Eco provider mechani fox texting macrossiply by reorting the ‘eps involved, so many simple eacros canbe ereated by users who have litle oc 90 programming knowledge, We illustrate here how to create a macro by recording Reysttokes how to ita macro using si concept from VBA so aso make itmore powerful, and how to um a macro info a wer-defned faction “Aay eto steps in Eace that an analyst repeats fequenlly ia good candidate fora macro, For example, some organizations requir that every spreadsheet has ‘ettaia header and footer (containing date, author, and related information) and that theirs several columns are formattedin a standard manner. To carryout these tasks Iandallymigh requice20-30separateactionsin Excel and take 10-1Sminstesevery time enew workbook must be created these actionscan be captaredina macro, the tse sequence can be exgeuted with one Key combination that takes seconds £9 recite, Some fume provide soch macros to employees as a way of ensuring ‘Sompllace wih corporate standards for good spreadsheet practice. 4.7.1 Recording a Macro Financia analysts often need to calculate cumulative returns for a eres of returns fata overtime. Consider, for example, the fllowing daly returns on the stock of| ‘Apple Computer for December 2008 What isthe cumulative retur fr each day, Calculated from December 1? a aly Rere alge on eet pay nomi . 2eoean? 20. osaio on orn coe roma 006 ‘mora 03 2ooeane oo 2108220 006 Since ther sno single function in Exc! fr ealeulating eumulaive retro, we need io proceed in steps. The fist step isto add 1 teach return. Then we multiply these growth factors together over the period in question andsubtaet fom theo to calculate the cumulative return. For example, the cumulative return over the fist ‘wo daysis(1+ 001°C. D038) —1= 0027. We have cad ou this eaeulation in the workbook shown in Figure 410, The input data appear in columns A and B Tncolumn C we Rave added Ito each return in column D we have multiplied the srowth fatorsin column C. We use the PRODUCT function todo this for example, he fumulative return from December Ito December 3 iscalealated in ell D25 wing the formula PRODUCTCSCS4:C25)-2, 90 ciuprens smvanowoexcx ses “There are several shortomings tothe procedure we have describ Oneisthat sve have to repeat these steps every times we want to calculate a cumulative return, ‘which could be dozens of times a day. Second, we have to elutter up ourspreadsheet ‘th intermediate cautions in column C. Instead, we ean use amacro Lo solve the ‘rst problem and swser-efined funtion to solve the second. "Theft step incteatinga macro isto document te steps that must be executed tocreate the deste outcome, Calculating cumulative returns fr every period given ‘column of returns requires four steps: ‘Step I: In he cell to the right ofthe frst return, write e formula that adds 1 to the fest retur (¢@, =B4+1). Step 2: Copy this formula down tothe last tne perio. Step 3 Inthe next column over writes formula that calculates the cumulative retlan (e, -PRODUCECSCS8:$C4)—1). ‘Step 4: Copy this formula down o the last time perio. “This proce wll work forthe data or example, but wo want our macro to-e more useful, we should aniipate that the columas tothe right ofthe returns dts may in some instances not be emply. this isthe ease, our iststep shouldbe to insert owo blak columns tothe right ofthe returns dat “Torecordamaerofor this process dspay the Returns datasheet. Then um on the Macro Recorder, which sa device that wil cord every ution performed on 8 ‘workbook antl the Recorder i turned off. The Recorder is trned on by selecting Developer Codeb Record Macro This opens the window shown in Figure 4.11 Give the macro a deserptive same (such as Compound. growth), store itn This ‘Workbook and wsignita shortet key that not normaly sed (sch sa") Click fon OK and noice thatthe Stop Revording button has ceplaced the Record Macro Duston in the Code group, Next proceed carefully through the steps outlined shose “Then click on the Slop Recordiag button. Check that the macro works correctly by fnylingtusng Ce» aafter deleting the contets ofeolumas Cand D, (lt might be ‘wise to make a copy ofthe worksheet beforehand) The results should betbe same as ‘those obtained earlier by manual calculation, 4.7.2 Editing a Macro “The macrowe have cteatediavery efficient forcaleulating cumulative eturnsas ong ss the date are located the rnge B4IB25. But we shoul expect to face stuationsin Iwhich we bavea diferent numberof returns andthe ae located somewbere else in the spreadsheet, Can we modify the existing macros that t works more generally? "Theft stp in this directions tocopen the Visual Basic Eaitor (VBE) and view the cod that was created when we recorded te Compound_growthmscro.Opea the ‘Viel asi Editor by chooting AICP (ee Figure. 12). Thelargepanecon the ght 's the Cade window. The code for the tmacro ean be viewed and edited here ‘Thepane on the let the Project Explorer ‘window, which ists all the open work Took and can be used to locate all the eros ia workbook “Three toolhars are commonly used in the VBE: Standard, Edit, and Debug ‘The Standard toolbar allows forthe usual Windows operations (Save, Help, and so on), bot it ako allows running and topping a program as wel as displaying ‘various aformationin the Editor (suchas is hepful for ‘working wth the code itself. thas useful icons for indenting tes, adding com: ‘mente, and 0 on Finally, the Debug tolbar makes it possible to ram the program in steps and to add a watch window to keep track of variables during code ‘The actual code forthe Compound_growth mactosshown in Figure 413-The frst ine of the macro starts with the word Sub flowed bythe name ofthe macro Compound_grovih(). The ast line ofthe macro is EndSub. The second line ofthe code begins wih single quote this is comment line andi not executed bythe ode. The remainder ofthe code is reproduced below, along with brit explanation ‘of what each line accomplishes. Columns(“C3D") Select select columns C and D Seleton.insort shift=xITORIght ‘insert two columns Ranget*C#") Select select Ct ‘ActveCell FormulaRICl = “=RC|-I}+1" enter formula = B4¥ Range(*C8") Select select Seletion.Copy| copy C4 Range(“CS:C25") Select select C5:C25 “Actvednect taste paste 19 C25 Range(“D4") Seloct selec DS Application CutCopyMode = Fae eit eopy mode ‘ActveCellFormlaRICL enter formula ‘= PRODUCT(RICSRC3)-1" PRODUCTISC¥SC4) —1 Range(“D4") Select select D4 ‘Selection AutoFill Destnati Range("DAD25"), ‘Type--aFillDefaal sutoll 0 DE:DIS Range("D&sD25") Select select DAD25 gune 439. conpe QUREAI Conpaind rae “The msjortakia making thismacromoregeneralisto replace thereferencesto specifi cel locations with gneri locations, o be specie by the wer. The edited ‘ode for this more powerful macro i given in Figure 4.14. Comments have been ‘eto this code to help explain the various changes. "The ist prt ofthe code wses Dim (Dimension) statements to create names or hrc ranges urerdta plasOneRag, and cumaRetRng. The fist range users, wil be set by he user, who must highligh the range of returss before running this micro ‘The plOneRRng wil contain the roturas pls oa; the cumRetRing wll contain the ‘cumulative retras “The second block of code iasers two blank columns to the ht of he returns data, The line ActiveSheet Cofumns(oerdata Colum + 1). Select highlights the ‘olomn tothe ght of the rstums data The line Selection knee shift=alToLet, ‘hich occurs twice, inserts a blank column. “Thenea block ofeode gives the names plsOneRng and cumRetRagtothe first ‘and second columns, respectively, t the right of the rturas data “The fourth block of codseretes the column of etures with faded. First the range plisOneRng is elected Then the formula RC[-]+1 is used to add one tothe ‘return one cel to the let Thea this formula is copied fo the bottom ofthe range. a a ue ‘The fit and final block of code calculates the cumulative returns. Fst the range cumRetRng iseelectd. Then the PRODUCT formula entered. Final, the Formulas copied tothe bottom ofthe range. “est this macro by fist highlighting the range B4825, then choosing Developesd> Code acres (or Alt+F8), highlighting CompoundEdited and sees ing Run The results should be ientcal to those obtained caries. Now delet these results, highlight just the range BIDB2N, and repeat the mocro, This should add Fetuensin columns Cand D starting in 1209 and running to 12/23. This demonstrates the increased generality ofthis version of the macto. “Mostot the lines of code that appeared inthe orignal macro have been changed in the edited version, Nonetheless, the overall ofthe logis enaiched nthe the edited version is usualy the case that recorded scope and een contain superious details, With some knowledge of VBA, itis posible to edit these templates and make thom both more general end more efficient. 4.7.3. Creating a User-Defined Function ‘The macros we have erated to tht point are powerful tools for analysts who Irequenly work with cumulative ceturs, Nevertheless, they sill have limitations, ‘One is simply that they requite the use of macros, which are not familiar tothe "majority of Exeel users Another limitation that we have to cuter the spreadsheet ‘with intermediate calculations It would be preferable f Excel ise had bun ‘function for calelating cumulative returns. Then We could simply enter this uncon ito any cell where twas needed, anywhere in a spreadsheet. Although Excel does ‘ot have such a function, we ean create one in VBA. “There are two fypes of VBA programs: Sub procedures and Function proce ‘dures: Both perform actions in Exeol. The macros We ave created ae examples of Sub procedures. A Function procedure difers fom a Sub procedure in that ican ‘eturna vale. The user-defined function we wish create will eturn the cumulative ‘turn or a specified range of otras dats Figure 41Sshows sucha program wien in VBA. ‘A sr-defined function begins with the words Puble Function, the function ‘ame (CunulatveRetum), and the type of inputs it accepts. Here our function Feuies one input a ange called "Retuns.""The next two lines crete a variable called“cell”(arange) and another called TotaRet, areal number. Then the variable “otalRet is set o the value 14 (14 is equivalent t0 10), “The core ofthis function sa For... Net loop. Tis oop takes cach clin the range Returns as 1, nd multiples hy the current value of TotaRet. When we ‘tact I rom the ial vale of FotlRet, we have the cumulative return over the Tange, which i ansiged tothe function valu, CumolativeRetura. ‘How can this fnction be wed ina spreadsheet? Fist, we can confirm thatthe function avilable na given spreadsheet by opening the Insert Function window ‘nd selecting User-defined fonction. Taea we ean use the function jst as we ase “ny oer Excel fnetion. Inthe worksheet coresponding to Figure 4.15, we have ‘entered the fonction CumltiveRetuen(SBS4SB4) in eel C4. Then we copy that function dwn the eolum, The results ae identical to those we have found using ‘Userdeined functions are preferable to macrosin many way. They are easier tousefor those unfair with macros. They can be wed Wo caeulate just the needed ‘results without adding anythingextrancoustothospreadsheet.Andthey canbe made ihly genera ‘We have not attempted to give a comprehensive overview of VBA in this section, but ater to convey a enseof what can be aecomplished using macros and \VBA- For those who spend shih pereentage of thet work fe using Excel many of| ‘whom creat elaborate spreadsheets and perform highly repetitive task, macros nd VBA represent the next frontier in power and efieny. 4.8_SUMMARY “ThischaptercovrsolcedEncel featrestintare edby_ Keybourdsbrteus can make interacting with Excel intemedinte and advanced modelers fo make thelr work easier and ulker, Cools an call comments make wh secadecs me tice or fo make he spvad- speadabetzesser ounderstand and easier ower mith, Ietetinore pometh tn sangse are seneraliy ied by sopstcted ode "Ihe chapter covered the olan topes lero make formulas csi fo read and Tess prone 6 + Keyboard shores ‘All Excel mel us know hw acest spl + Contos foes bt ome moses equ more aGraned we of 1 al coment foumsia Wesbow bow tonet incinerate powedal 1 Naming sl ad aap founulsinasingeesl and bow erat reuse formas 1 Adeaced fmm nd fonctions sing ete parametrization + Recording mucts and sas Visual Bas or Appleton SUGGESTED READINGS (G5 Soper cn dnl a0 co Eom tp ae aurea hast on ce. ‘Aamo. © 207, 8 Mas. Bnet CA: Ds. ‘Gar DF Acumen 28 oe “ak cmt 3 Bon NA Toma eae Ro § 2. Wg Mah VK, ae, Sas “CxO Ssurr € ioca Madn ag Eco. obo. Ten Jim Way nd Sms ‘wero W300 es Ee fan Aaa ant Basis “ein Dae Redmee, WA: Mates

You might also like