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

ExcelIFStatements,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.

IFstatementsareoneofthecoreformulamodelsyoucanuseinExcel,andtheycanbeverypowerfulwithregardstotheirlogic. 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(A1<60,"F"))))) Anotheriscalculatingcommissionstatements: =IF(A1>25000,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 hardcodedinaformula,wherechangingthevaluescanbeachallenge.ManyworkbookshavebrokenbecauseofnumerousIF statementsthatsomeonedidntupdate.Inthecommissionexampleabove,whatwouldhappenifyouneededtochangethe2% andyouhadhundredsofformulasdependingonthatone?Itwouldntbefun,andthatsarelativelysmallexample.Imagineone with64conditions!Andthatsifyoucanevenfindtheformulainthefirstplace!Tablebaseddependenciesaremucheasierto changeonthefly,whichcanmeanalotespeciallyifyouredealingwithcomplexmodelsandtestingmultiplecriteria. Note:datatablesthatdrivereferentialformulasdontneedtobehousedintheopenwhereuserscanchangethem.Veryoftenyoullfindsensitive
tableshousedonhiddenworksheets,whereonlythecreator/administratorcanchangethedata.

ThefirstformulainthefamilyofreferentialformulasisLOOKUP(theyrecalledreferentialformulasbecausetheycanreturna referencetoavalue,oravalueinarangeofvalues).LOOKUPhasplentyofuses,butitsalsothemostfragileandleastflexiblein theLookupfamily.

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.

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,itsthe4thcolumntotheright,andCOLUMN()returnsa4,whichfeedsthecorrectnumbertotherestofthe formula.Butthisexampleassumesthatyoullhavearelativelystaticdatasetliketheoneabove.Butwhatifyourcolumnheaders arentalwaysthesame?ThenextexampleshowsyouhowtobuildadynamicVLOOKUPwhereyoudonthavetoknowtheheaders orwheretheyrelocated,yousimplyhavetheformuladoitforyou.

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)

=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. MATCHsyntaxisasfollows: =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,andMATCHisreturningthe4throwdownforGrossProfit.Withoutthe MATCHformulaitwouldbe: =HLOOKUP($B5,$A$7:$F$16,4,FALSE)

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.

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)) =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0),MATCH($A7,$A$11:$F$11,0)) =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0),MATCH($A8,$A$11:$F$11,0)) =INDEX($A$12:$F$51,MATCH($B$4,$B$12:$B$51,0),MATCH($A9,$A$11:$F$11,0))

Region: Department: Earnings:

TheonlyvariationintheformulasisA5:A9,whereImtellingitwhatcolumnheadertofindintheinformationtable. SotheINDEXformulasaysLookintherangeA12:F51andfirstfindtherownumberthatholdstheemployeenameinB12:B51,then findthecolumnnumberthatholdstheheader(EmployeeID#,SSN,Region,etc.)inA11:F11,andreturntheintersectionofthose twovalues.SointhisexampleforSandyStewart,forEmployeeID#,Iwantthe4throwinthefirstcolumn,whichistotheleftofthe namecolumnwerelookingin.Sothatshowyoucanlookuptotheleft. Nowyoumightbethinkingthatsabithardtofathomallatonce,andfranklyitcanbe,buttheresatricktobuildingcomplex formulaslikethis:youdothemonestepatatime.YoullseethedetailofhowIgothereinthesampleworkbook,butIllwalkyou 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.

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