Вы находитесь на странице: 1из 109

Intermediate/AdvancedExcel,

Intermediate/Advanced
Excel
andVBA,
forRealEstateFinance
StephenMalpezzi
smalpezzi@bus.wisc.edu
http://www.bus.wisc.edu/realestate

2010S.Malpezzi

Tom Tomorrow
(A few years ago...)

2005,S.Malpezzi

Key Spreadsheets
KeySpreadsheets
SimpleExcelProforma.xls
Atoymodel,easytonavigate,demonstratessome
principlesofgooddesign.
Simple
SimpleProforma
Proforma withDetailedDevelopmentand
with Detailed Development and
Scenarios.xls
Multipleworksheetdesign,ScenarioManager
ApartmentProforma 1.xls
IncludesuseofIFandISBLANKfunctionsforflexibleinput
assu pt o s
assumptions.

2010S.Malpezzi

Objectives
Examine
Examineseveralproformas
several proformas inExcel.
in Excel.
Averysimplemodel
Othermodelsifwehavetime
Other models if we have time
Focusongooddesign,comments,auditing,named
ranges
IntrotoVBA
VBA Project: Proforma ModelforMultipleCases
Model for Multiple Cases
VBAProject:Proforma

2010S.Malpezzi

History of Spreadsheets
HistoryofSpreadsheets

Visicalc
Themotherofallspreadsheets.(Imaginelifewithoutone).Invented
bytwoBSchoolstudentstosavetimeonhomework.Thekillerapp
fortheAppleII.
L t 123
Lotus123
Macros!Functions!Graphs!95%MarketShare!
Quattro
Copyable!Decent(?)graphingandformatting,macrorecording.
C
bl !
(?)
hi
df
i
di
QuattroPro,Lotusv.3+,Supercalc,Excel
Mousesupport,multiplepages,linktootherapplications,more
f ti
functions,bettergraphics.
b tt
hi
Excel97,2000,2002,2003
Marketleader.Fullblownprogramminglanguage(VBA)builtin.Good
integration with other MS products
integrationwithotherMSproducts.

2010S.Malpezzi

History of Spreadsheets: Excel 2007


HistoryofSpreadsheets:Excel2007
Bettergraphics,newfonts
TheRibbon.
Th Ribb
Worksbetterinthelongrun;bettergroupings,more
flexible.Butapaintogetusedto.
EaseofaddingoftusedcommandstotheQuickAccess
Toolbarisnice.
Newfileformats!Extensions:
New file formats! Extensions:
xls isourfamiliarExcelspreadsheet
xlsx denotes2007format
xlsm denotesa2007spreadsheetcontainingmacros/VBA
code
Intheory,Excel2003candownloadafreereaderthatwill
In theory Excel 2003 can download a free reader that will
convertthenewformatstotheoldones.(Letmeknow
howthatworksout.)

2010S.Malpezzi

Excel for the Mac


ExcelfortheMac
ExcelfortheMac:apieceof#@&!!.Whatwerethey
thinking?
ItdoesntevenhaveVBA.
It
ItssalmostlikeMicrosoftdoesn
almost like Microsoft doesnttlikesupportingtheMac
like supporting the Mac
environment
IrunWindowsXPonmyMacsoIcanuseExcel2007.

2010S.Malpezzi

Three Stages of Spreadsheet Design


ThreeStagesofSpreadsheetDesign
Think.
Think.Mapoutyourspreadsheetbeforeyoubegin.
Map out your spreadsheet before you begin.
Implement. Codecarefullyandclearly.Dontbetoo
clever.
Debug. Trytobreak theprogram.Everyprogram
everwrittenhaserrors.Bethefirsttofindyours.
y

2010S.Malpezzi

Spreadsheet Style
SpreadsheetStyle
Style
Stylematters.
matters.
Designlogically,fromlefttoright,fromtopto
bottom.
Inproformas,
grouplikeinputstogether
group like inputs together
letcolumnsrepresentyearsorotherperiods
don
donttputnewthingsunderoldthings
put new things under old things

2010S.Malpezzi

Goodspreadsheetform:moveleftto
right,andtoptobottom.
i h
d
b

Inputs

Outputs
Model

Outputs

2010S.Malpezzi

From Geltner and Miller can we improve this?

Exhibit 14-2

Exhibit 14
14-2:
2: Example After
After-Tax
Tax Income & Cash Flow Proformas . . .
Property Purchase Price (Year 0): $1,000,000
Unlevered:
Levered:
Depreciable Cost Basis:
$800,000
Before-tax IRR:
6.04%
7.40%
Ordinary Income Tax Rate:
35.00%
After-tax IRR:
4.34%
6.44%
Capital Gains Tax Rate:
15.00%
Ratio AT/BT:
0.719
0.870
25.00% ____________________ ______________________________ ________________________________________________________________
Depreciation Recaptur___________

Operating:
Accrual Items:
NOI
- Depr.Exp.
- Int.Exp.
=Net Income (BT)
- IncTax
=Net
N t IIncome (AT)

Year:
Y
1
$60,000
$29,091
$41,250
($10,341)
($3,619)
($6 722)
($6,722)

2
$60,600
$29,091
$41,140
($9,631)
($3,371)
($6 260)
($6,260)

Adjusting Accrual to Reflect Cash Flow:


- Cap. Imprv. Expdtr.
$0
$0
+ Depr.Exp.
$29,091
$29,091
-DebtAmort
$2,000
$2,000
=EATCF
$20,369
$20,831
+ IncTax
=EBTCF

($3,619)
$
$16,750

($3,371)
$
$17,460

Oper. Reversion
O
R
i
Yr.10
Item:

$61,206
$29,091
$41,030
($8,915)
($3,120)
($5 795)
($5,795)

$61,818
$29,091
$40,920
($8,193)
($2,867)
($5 325)
($5,325)

$62,436
$29,091
$40,810
($7,465)
($2,613)
($4 852)
($4,852)

$63,061
$29,091
$40,700
($6,730)
($2,356)
($4 375)
($4,375)

$63,691
$29,091
$40,590
($5,990)
($2,096)
($3 893)
($3,893)

$64,328
$29,091
$40,480
($5,243)
($1,835)
($3 408)
($3,408)

$64,971
$29,091
$40,370
($4,490)
($1,571)
($2 918)
($2,918)

$65,621 Sale Price


$29,091 - Book Val
$40,260
($3,730) =Book Gain
($1,305)
- CGT
($2 424) =Gain
($2,424)
G i (AT)

$50,000
$29,091
$2,000
($28,704)

$0
$29,091
$2,000
$21,766

$0
$29,091
$2,000
$22,239

$0
$29,091
$2,000
$22,716

$0
$29,091
$2,000
$23,198

$50,000
$29,091
$2,000
($26,317)

$0
$29,091
$2,000
$24,173

($3,120)
$
($31,824)

($2,867)
$
$18,898

($2,613)
$
$19,626

($2,356)
$
$20,361

($2,096)
$
$21,101

($1,835)
$
($28,152)

($1,571)
$
$22,601

Rever.
R
Yr.10

T t l
Total
Yr.10

$1,104,622
$809,091
$295,531
$73,421
$222 111
$222,111

$219 686
$219,686

$0
$29,091 + Book Val
$2,000
-LoanBal
$24,667
=EATCF

$809,091
$730,000
$301,202

$325,868

($1,305)
$
$23,361

$
$73,421
$374,622

$397,983

+ CGT
=EBTCF

$291,801

_______________________________________ ____________________ ______________________________ ________________________________________________________________


CASH FLOW COMPONENTS FORMAT
Year:
Oper. Reversion
Rever.
Total
Operating:
1
2
3
4
5
6
7
8
9
Yr.10
Item
Yr.10
Yr.10
Accrual Items:
NOI
$60,000
$60,600
$61,206
$61,818
$62,436
$63,061
$63,691
$64,328
$64,971
$65,621 Sale Price $1,104,622
- Cap. Imprv. Expdtr.
$0
$0
$50,000
$0
$0
$0
$0
$50,000
$0
$0
=PBTCF
$60,000
$60,600
$11,206
$61,818
$62,436
$63,061
$63,691
$14,328
$64,971
$65,621
=PBTCF $1,104,622
$1,170,243
- Debt Svc
$43,250
$43,140
$43,030
$42,920
$42,810
$42,700
$42,590
$42,480
$42,370
$42,260
- LoanBal
$730,000
=EBTCF
$16,750
$17,460
($31,824)
$18,898
$19,626
$20,361
$21,101
($28,152)
$22,601
$23,361
=EBTCF
$374,622
$397,983
-taxNOI
$21,000
$21,210
$21,422
$21,636
$21,853
$22,071
$22,292
$22,515
$22,740
$22,967 taxMktGain
$693
$23,661
+ DTS
$10,182
$10,182
$10,182
$10,182
$10,182
$10,182
$10,182
$10,182
$10,182
$10,182
- AccDTS
($72,727)
($62,545)
+ ITS
$14,438
$14,399
$14,361
$14,322
$14,284
$14,245
$14,207
$14,168
$14,130
$14,091
$14,091
=EATCF
$20,369
$20,831
($28,704)
$21,766
$22,239
$22,716
$23,198
($26,317)
$24,173
$24,667
EATCF
$301,202
$325,868

11

Avoidthis.
(fromawellknowntextbook).

Usually include
period 0, the
development or
investment
period.

Sale is in year 5,
so this stuff should
be in column for
year 5

Generally,
Generally
sign cash in
as positive,
cash out as
negative. =SUM
positive and
negative numbers.
Avoid subtraction.

2010S.Malpezzi

Elements of Spreadsheet Style


ElementsofSpreadsheetStyle
Choose
Chooseasuitabledesignandholdtoit.
a suitable design and hold to it.
Uselotsofcommentsandlabels.Makeyour
spreadsheetsselfdocumenting.
p
g
Usenamedrangesforinputs.Makethenames
mnemonic.
Beverycarefulaboutsigns.

Cashin=+
Cashout=
Consider replacing complicated formulae with a
Considerreplacingcomplicatedformulaewitha
macro.
2010S.Malpezzi

More Elements of Spreadsheet Style


MoreElementsofSpreadsheetStyle
Never
Neverusemorethanonefont.
use more than one font.
Seriffonts(likeTimesRoman)aremoreformal,and
easiertoreadinlargeblocksoftext.(Theserifsaid
g
(
recognition).
Sans serif fonts ((like Arial)) are easier to read
from a distance (e.g. overhead presentations in
a large room).
Usecolor,italics,etc.sparingly.
Ifforsomereasonyouviolatetheserules,never
usemorethantwofonts.
2010S.Malpezzi

AFewCoolThingsMostSpreadsheet
UsersNeglect
l

Comments
NamedRanges
The Auditing Tool
TheAuditingTool
ScenarioManager

2010S.Malpezzi

User Friendly, Professional Models


UserFriendly,ProfessionalModels
Subtly highlightinputareas,andkeyoutputareas
highlight input areas, and key output areas
Considerprotectingcellscontainingformulas.
Password protectedcellsifyoudon
protected cells if you donttwantanyone
want anyone
messingwiththem.
Considerusingthevalidationtoolstolimitdataentry
Consider using the validation tools to limit data entry
rangestovalidvalues.
Uselotsofcomments.Makeyourspreadsheetself
y
p
documenting.

2010S.Malpezzi

Comments
Professionalspreadsheetsareclearandwelldocumented.
Sometimesyouwilldocumentwithtextcontainedincells.
Formajorprojects,awrittenusersguidemayberequired.
Another useful tool are comments within cells.
Anotherusefultoolarecommentswithincells.
2003:Selectthecell,thenINSERT,COMMENT
(Tocontroldefaultview redtriangles,fullcomment,or
nothing TOOLS
nothing
TOOLS,OPTIONS,VIEW
OPTIONS VIEW))
2007:Selectthecell,thenREVIEWtaboftheRibbon,NEW
COMMENTintheCommentsGroup.

2010S.Malpezzi

2010S.Malpezzi

The red triangles


markk cells
ll containing
i i
comments
Heres
H
a commentt
viewed in its entirety.

2005,S.Malpezzi

Be cool: use the auditing tools


Becool:usetheauditingtools
Trace
TracePrecedentsshowswhichcellscontaininputsto
Precedents shows which cells contain inputs to
theselectedcell.
TraceDependents
p
showswhatcellsarebasedonthe
datainthecurrentcell.
2003:TOOLSMenu
2007:FORMULAStaboftheRibbon

2010S.Malpezzi

Auditing Tools
AuditingTools
Tools,Auditing,TracePrecedents:findcellsthatare
,
g,
thebuildingblocksofthecurrentcell.
Tools,Auditing,TraceDependents:findcellsthat
d
dependonthecurrentcell.
d
h
ll
Unfortunately,auditingonlypointstocellswithin
a single worksheet
asingleworksheet.
Tools,FormulaAuditing:showformulaeon
p
( gg
spreadsheetinsteadofresults(togglebackandforth
withCtrl+

2010S.Malpezzi

2010S.Malpezzi

2005,S.Malpezzi

Tools, Auditing, Precedents yields this symbol


when precedent cells are on another worksheet

Click here
to go to cells
Click on dotted arrow,
Box pops up with cell refs.

2010S.Malpezzi
2005,S.Malpezzi

Named Ranges
NamedRanges
The
Themostcommonwaytorefertocellsistousethe
most common way to refer to cells is to use the
labelsofcolumnsandrowsonaworksheet.
Forexample,Sheet1!C27
p ,
Oryoucancreatedescriptivenamestorepresent
cells,rangesofcells,formulas,orconstantvalues.
g
Often,weusemnemonic names.
Example:ZLTV

2010S.Malpezzi

A few ways to create named ranges


Afewwaystocreatenamedranges
Select
Selectthecell,orcells,tobenamed.Thentypethe
the cell, or cells, to be named. Then type the
nameintheNAMEBOXthatappearsinExceljust
abovethetopleft.
Selectthecellstobenamed,aswellas adjacentcells
(usuallyabove,ortotheleft)ofthosecellsthat
containthetextofthenames.Thengotothedrop
downmenusandINSERT,NAME,CREATE,OK(2003).
2007:FORMULAStaboftheRibbon,DEFINED
b f h bb

NAMESsection.
2010S.Malpezzi

2010S.Malpezzi

2. Type name of cell in Name Box.


Be sure to hit <Enter>

1. Select cell to be named

Note: its convenient to also list the


names in adjacent cells,
cells for 2 reasons:
ease of use, and the better way to create
2005,S.Malpezzi
names (see next slide)

2010S.Malpezzi

1. Select cells to be named, AND


adjacent cells containing the names
2. Insert, Name, Create and Excel
guesses which
hi h part off range contains
i
names; the remainder contains ranges
to be named.

2005,S.Malpezzi

Advantages of named ranges


Advantagesofnamedranges
ItseasiertorememberZLTVthanSheet1!C27.
Unlikerowandcolumnlabels,namedrangesremain
unchangedasrowsandcolumnsareinsertedordeleted,or
otherwisemovedaround.
th
i
d
d
WhenweuseVBA(later),namedrangesarenearlyessential.
Note:anamecanrefertoasinglecell,arangeofcells.
Note: a name can refer to a single cell a range of cells
Rangescanevenbenoncontiguous,andextendovermore
thanoneworksheet.
Easiertoreadformulae.

2010S.Malpezzi

Garbage in, Garbage out.


Garbagein,Garbageout.
Choosing
Choosingtherightdecisionrule(s)isimportant.
the right decision rule(s) is important.
e.g.IRR,NPV,arebetterprimaryrulesthancash
oncashreturns,thoughthelatterisofsome
,
g
interest.
j g
Butdata,informationandjudgmentareevenmore
important.
Gooddataandaruleofthumbcanoutperform
lousydataandthebestcalculationtechnique.
Holistic:ifprimary(IRR,NPV)andsecondary(DCR,
cashoncash)disagree,askwhy?
2010S.Malpezzi

Everything you know is wrong!


Everythingyouknowiswrong!
Nomatterhowgoodyourestimatesandforecasts
g
y
offutureNOI,ofgoingoutcaprates,vacancyrates,
etc. weknowonethingforcertain:yourforecasts
will be wrong
willbewrong.
ForgettherateofreturnortheNPV.Thinkof
ranges, probabilities.
ranges,probabilities.
Manywaystotakethison,ScenarioManagerisa
usefulstart.
Togetstartedin2003:TOOLS,SCENARIOS,ADD
In2007:DATAtaboftheRibbon,DATATOOLS
section,WHATIFANALYSIS

2010S.Malpezzi

Scenario Manager
ScenarioManager
Ataminimum,Idefinethreescenarios:mylikelyscenario,

optimisticcase,andworstcase.
d

Likely:mybest estimatesandforecasts
Optimistic:agooddayattheoffice,butstillreasonable.
p
g
y
WorstCase:vacanciesandinterestratesrising,rents
falling,agooddaytoteachratherthaninvest.
Togetstarted:Tools,Scenario,Addthenfollowthrough
g
,
,
g
menus.Obviously,youllwanttocreateatleasttwo
scenarios.
Trap:IFCalculationissettoManual,ScenarioManager
p
,
g
doesntwork.IntheToolsmenu,setCalculationtoAutomatic.

2010S.Malpezzi

Anotherscenario(orsetofscenarios)you
shouldinclude.
h ld i l d
Whatassumptionsdriveyoutothethresholdofdefault?(EG
toadebtcoverageratiolessthanone?Wherethevalueof
thebuildingfallsbelowthevalueofthemortgage?)
Canundertaketrialanderror.
Can undertake trial and error.
CanuseSOLVERtofindassumptionsthatdriveyoutothe
threshold.
Note:Ifyouhave(say)twokeyinputs(rent,andstabilized
N t If
h
( )t k i
t ( t d t bili d
vacancyrate)andonlyonecriterionfordefault(DCR),there
aremanypossiblesolutions.
Simplesolution:youcaneitherfixrentsandchange
vacancy,orthereverse.
Moresophisticated:youcanspecifyarelationship
More sophisticated: you can specify a relationship
betweenrentsandvacancieswithinSolver.
2010S.Malpezzi

Named Ranges would


be good here!!!
Scenario Manager Output
ScenarioManagerOutput
Scenario Summary
Current Values:

High

Medium

Changing Cells:
ZGR_SF
15
16
15
ZVAC1
30%
30%
25%
ZVAC2
10%
10%
10%
ZVAC3
5%
5%
5%
Result Cells:
$I$28
10,027,927
10,696,455
10,027,927
$E$48
(988,669)
(655,769)
(951,807)
$E$49
0.77%
6.07%
1.21%
$F$50
0.49
0.53
0.58
Notes: Current Values column represents values of changing cells at
time Scenario Summary Report was created. Changing cells for each
scenario
i are hi
highlighted
hli ht d iin gray.
2010S.Malpezzi

Low

13
40%
20%
10%
7,900,791
(2,126,186)
-24.10%
0.28

Alternatives to Scenario Manager


AlternativestoScenarioManager
Data
DataTables
Tables
AlsoinWhatIfsection.Figureoutonyourown.

2010S.Malpezzi

Common functions you should know cold.


Commonfunctionsyoushouldknowcold.

SUM,AVERAGE,MEDIAN,PERCENTILE
SUM,
AVERAGE, MEDIAN, PERCENTILE
PV,NPV,IRR
PMT FV
PMT,FV
LN,EXP
IF
HowtouseSOLVER(notafunction,strictly,but
extremely useful)
extremelyuseful).

2010S.Malpezzi

Some tips on familiar functions (I)


Sometipsonfamiliarfunctions(I)

Gotdata?Great!Howtosummarizeit?Measuresofcentraltendency
arethefirststep!
h f
!
Everyoneisfamiliarwithaverage.Considerusingmediansandother
orderstatistics
AVERAGE( l 1 l 2 )
AVERAGE(value1,value2,...)
Mediansarebettermeasuresofcentraltendencyforvariablesthatare
veryskewed likerealestatevalues,incomes
MEDIAN(number1 number2 )
MEDIAN(number1,number2,...)
Amoreversatilefunctioncomputesmedians,quartiles,deciles,orany
percentilebasedstatistic:
PERCENTILE(array k)
PERCENTILE(array,k)
TocomputeamedianwithPERCENTILE,setk=.5

2010S.Malpezzi

Some tips on familiar functions (II)


Sometipsonfamiliarfunctions(II)
RememberthedifferencesbetweenPVandNPV:
PVisthepresentvalueofarepeatedpaymentofconstant
size;NPVisthepresentvalueofastreamofvarying
payments.
PV(rate,nper,pmt,fv,type)
NPV(rate,value1,value2,...)
RememberthatNPVstartsdiscountingimmediately.Ifyour
investmentismadetoday(undiscounted),compare:
=NPV(300,100,100,100)isincorrect
( 300, 00, 00, 00) s co ect
=300+NPV(100,100,100)iscorrect

2010S.Malpezzi

IF Function
IFFunction
Returns
Returnsonevalueifaconditionyouspecify
one value if a condition you specify
evaluatestoTRUEandanothervalueifitevaluatesto
FALSE.
UseIFtoconductconditionaltestsonvaluesand
formulas.
IF(logical_test,value_if_true,value_if_false)

2010S.Malpezzi

Someveryhandy,butunderappreciated,
f
functions
i
RAND(randomnumbergenerator)
(
g
)
MIRR(modifiedIRR,accountingforfinanceandreinvestment
interest)
XIRR,XNPV(IRRandNPVforirregularcashflows)
ISERROR(returnsanExcelerrorvalue;usewithIF,asin:

=IF(ISERROR(B12),WeAreDoomed,LifeisGood)
IF(ISERROR(B12) W A D
dLif i G d)

2010S.Malpezzi

Whatifyoucantfindsomeadvanced
f
functions?Addins.
i ? Add i
AdvancedfunctionsarepartoftheANALYSISTOOLPACKin
Excel.TheyareAddIns.
AddinsareactuallymacrosandfunctionswritteninVBA,
and compiled
and
compiled (youcanusethembutcan
(you can use them but canttreadilyaccess
readily access
thecode).
SomeAddinsareavailablecommercially(e.g.@RISKor
Crystal Ball or S Plus)
CrystalBallorSPlus).
OnceyouknowVBAyoucanwriteyourown
SomeAddInsareprovidedbyMicrosoftbuthavetobe
activated.

2010S.Malpezzi

Activating Addins.
Activating
Add ins.
In2003,TOOLS,ADDINS,thencheckofftheAddinsyou
desire.
2007,HOMEtab(topleftcorner),EXCELOPTIONS,ADDINS;
then go to to the MANAGE ADDINS
thengotototheMANAGEADD
INSbuttonatthebottom.
button at the bottom.
ThencheckofftheAddinsyouneed.
OfreadilyavailableMicrosoftAddinsIrecommendyoucheck
off ANALYSIS TOOLPACK ANALYSIS TOOLPACK VBA and
offANALYSISTOOLPACK,ANALYSISTOOLPACKVBA,and
SOLVER.

2010S.Malpezzi

Other Useful Functions: IS


OtherUsefulFunctions:
IS functions.
functions.

ISBLANK(cellref.):isacellblank?
ISBLANK(cell
ref.): is a cell blank?
ISERROR(cellref.):doesacellreturnanerror?
ISNUMBER(cell ref): does a cell contain a number?
ISNUMBER(cellref):doesacellcontainanumber?
ISTEXT(cellref):doesacellcontaintext?
Andfiveothervariationsonthetheme(seeonline
And five other variations on the theme (see online
help).

2010S.Malpezzi

Acommonprobleminproformas(andother
models)
d l)

Sometimeswewanttoenteravalueofavariablethatwillremain
constantforallyearsorperiods.
f
ll
d
EGinflationrates,mortgagerates,vacancyrates
Butsometimeswewanttooverridethedefaultvalue.
Whatifinflationtakesoff?Whatifwehaveavariableratemortgage?
Whatifvacancyratesarefallingasourpropertyleasesup,orrisingas
themarkettanks?
Two part solution:
Twopartsolution:
Setupadataentryformthatallowsyoutoenteraninitialrate,that
youcanchoosetooverrideforoneormoreperiods.
Whenusingthevariable,combineIFandISBLANKfunctionstouse
When using the variable combine IF and ISBLANK functions to use
enteredvalues,ordefaultifnovalueentered.

2010S.Malpezzi

Example:twowaystoenteraninflation
adjustment
dj
((1)Defaultinflationrateforagivenlineitem(ColumnIof
)
g
(
spreadsheetfragmentinnextslide)
(2)Inflationrateforagivenyearforagivenlineitem
If(2)isentered,thatentryoverridesthedefaultin(1)
Thisexample:inflationadjustmentsforvariousrentsor
expenses But this structure can be used for any variable that
expenses.Butthisstructurecanbeusedforanyvariablethat
mightbeassumedconstantforallperiods,oralternatively
mightvaryyearbyyear(e.g.vacancyrate,mortgagerate)

2010S.Malpezzi

Setup for inflation adjustment: input data


Setupforinflationadjustment:inputdata
When cell is blank,, will default
to value in Col. I of this row:

When NOT bl
Wh
blank,
k value
l iin thi
this cell
ll
overrides value in Col. I
2010S.Malpezzi

Now use data from previous slide in formulae


Nowusedatafrompreviousslideinformulae

2010S.Malpezzi

AnotherDesignDecision:whentostartanother
worksheet?
kh ?
Do
Dowestickwithaone
we stick with a onesheet
sheetmodel,orputinputson
model, or put inputs on
onepage,thecashflowmodelonasecondpage,
outputsonathird?Depends.
Example:whatifwedevelopabuilding,insteadof
purchasingacompletedbuilding?

2010S.Malpezzi

Charting Style
ChartingStyle
Keep
Keepitsimple:avoid3
it simple: avoid 3D
Dliketheplague
like the plague
Keepbackgroundsuncluttered,andwhite
Howwillthislookwhenit
How will this look when itssxeroxed?
xeroxed?
Usesimple,widelyavailablefonts(ArialorTimes
Roman)
Limituseofboxes
Simple orientation is usually best
Simpleorientationisusuallybest

2010S.Malpezzi

After Tax Cash Flows


4000000
3000000
2000000
1000000
0
0
-1000000
-2000000
-3000000

2010S.Malpezzi

After Tax Cash Flows


800,000
600,000
400,000
200,000
0
(200 000)
(200,000)
(400,000)
(600,000)
(800,000)
0

2010S.Malpezzi

RevenuesbyPropertyType,Firefly
R l C LLP
RealtyCo.LLP
Quarterlyy Revenuess, $Mil.

70
60

Office

50

Retail

40
30
20
10
0
1st Qtr

2010S.Malpezzi

2nd Qtr

3rd Qtr

4th Qtr

Charting Tips
ChartingTips
Be
Besureyouunderstandthedifferencebetweenline
sure you understand the difference between line
chartsandxycharts.
Makefontsbigenoughtoread.
g
g
Overheadsneedlargerfontsthanprintedreports!

2010S.Malpezzi

More Charting Tips


MoreChartingTips
Excel/PowerPoint'schartingenginecontainsmany
/
g g
y
charttypesthatshouldneverbeused
Radarcharts,conecharts,etc.
Excel/PowerPoint'schartingengineismissingmany
usefulcharttypes
Boxplots,sidebysidegraphs,etc.
B l t id b id
h t
Example:useasidebysidegraphifcomparisons
between individual pairs of values are most
betweenindividualpairsofvaluesaremost
important.

2010S.Malpezzi

Recommendation
Excel/PowerPointchartengineissimplynot
/
g
py
sufficientforseriousbusinessusers.
Ifyouarechartingdata,consideroneormoreofthe
f ll
followingseparateproducts,Exceladdins,ortheir
d
l dd
h
equivalents
SPlus(statisticspackagethathasgoodgraphics
S Plus (statistics package that has good graphics
addinforExcel)
SPSS
SigmaPlot(goodanalyticalcharts)

2010S.Malpezzi

Still More Charting Tips


StillMoreChartingTips
Excel/PowerPoint'schartingengineisparticularlypooron
analyticgraphingcapabilities
Example:therearenotruedatalabelsavailableforxy
plots in Excel
plotsinExcel
WhatMScallsadatalabelisnotatruedatalabel.Excelallows
youtoshowthevalueoftheyaxisvariableonthechart;
occasionallyuseful,butatruedatalabelpermitsuseofathird
variable.

Example:youwanttoplothousepricebyMSApopulation;
p
labelpointswiththreelettercodefornameofMSA.Cant
doeasilyinExcel,althoughyoucaneasilydoitinevery
otherspreadsheetonthemarket.
Solution:useQuattroPro,orLotus;oruseamacrooran
Solution: use Quattro Pro, or Lotus; or use a macro or an
addin.
2010S.Malpezzi

SomefeaturesofExcelyoushould
learn.
VBA:ThemacrolanguageforExcel
VBA: The macro language for Excel
Database(list)processing
Sorting
Filtering(querying)thedata
VLOOKUPfunction(turnsExcelsflatfiledatabasesinto
thepoormansrelationaldatabase)
Datatables(whatif)
Scenarios(whatif)
S
i ( h t if)
Pivottables(crosstabs)
Solver(optimization)
Solver (optimization)
Arrayprocessing(matrixalgebra)
2010S.Malpezzi

IntroductiontoVisualBasicfor
Applications(VBA)

2010S.Malpezzi

Objectives
Introduction
IntroductiontoVBA
to VBA
Thebasicidea
Theenvironment(theVBAeditor)
The environment (the VBA editor)
Themacrorecorder,vs.writingcode
Keyconcepts
Key concepts
Threekindsofsubroutines
Startanexample:aproformamodelformultiple
Start an example: a proforma model for multiple
cases

2010S.Malpezzi

VBA Readings
VBAReadings
S.
S.Malpezzi,
Malpezzi, Introduction
IntroductiontoMacrosandVisualBasic
to Macros and Visual Basic
inExcel
S.Malpezzi,DeconstructingaVisualBasicProgram
p
,
g
g
S.Malpezzi,TowardsaDeeperUnderstandingof
VBA
Microsoft,MakingDecisions

2010S.Malpezzi

Security considerations and VBA


SecurityconsiderationsandVBA
WithinExcelOptions,gototheTrustCenterandwithin
p
,g
MacroSettings,chooseDisableAllMacroswith
Notification.
InExcel2003,wesaveallfiles
I E l 2003
ll fil
withorwithoutmacros
ith
ith t
with
ith
extension.xls
InExcel2007,ifwehaveamacro,wecantsavewiththe
,
,
default.xlsxextension;wemustsaveitwithextension.xlsm
Finally,onceyouvegottheseright,youmayhavetosaveand
exit,reopenspreadsheet,andrespondtotheSecurity
i
dh
d
d
h S
i
WarningMacrosHaveBeenDisabledwithEnableThis
Content
2010S.Malpezzi

Macros: motivation
Macros:motivation
How
Howcanweautomateourwork?
can we automate our work?
Examples:
Wedesignaproformaforarepresentative
We design a proforma for a representative
investment.Whatifwehaveadatabasewith500
investments?
Wewanttowriteourownfunctionthatcalculates
IRRforawiderangeofpossiblevalues

2010S.Malpezzi

Two ways to create macros in Excel


TwowaystocreatemacrosinExcel
(1)
(1)Usethemacrorecorder
Use the macro recorder
ExcelrecordsVBAcodethatreflectswhatyoudo
untilyouturntherecorderoff.
y
(2)WritecodedirectlyintheVBAeditor
Usually, we do a bit of both
Usually,wedoabitofboth
Therecorderoftendoestheunexpected,orthe
redundant;runtherecorder,thenedittheresults.
Whenwritingcode,andyoudontknowwhattodo,try
therecordertogetsomeideas.

2010S.Malpezzi

The VBA Editor


TheVBAEditor
Between
BetweenExcel5.0andExcel97,theenvironmentfor
Excel 5.0 and Excel 97, the environment for
writingVBAcodechangedalot.
The97/2000/2002VBAeditorismuchmore
/
/
powerfulthanmodulesheetsin5.0.
Itisalsomorecomplicated.
p

2010S.Malpezzi

Getting to Macros and the VBA Editor


GettingtoMacrosandtheVBAEditor
In
In2007:DEVELOPERtaboftheRibbon,CODE
2007: DEVELOPER tab of the Ribbon, CODE
Section.
In2003:TOOLS,MACRO
,

2010S.Malpezzi

The Visual Basic editor works


alongside Excel, but it is not
Excel. It is a separate application.

This window contains


a macro (a function,
actually). You can
type and edit, like a
simple word processor.

This window explores your MS


environment. You can find your
open Excel
E l files,
fil your macros
(in modules), and other stuff.

2010S.Malpezzi

In the Project Explorer window, we see whats associated


with the project R631 Probs 1 and 2.xls, i.e. with the
Excel spreadsheet of the same name.
These modules contain my macros and functions. Click, and
they will appear in the larger area to the right.
These sheets are my Excel worksheets. Click and well go
to them, in Excel (another window).
Here I have some add-ins open, that work with Excel, like
PDF writer, and S-Plus (a statistical and graphics package).

2010S.Malpezzi

ATPVBAEN.XLA and FUNCRES.XLA are collection of


extra functions and analytic procedures that come
with Excel. If theyre not open, go to OPTIONS menu in Excel
if you will need them. (You will).

WhenyouopenVBAeditorforthefirsttime,
theremayormaynotbeamodulesheet.
h
b
d l h
If
Ifyouhaven
you haventtwrittenanycodeearlier(orrunthe
written any code earlier (or run the
recorder)youprobablywontfindamodulesheet.
GotothePROJECTEXPLORERwindowoftheVBA
Editor,selectyourVBAProject(thenameoftheExcel
workbookyouareusing),andthenfromtopmenu,
INSERTaMODULE.Oneshouldappear,likeablank
sheetofwhitepaper,inthelargewindowtothe
right.
right

2010S.Malpezzi

Our first macro written from scratch


Ourfirstmacrowrittenfromscratch

Sub Sillymacro( )
Beep
End Sub
Required

2010S.Malpezzi

Action to be
performed

Expressions
Definition:somethingthatreturnsavalue
g
inVBA.
Forexample,
3+2
zzz=5
a VBA function,
12
built
built in
in
x=sqr(4)
x<7
a logical expression
x=x+3
(returns true or false)

2010S.Malpezzi

Types of VBA procedures


TypesofVBAprocedures
Macro
asubroutinewithanemptyargumentlist
e.g.SubFred()
Subroutine
S b ti withnonemptyargumentlist
ith
t
t li t
canusuallyonlybecalledbyanothersubroutine,e.g.a
macro(cantberunfromthemacrodialoguebox,orthe
toolbar)
whenSubFredcallsSubEthel,Fredcanpassarguments
( a ues o so et g) to t e
(valuesofsomething)toEthel
Function
afunctioniscalledfromaspreadsheetcell,andafterit
runsthereisareturnvaluethatisplacedinthecell.
th
i t
l th t i l d i th
ll
functionsmusthaveargumentspassedtothem.
2010S.Malpezzi

A simple function
Asimplefunction

return value
is whatevers
in variable Zap
when function ends

Function Zap(a,b,c)
Zap = a + b + c
End Function

in functions, theres
a variable implied with
the same name as the
function

To invoke Zap, within a spreadsheet cell type the function,


followed by the arguments, for example:

=ZAP(1,2,3)
Function ZAP will return the value 6.
2010S.Malpezzi

Control Structure
ControlStructure
Withoutcontrolstructure,amacrorunsfrombeginningto
end.
Controlstructure
Whichstatementsexecute?When/howoftenarethey
Which statements execute? When/how often are they
executed?Aretheyrunatall?
Generalelementsofcontrolstructure
IF/THEN/ELSE
looping

FORNEXT
FOR NEXT
DOWHILE
DOUNTIL
DO UNTIL
GOTO(avoid)
2010S.Malpezzi

Exampleofcontrolstructure:

ForNext

variable

these are
always paired

counter (also
Sub Testloop ( )
a variable)
zzz = 5
For n = 1 to zzz
MsgBox The current number is & n
Next n
MsgBox Now were out of the loop
End Sub
concatenation
operator

2010S.Malpezzi

A little VBA style


AlittleVBAstyle
Use
Uselotsofcomments.
lots of comments.
Assumesomeoneelsewillwanttofigureoutwhat
y
youvedone.Makeyourprogramself
y
p g
documenting.
y
Indentyourcodetomakeiteasiertofollow.
Dontbeclever.Beclear.

2010S.Malpezzi

Our First Serious Exercise


OurFirstSeriousExercise
Modify
Modifyoursimpleproformamodeltohandlemany
our simple proforma model to handle many
cases(investments)
Key:insteadofonecolumnofinputs,letshavemany
y
p ,
y
rowsofinputs.Eachrowisaninvestment.
g
g
Runeachrowinturnthroughour(single)model.
Letshaveasmanycorrespondingrowsofoutput
(presentvalue,IRR,etc.)

2010S.Malpezzi

ThreeStagesofSpreadsheetDesign
(f
(fromabove)
b
)
Think.
Think.Mapoutourspreadsheet.
Map out our spreadsheet.
Implement. Codecarefullyandclearly.
Debug Trytobreak
Try to break theprogram.Everyprogram
the program Every program
Debug.
everwrittenhaserrors.

2010S.Malpezzi

Earlier,wesaid:Goodspreadsheetformis
movelefttoright,andtoptobottom.
l f
i h
d
b

Inputs

Outputs
Model

Outputs

2010S.Malpezzi

Multiplecases:moveeachcase(row),inturn,intothe
buffer;calculatethemodel;thenmovekeyoutputsto
;
;
y
p
correspondingoutputrow
Buffer
Model

Inputs

2010S.Malpezzi

Outputs

Rulesweremadetobebroken.
( h b k h
(Whybreakthemhere?)
h ?)

Buffer

Model
Inputs

2010S.Malpezzi

Outputs

How do we figure this stuff out?


Howdowefigurethisstuffout?

LearnsomeVBAprinciples,andsomecode.
Learn
some VBA principles, and some code.
Examineexamples.
Run the macro recorder
Runthemacrorecorder.
Usetheonlinehelp.
Browse books and web resources
Browsebooks,andwebresources.

2010S.Malpezzi

Principles:TowardsaDeeper
UnderstandingofVBA

2010S.Malpezzi

The Grammar of VBA


TheGrammarofVBA
Objects
j
((nouns))
e.g.Workbook,Range,Font,Name
Ifyouknowanobjectstypeorclass
y
j
yp
yyouknow
whatproperties applytoit.
Properties (adjectives)
e.g.Bold,Count,ColumnWidth,ActiveCell
Methods (verbs)
e.g.PasteSpecial,Add,ClearContents,Copy,Edit,
l dd l
d
Sort
2010S.Malpezzi

More VBA Grammar


MoreVBAGrammar
Statements
Statements(programmingconstructs)
(programming constructs)
EGForNext,DoWhile
(built in routines)
Functions (builtinroutines)
EGAbs,Rnd,Sgn,SolverLoad,Sqr
NotethereareExcelfunctionsandVBA
Note there are Excel functions and VBA
functions;theyareoftensimilarbutnot
identical.
Operators (arithmetic,logicalcomparisons)
EG&,+,
EG &, +, *,,,,/,
/, ^
EGAnd,Is,Not
2010S.Malpezzi

Whatworkbook?Whatsheet?Whatcell?
Whatvalue?
h
l ?
Example:
Method that assigns the value 3
to the object Sheet1!A1

Worksheets(Sheet1).Range(A1).Value=3

Method that returns


the object Sheet1

Method that returns


the object A1

Notice that objects can be hierarchal.


Because we havent specified the workbook, VBA will look
in the workbook we are currently in.
2010S.Malpezzi

Twowaystoreferto(say)aparticular
rangeinVBA
i VBA
Workbooks(Workbook 1.xls).Activate
Worksheets(Sheet 1).Activate
Range(Fred).Select
Three statements
Continuation _
Workbooks(Workbook1.xls). _
Worksheets(Sheet 1).Range(Fred).Select

A single statement
2010S.Malpezzi

Heresaninterestingconstruction!
g

Worksheets("prob 3").Activate
'copy a row of input into the buffer
Range("XCASES").Rows(nnn).Select
Selection.Copy
ActiveSheet.Paste destination:=Worksheets("prob 3").Range("BUFFER")

Hmm. How did I figure out the Rows method of referring


to a (you guessed it) row?
2010S.Malpezzi

VBA Grammar
VBAGrammar
Some
Somewordscanbemorethanonepartofspeech,
words can be more than one part of speech,
dependingoncontext.EGrangecanbeanobjector
amethod.
LikeGerman:methods(verbs)comeattheend.

2010S.Malpezzi

Program Control
ProgramControl

If/Then/Else
ForNext
Do Until
DoUntil
DoWhile
Select Case
SelectCase

2010S.Malpezzi

The Logic of Looping Control Structures


(For/Next, Do While, Do Until, etc.)
FOR, DO UNTIL,
DO WHILE, etc.
(Are the circumstances met?)

Yes
Execute the
statements between
b i i andd
beginning
end of loop

No

End of loop (NEXT,


END, etc.)

2010S.Malpezzi

Continue the rest of the program

For Next
ForNext
Forx
For
x =1to10
1 to 10
Beep
Nextx
UseForNextwhenyouknowexactlyhowmanytimestorun
theloopwhenyoustart.
Ifyoudontknowthis,useaDoLoop.
f
d k
hi

2010S.Malpezzi

Do While ... Loop


DoWhile...Loop
x=0
DoWhilex<10
Beep
x=x+1
Loop
UseDoWhile...Loopwhenyouwanttotestacondition
beforeyouruntheloopandthencontinuetoruntheloop
whiletheconditionistrue.

2010S.Malpezzi

Do Until ... Loop


DoUntil...Loop
x=0
DoUntilx>10
Beep
x=x+1
1
Loop
UseDoUntil...Loopwhenyouwanttotestaconditionatthe
p
y
beginningoftheloopandandthenruntheloopuntilthe
conditionistrue.
NB:Iftheconditionistruetobeginwith,thestatementsinthe
NB: If the condition is true to begin with the statements in the
looparenotexecuted!
SupposewechangedcodeabovetoDoUntilx<10
2010S.Malpezzi

If... Then... Else ...


If...Then...Else...

Singlelinesyntax:
Ifx<3Theny=0
Blocksyntax:
Ifx<3Then
y=0
z=x+1
EndIf
If,Then,Else:
Ifx<3Then
y
y=0
Else
y=1
End If
EndIf

2010S.Malpezzi

The Logic of IF/THEN Control Structures

IF Statement
(Is the condtion true?)

Yes
Execute the
statements between
IF and END IF

No

END IF

2010S.Malpezzi

Continue the rest of the program

Elseif, and Select Case


Elseif,andSelectCase

SupposeyouhavemorethantwoalternativestoevaluateinanIf...
Then...situation
h

e.g.ifyouhaveseveralincomeclasses,needtocalculatetaxes
differentlyforeachclass
Y
YoucannestIf...Then...Else...statements(doable,buthardtofollow.
t If Th
El
t t
t (d bl b t h d t f ll
YoucanuseIf...Then...Elseif
Ifinc<10000thentax=inc*.2
Elseifinc<20000thentax=inc*.3
l if i
20000 h
i * 3
Elseifinc<30000thentax=inc*.4
Elsetax=inc*.5
EndIf

2010S.Malpezzi

Select Case
SelectCase

SelectCaseissimilartoIf...Then...Elseif
SelectCaseinc
Case0to10000

tax inc * 2
tax=inc*.2
Case10001to20000

tax = inc *.3


tax=inc
3
Case20001to30000

tax=inc*.4
CaseElse
tax=inc*.5
End If
EndIf
2010S.Malpezzi

Functions
Macros(subroutines)canbecalledinseveralways,for
example:
Tools,Macro,thenselect
Installbuttonsinworksheetorontoolbar
Install buttons in worksheet or on toolbar
Macroscancallothermacros
Macrosdontpassargumentswhencalled(exceptwhena
macrocallsanothermacro)
Functions,incontrast,arealwayscalledfromwithinacell;
a d o e o o e a gu e ts a e usua y passed
andoneormoreargumentsareusuallypassed.
Functionsalwaysreturnavaluetothecellcontainingthem.
Example:=SUM(1,2,3)returnsthevalue6tothecell
containingtheformula.
t i i th f
l
2010S.Malpezzi

Functions
Microsoft
Microsoftprovidesalargesetofpre
provides a large set of prewritten
written
functions(SUM,IRR,NPV,AVERAGE,andsoon),but
wecanwriteourown.
Wellwriteonetoday:
Computeinternalrateofreturnforaseriesof
p
cashflows
UnlikeExcels,ourIRRfunctionwontquittillit
solves.
Itisntasefficient,andhasntbeenthoroughly
testedyet.
2010S.Malpezzi

How to turn off the monitor in VBA


HowtoturnoffthemonitorinVBA
When
WhenwerunamacroinVBA,thescreenjumpsasif
we run a macro in VBA, the screen jumps as if
werecarryingouttheprocedureusingkeyboardand
mouse,exceptveryfast.
Thiskillsefficiency,becausechangingthescreenso
muchtakeslotsofcomputingpower.
Toshutoff,putthefollowinginstructionatthe
beginningofyourmacro:
Application.ScreenUpdating=False

2010S.Malpezzi

Spaces sometimes matter in VBA


SpacessometimesmatterinVBA
Make
Makesurethere
sure theressaspacebeforeandafterthe
a space before and after the
concatenationoperator,&.OtherwiseVBAmay
interpretitasatypedeclarationcharacter.
TheVBAlinecontinuationsequenceisactuallytwo
characters:aspace,followedbytheunderscore_

2010S.Malpezzi

Howtorunamacrousingabuttonina
cellll
Getintotheworksheetyouwanttocontainthebutton.
y
Rightclickanytoolbar,andselectForms fromthemenu.
ClickonceontheButtontoolontheFormstoolbar.Then
movethecursortothecellyouwanttocontainthebutton.
Excelimmediatelypresentsyouwithalistofmacros,so
you can choose which one to assign to the new button
youcanchoosewhichonetoassigntothenewbutton.
Afteryouvecreatedit,youcanrightclickonthebutton
andchangethetext,font,etc.
Onceitsfinished,clickonthebuttontorunthemacro.

2010S.Malpezzi

Howtorunamacrousingabuttononthe
toolbar
lb
Tools
Customize
Commands
Macros
dragCustomMenuItemtotoolbar
rightclickitemtoassignmacro,giveitatitle,format
themenuitem.
Onceyouredone,clickonthetoolbarbuttontorun
d
l k
h
lb b
themacro.

2010S.Malpezzi

DefiningVariableTypeswithDIM
Statements
VariablesinVBA(andotherenvironments,includngExcel)can
bemanytypes:
Integers
Floatingpointnumbers(fordecimalsandfractions)
gp
(
)
Characters

Theycanalsobemanysizes
A
Asinglenumber,orscalar
single number or scalar
Anarray,ormatrix,ofagivensize(e.g.a10x1vector,ora5000x10
array)

VBA
VBAisusuallyprettygoodaboutfiguringoutvariabletypes,
is usually pretty good about figuring out variable types
andsizes,onthefly.

2010S.Malpezzi

DefiningVariableTypeswithDIM
Statements
VBAisusuallyprettygoodaboutfiguringoutvariabletypes,
andsizes,onthefly.
Butitcanbemoreefficient,andalsogoodprogramming
practice, to predefine variables before they are used.
practice,topredefinevariablesbeforetheyareused.
Examples:

DIMIasInteger
Dim X(3 4) As Integer
DimX(3,4)AsInteger
DimY(1To5,4To9,3To5)AsDouble
DimBirthDay(1To10)AsDate

2010S.Malpezzi

Going forward
Goingforward
Lifetime
Lifetimelearning:Setaside20
learning: Set aside 2030
30minutesevery
minutes every
weekortwotobrowseanExcelmanualortheonline
help,ortostudysomeoneelsesmodels.
Startwithtodaysmaterial.
p
pp
TakeRE631,ComputerApplications.(Ifnot,collect
materialsfromthewebsite).
Examineotherpeoplesmodels.Learnfromthem.
Dropthejunk.
Onlinehelp,websources,browsingyourfavorite
bookstore.
2010S.Malpezzi

Вам также может понравиться