Академический Документы
Профессиональный Документы
Культура Документы
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
2010S.Malpezzi
2010S.Malpezzi
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
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)
($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)
$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
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
Cashin=+
Cashout=
Consider replacing complicated formulae with a
Considerreplacingcomplicatedformulaewitha
macro.
2010S.Malpezzi
AFewCoolThingsMostSpreadsheet
UsersNeglect
l
Comments
NamedRanges
The Auditing Tool
TheAuditingTool
ScenarioManager
2010S.Malpezzi
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
2005,S.Malpezzi
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
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
NAMESsection.
2010S.Malpezzi
2010S.Malpezzi
2010S.Malpezzi
2005,S.Malpezzi
2010S.Malpezzi
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
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
2010S.Malpezzi
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
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
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
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
When NOT bl
Wh
blank,
k value
l iin thi
this cell
ll
overrides value in Col. I
2010S.Malpezzi
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
2010S.Malpezzi
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
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
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
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
2010S.Malpezzi
2010S.Malpezzi
2010S.Malpezzi
2010S.Malpezzi
2010S.Malpezzi
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
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
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
=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
2010S.Malpezzi
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
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
Whatworkbook?Whatsheet?Whatcell?
Whatvalue?
h
l ?
Example:
Method that assigns the value 3
to the object Sheet1!A1
Worksheets(Sheet1).Range(A1).Value=3
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")
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
Yes
Execute the
statements between
b i i andd
beginning
end of loop
No
2010S.Malpezzi
For Next
ForNext
Forx
For
x =1to10
1 to 10
Beep
Nextx
UseForNextwhenyouknowexactlyhowmanytimestorun
theloopwhenyoustart.
Ifyoudontknowthis,useaDoLoop.
f
d k
hi
2010S.Malpezzi
2010S.Malpezzi
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
IF Statement
(Is the condtion true?)
Yes
Execute the
statements between
IF and END IF
No
END IF
2010S.Malpezzi
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*.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
2010S.Malpezzi
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