Excel if Statements LOOKUPS

download Excel if Statements LOOKUPS

of 8

Embed Size (px)

Transcript of Excel if Statements LOOKUPS

  • 7/21/2019 Excel if Statements LOOKUPS

    1/8

    Excel IFStatements,LOOKUPS&INDEX/MATCH.Whentochoosewhichone?

    ThisarticlewillfocusontheappropriateuseofIFstatements,andalsoshowyouwhenit'sbettertomoveintomorerobustformulas

    likeLOOKUP,VLOOKUP,HLOOKUP&INDEX/MATCH.

    NOTES:thisarticleiswrittenforExcel2010anditsRibbonInterface. TheexamplesyouseewerecreatedinExcel2010,butsavedasExcel972003.

    WorkingexamplesarehostedonMicrosoft's[url=http://cid8cffdec0ce27e813.skydrive.live.com/redir.aspx?resid=8CFFDEC0CE27E813!195]SkyDrive

    service[/url]foryoutodownload.

    IFstatements

    are

    one

    of

    the

    core

    formula

    models

    you

    can

    use

    in

    Excel,

    and

    they

    can

    be

    very

    powerful

    with

    regards

    to

    their

    logic.

    Verysimplytheyfollowthismethodology:IF(somethingisTrue,thendosomething,otherwisedosomethingelse).

    =IF(A1="Yes",1,2),whichsimplysaysifA1=Yes,thenreturna1,otherwisereturna2.

    YoucanalsocombineIFstatementstoevaluatemultiplecriteriabynestingthem,however,manypeopletrytogetIFstatementsto

    dotoomuch.PreviousversionsofExcelallowedupto7levelsofnestedIFstatements,whichmeansthatyoucouldevaluateupto7

    differentcriteria. Excel2007+allows64levelsofnestedIFstatements,butjustbecauseyoucandosomethingdoesn'tmeanyou

    should!

    OneofthemostcommonusesofIFstatementsistoreturndatathatmatchesspecificcriteria,orfallswithinarangeofvalues.Here

    isarelativelycommonexampleofanestedIFstatementtoreturnlettergradesbasedontestscores:

    =IF(A1>=90,"A",IF(A1>=80,"B",IF(A1>=70,"C",IF(A1>=60,"D",IF(A125000,A1*2%,IF(A1>15000,A1*1.5%,IF(A1>5000,A1*1%,0)))

    Notethatinbothformulas,thecriterianeedtobeorderedsequentiallyinorderfortheformulatocalculatecorrectly. Sointhefirst

    exampleA1>=90getsevaluatedfirst,andifthatconditionistrue,thentheformulaperformsthecalculationassociatedwiththat

    condition. Iftheconditionisnttrue,thenitmovesontothesecond,andsoon. Butifyougetyourconditionsoutoforder,thenone

    conditioncaninvalidatethenextandrenderyourformula(s)useless. OneoftheinherentweaknesseswithIFstatementsisthat

    theyneedtobepreciseandordered.

    Whilebothoftheseformulasworkfine,they'reunwieldyandshouldbeavoidedifatallpossible. Why? Primarilybecausethedata

    intheformulasisstatic,soiftheconditionsdrivingtheformulaeverneedtobechanged,theformulaneedstobemanuallyadjusted

    asaresult. Granted,thegradesexampleisn'ttoobad,becauseit'snotlikelythatinformationwillchangetoooften,butjustimagine

    howmuchworkyou'dhavetodoifyouhavealotofformulaslikethecommissionexample,andyouhavetochangethecriteria.

    Ideally,you'llgetintothehabitofonlyusingIFstatementsforTextcomparisonsliketheearlierexample. Yes/No/Maybeor

    Male/Femaleevaluationsareverycommon,andthenicethingaboutthemisthatcriteriaarentlikelytochangeveryoften. Ifyou

    findyourselfwithsituationslikethisthenbyallmeansuseIFstatements,otherwiseit'stimetomoveuptomorerobustalternatives

    startingwithLOOKUP.

    OneoftheprimaryreasonstomoveawayfromIFstatementsformultiplecriteriaissothatyoucanuse"tablebased"reference

    data. Thisgivesyoutheabilitytohaveyourdatapointsonaworksheet,wherethevaluescanbeeasilychanged,asopposedto

    hardcodedin

    aformula,

    where

    changing

    the

    values

    can

    be

    achallenge.

    Many

    workbooks

    have

    broken

    because

    of

    numerous

    IF

    statementsthatsomeonedidntupdate. Inthecommissionexampleabove,whatwouldhappenifyouneededtochangethe2%

    andyouhadhundredsofformulasdependingonthatone? Itwouldntbefun,andthatsarelativelysmallexample. Imagineone

    with64conditions! Andthatsifyoucanevenfindtheformulainthefirstplace! Tablebaseddependenciesaremucheasierto

    changeonthefly,whichcanmeanalotespeciallyifyouredealingwithcomplexmodelsandtestingmultiplecriteria.

    Note:datatablesthatdrivereferentialformulasdontneedtobehousedintheopenwhereuserscanchangethem. Veryoftenyoullfindsensitivetableshousedonhiddenworksheets,whereonlythecreator/administratorcanchangethedata.

    ThefirstformulainthefamilyofreferentialformulasisLOOKUP(theyrecalledreferentialformulasbecausetheycanreturna

    referencetoavalue,oravalueinarangeofvalues). LOOKUPhasplentyofuses,butitsalsothemostfragileandleastflexiblein

    theLookupfamily.

  • 7/21/2019 Excel if Statements LOOKUPS

    2/8

    FollowingareexamplesofaDiscounttable,andaGradestableusingastandardLOOKUPfunction:

    ALOOKUPformulaevaluatesavalue(eitherhardcodedorinacell)thenfindsamatchforitinatablethatliststhevaluestobe

    lookedup,andthevaluestoreturn. IntheseexamplesImusingLOOKUPtoreturnavariablerangefromalistofvalues. LOOKUPis

    governedbythefollowingsyntax:

    =LOOKUP(Valueyouwanttolookup,rangewhereyouwanttoreturntherightmostvalue).

    NOTE:LOOKUPformulascanlookupahardcodedvalue,ortheycanlookupavaluefromacell.

    =VLOOKUP(900,A2:B23)&LOOKUP(A5,A2:B23)doexactlythesamething,butthelatterismuchmoreflexiblesinceyoudonthavetochangethe900

    valuewheneveryouwanttochangethelookupvalue. Youshouldalwaystrytousecellreferencesinformulasasopposedtohardcodedvalues.

    Sointheexampleabove,=LOOKUP(A5,A2:B23) willlookinrangeA2:A23forthevalueclosesttowhatwasenteredincellA5,and

    returnthecorrespondingvaluefromcolumnB. Inthiscase,lookingfor$900resultsina2%resultbymatching$750,whichisthe

    largestvaluethatslessthanorequaltothevalueevaluatedbytheformula. Hadyouenteredavaluebetween$1,000and$1,249

    theresultwouldhavebeen3%. NotethattheLOOKUPformularequiresyourdatatobesortedinAscendingorder,otherwiseits

    notgoingtoprovideyouwithconsistentorcorrectresults. AquicknoteonLOOKUPanditscounterpartVLOOKUPisthattheycan

    onlylooktotherightofthelookupvalue;theycantgototheleft. ForthatyouneedtocombineINDEX/MATCH,whichwillbe

    coveredlater.

  • 7/21/2019 Excel if Statements LOOKUPS

    3/8

    VLOOKUPThisisthebigbrothertotherelativelylimitedLOOKUP,andgivesyoumoreflexibilitywithregardstowhatdatayoucan

    returnandwhere. VLOOKUPfollowsthissyntax:

    =VLOOKUP(Valueyouwanttolookup,rangewhereyouwanttolookupthevalue,numberofcolumnstotherightofthe

    foundvalue,ExactMatchorApproximateMatchIndicatedwith0/FALSEor1/TRUE).

    SowhereLOOKUPisgoingtoreturnavaluefromtherightmostcolumnintherangethatyouspecify,VLOOKUPletsyoulookupa

    multicolumnrange,andchoosewhichcolumnfromwhichtoreturnavalue. VLOOKUPisveryoftenusedinfinancescenarioswith

    12Monthperiodsbecauseyoucaneasilychoosewhichmonthtoreturn.

    Notethefirsttwoformulasusestaticcolumnreferences(2&3),whichtelltheformulatoreturnvaluesfromthesecondandthird

    columnsrespectively:

    =VLOOKUP($A8,$A$2:$M$4,2,FALSE)

    =VLOOKUP($A8,$A$2:$M$4,3,FALSE)

    Thisisallwellandgood,andformanymodelslikethisoneitsok,butitcanbetimeconsumingtohavetogointoeachformulaand

    adjustthosecolumnreferences. Thelatterformulas(Marchforward)useatricktomakethecolumnsdynamicbyusingthe

    COLUMN()functioninstead:

    =VLOOKUP($A8,$A$2:$M$4,COLUMN(),FALSE)

    SointhecaseofMarch,itsthe4th

    columntotheright,andCOLUMN()returnsa4,whichfeedsthecorrectnumbertotherestofthe

    formula.Butthisexampleassumesthatyoullhavearelativelystaticdatasetliketheoneabove. Butwhatifyourcolumnheaders

    arentalwaysthesame? ThenextexampleshowsyouhowtobuildadynamicVLOOKUPwhereyoudonthavetoknowtheheaders

    orwheretheyrelocated,yousimplyhavetheformuladoitforyou.

  • 7/21/2019 Excel if Statements LOOKUPS

    4/8

    Inthisexampleyoucoulduse:=VLOOKUP($A5,$A$9:$F$48,2,FALSE), butyouwouldneedtomanuallyadjustthecolumnreference

    accordingly,knowingthatNameiscolumn2,Departmentiscolumn5,Earningscolumn6,andRegioncolumn4. Oryoucan

    introducetheMATCHformula. UsingMATCH,youdontneedtoknowthecolumnheaders,becauseyoutelltheformulatofind

    themforyou.

    TheformulasinB5:E5are(theredtextindicateswheretheformulasaredifferent):

    =VLOOKUP($A5,$A$9:$F$48,MATCH(B4,$A$8:$F$8,0),FALSE)

    =VLOOKUP($A5,$A$9:$F$48,MATCH(C4,$A$8:$F$8,0),FALSE)

  • 7/21/2019 Excel if Statements LOOKUPS

    5/8

    =VLOOKUP($A5,$A$9:$F$48,MATCH(D4,$A$8:$F$8,0),FALSE)

    =VLOOKUP($A5,$A$9:$F$48,MATCH( E4,$A$8:$F$8,0),FALSE)

    ThisisverysimilartousingtheCOLUMN()functioninthepreviousexample,exceptthistimethecolumnsarentinorder,sowe

    cantusethat. InsteadweuseMATCH,whichfindsthevaluewespecify. InthiscasewematchtheheadervaluesinB4:E4(Name,

    Department,Earnings,andRegion)withthecorrespondingheadersinA8:F8. MATCHreturnsanumericmatchfromthebeginning

    ofthedataseriestotheend,soNameis2,Departmentis5,andsoon.

    MATCHsyntax

    is

    as

    follows:

    =MATCH(Valueorcellyouwanttofind,Rangetolookin,0=Onlyfindanexactmatch).

    NOTE:Ifyouleavethe0outorputa1,theformulawillfindtheclosestapproximatematch.

    NextintheLOOKUPfamilyoffunctionsisHLOOKUP. WhereVLOOKUPisaverticallookup,lookingfromlefttorightinarange,

    HLOOKUPisahorizontallookup,whichgoesfromtopdowninarange.

    HLOOKUPssyntaxisverysimilartoVLOOKUP:

    =HLOOKUP(Valueyouwanttolookup,Rangeyouwanttolookin,numberofrowsdowntoreturnavalue,TRUE/FALSE)

    NOTE:Hereagain,1/TRUEwillreturnanapproximatematch,while0/FALSEwillreturnanexactmatch.

    InthiscaseImdoingadynamicHLOOKUPsothatIdonthavetoknowthepositionsoftherowsthatIwanttoreturn.

    WheretheformulasinC5:E5are:

    =HLOOKUP($B5,$A$7:$F$16,MATCH(C4,$A$7:$A$16,0),FALSE)

    =HLOOKUP($B5,$A$7:$F$16,MATCH(D4,$A$7:$A$16,0),FALSE)

    =HLOOKUP($B5,$A$7:$F$16,MATCH(E4,$A$7:$A$16,0),FALSE)

    SoforC5,ImlookingforthevalueinB5(Qtr3)inA7:F16,andMATCHisreturningthe4th

    rowdownforGrossProfit. Withoutthe

    MATCHformulaitwouldbe:

    =HLOOKUP($B5,$A$7:$F$16,4,FALSE)

  • 7/21/2019 Excel if Statements LOOKUPS

    6/8

    Andyouwouldneedtomanuallyadjusttherowreferencesasyoucopiedtheformula,soyoudneedtomanuallydeterminewhere

    GrossProfit,NetProfitandProfit%fellwithinthatrangeandadjusttheformulatosuit.

    Finally,weremovingontowhatisprobablythemostpowerfuloflookupcombinations,whichiswhenyouuseINDEX&MATCH

    together. YouvealreadyseenhowyoucanuseMATCHtomakelookupsmoredynamic,butwhathappensifyouneedtodoa

    lookuptotheleft,whenLOOKUPsonlygototheright? INDEX/MATCHisthesolution,andonceyougetthehangofit,youllbe

    surprisedhoweasyitis.

    YouknowthatMATCHreturnsareferenceforavaluefoundinatablebygivingyouthevaluespositioninthetable. INDEXreturns

    aROW&COLUMNreferenceinarangebasedonwhatrow&columnyoutellittolookin,so:

    =INDEX(A1:B10,1,2)

    WouldreturnthevalueincellB1,whereINDEXssyntaxis:

    =INDEX(Rangeyouwanttolookin,#ofrowstolookdownfromthetopoftherange,#ofcolumnstolooktotherightof

    therange).

    Butwait,youmightbethinkingthatscontrarytowhatIsaidaboutINDEX/MATCHbeingabletolookleft! Dontworry,theycanand

    thefollowingexampleshowshow:

    Note:aswithLOOKUPsyoucanreturnamatchingvalueinthesamecolumnasthelookupvalue,butthatsgenerallypointlessunlessyourejusttrying

    toseeifavalueactuallyexistsinatable.

  • 7/21/2019 Excel if Statements LOOKUPS

    7/8

  • 7/21/2019 Excel if Statements LOOKUPS

    8/8

    Inthiscase,wereusingtheEmployeeNametoreturntheothervaluesinthelist. SomearetotherightofEmployeeNameand

    someareontheleft. Thevariousformulasareasfollows:

    EmployeeID#: =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0),MATCH( $A5,$A$11:$F$11,0))

    SSN: =INDEX($A$12:$F$51,MATCH($B$4, $B$12:$B$51,0),MATCH($A6,$A$11:$F$11,0))

    Region: =INDEX($A$12:$F$51,MATCH($B$4, $B$12:$B$51,0),MATCH($A7,$A$11:$F$11,0))

    Department:

    =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0),MATCH($A8,$A$11:$F$11,0))

    Earnings: =INDEX($A$12:$F$51,MATCH($B$4, $B$12:$B$51,0),MATCH($A9,$A$11:$F$11,0))

    TheonlyvariationintheformulasisA5:A9,whereImtellingitwhatcolumnheadertofindintheinformationtable.

    SotheINDEXformulasaysLookintherangeA12:F51andfirstfindtherownumberthatholdstheemployeenameinB12:B51,then

    findthecolumnnumberthatholdstheheader(EmployeeID#,SSN,Region,etc.)inA11:F11,andreturntheintersectionofthose

    twovalues. SointhisexampleforSandyStewart,forEmployeeID#,Iwantthe4th

    rowinthefirstcolumn,whichistotheleftofthe

    namecolumnwerelookingin. Sothatshowyoucanlookuptotheleft.

    Nowyoumightbethinkingthatsabithardtofathomallatonce,andfranklyitcanbe,buttheresatricktobuildingcomplex

    formulaslike

    this:

    you

    do

    them

    one

    step

    at

    atime.

    Youll

    see

    the

    detail

    of

    how

    Igot

    here

    in

    the

    sample

    workbook,

    but

    Ill

    walk

    you

    throughitjustincase.

    First,sinceIknowIllbeusingEmployeenameastheprimarydriverfortherestoftheformula,Istarttherebymatchingasample

    nameintheNamecolumn. Inthiscase,SandyStewartisrow4,whichIfindwithaMATCHformula:

    =MATCH($B$4,$B$12:$B$51,0) SofindSandysnameincolumnBandgivemeanexactmatch.

    ThenstartingwithEmployeeID#,whichIknowiscolumn1,Itakethe4andaddittoanINDEXformula:

    =INDEX($A$12:$F$51,4,1)

    WhichgivesmeE033,andthatsthefourthrowinthefirstcolumn.

    NowIneedtoreplacethe4andthe1. Ialreadyhavethe4,soIcanaddthatnext:

    =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0) ,1)

    NextIneedtofindthe1forEmployeeID#,whichIcandowithanotherMATCHformula:

    =MATCH($A5,$A$11:$F$11,0)

    Finally,Ireplacethe1withmynewMATCHformula:

    =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0), MATCH($A5,$A$11:$F$11,0) )

    Nowyoucancopythefinalformuladown,andaslongasyougotyourAbsolutereferencesrightitwillautomaticallyupdateforeach

    cellitscopiedinto.