248 8 12MB
English Pages 382
ExcelbyExample
This page intentionally left blank
ExcelbyExample
AMicrosoft®ExcelCookbookforElectronicsEngineers ByAubreyKagan
AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Newnes is an imprint of Elsevier
NewnesisanimprintofElsevier 200WheelerRoad,Burlington,MA01803,USA LinacreHouse,JordanHill,OxfordOX28DP,UK Copyright©2004,ElsevierInc.Allrightsreserved. Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedin anyformorbyanymeans,electronic,mechanical,photocopying,recording,orotherwise, withoutthepriorwrittenpermissionofthepublisher. PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRightsDepartmentinOxford,UK:phone:(+44)1865843830,fax:(+44)1865853333,e-mail: [email protected].Youmayalsocompleteyourrequeston-lineviatheElsevier homepage(http://elsevier.com),byselecting“CustomerSupport”andthen“ObtainingPermissions.” Recognizingtheimportanceofpreservingwhathasbeenwritten,Elsevierprintsitsbookson acid-freepaperwheneverpossible. LibraryofCongressCataloging-in-PublicationData
(Applicationsubmitted.)
BritishLibraryCataloguing-in-PublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary. ISBN:0-7506-7756-2 ForinformationonallNewnespublications visitourwebsiteatwww.newnespress.com 04050607080910987654321 PrintedintheUnitedStatesofAmerica.
InmemoryofJonathanMosheKagan
This page intentionally left blank
Contents Acknowledgments.......................................................................................................xiii Introduction...............................................................................................................xiv What’sontheCD-ROM?.......................................................................................... xviii EXAMPLE1:Voltage-to-CurrentConverter.................................................................. 1 ModelDescription......................................................................................................................................1 StartingExcel.............................................................................................................................................2 DataEntryintoaWorksheet.....................................................................................................................3 Autofill.......................................................................................................................................................5 BulkFormatting.........................................................................................................................................7 Formulas.....................................................................................................................................................8 CopyingFormulas......................................................................................................................................9 RelativeandAbsoluteReferences...........................................................................................................10 NamingCells............................................................................................................................................12 HidingCells.............................................................................................................................................15 Borders......................................................................................................................................................15 BellsandWhistles....................................................................................................................................17 ConditionalIFandAbsoluteValue.........................................................................................................17 Chart........................................................................................................................................................17 ErrorBars..................................................................................................................................................20 AddingaTrendline..................................................................................................................................21 Macro:Timer............................................................................................................................................22
EXAMPLE2:BaudRateSelection............................................................................... 26 ModelDescription....................................................................................................................................26 SetupWorkbook......................................................................................................................................27 Hexadecimal.............................................................................................................................................29 LookupTables..........................................................................................................................................30 ConditionalFormatting...........................................................................................................................33 Macro.......................................................................................................................................................35
EXAMPLE3:MeanTimeBetweenFailures(MTBF).................................................... 41 ModelDescription....................................................................................................................................41 Factors......................................................................................................................................................42
vii
ExcelbyExample BillofMaterial.........................................................................................................................................44 CalculatingtheQualityFactor................................................................................................................49 CalculateElectricalStressFactor.............................................................................................................50 CalculationofλG......................................................................................................................................52 Scenario....................................................................................................................................................54
EXAMPLE4:CountingMachineCycles....................................................................... 58 ModelDescription....................................................................................................................................58 ImportingtheFile....................................................................................................................................58 ExtractingOp-code..................................................................................................................................62 OpeningaSecondWorkbook..................................................................................................................63 CrossWorkbookReference......................................................................................................................67 EasingthePainofNestedIFs...................................................................................................................67
EXAMPLE5:CharacterGenerator.............................................................................. 69 ModelDescription....................................................................................................................................69 CreatingtheBasicWorkbook..................................................................................................................70 LENFunction...........................................................................................................................................71 FormsControls.........................................................................................................................................71 TextOrientation......................................................................................................................................75 Comments................................................................................................................................................75 Double-ClickMacro................................................................................................................................76 MacroActivationbytheCommandButton...........................................................................................78 SavetoDataFile......................................................................................................................................81 Usage........................................................................................................................................................85
EXAMPLE6:8052MicrocomputerRegisterSetup...................................................... 86 ModelDescription....................................................................................................................................86 SpreadsheetConcept...............................................................................................................................86 Counter/Timer0Sheet............................................................................................................................93 TimerCounterControlRegisterTCON.................................................................................................97 CountingTypes........................................................................................................................................97 MacrostoHideandUnhide..................................................................................................................102 AddingForms.........................................................................................................................................106 AddImageControl................................................................................................................................108 Timer/Counter1Sheet..........................................................................................................................111 Timer/Counter2Sheet..........................................................................................................................112 SerialPortSheet....................................................................................................................................113 InterruptControlSheet.........................................................................................................................113 SummarySheet......................................................................................................................................115 InitializeValues......................................................................................................................................116 Conclusion.............................................................................................................................................116
EXAMPLE7:FindingtheOptimalResistorCombination:LP2951............................ 118 ModelDescription..................................................................................................................................118 CustomAutofill......................................................................................................................................118 DataTables.............................................................................................................................................120 MinFunction.........................................................................................................................................123 MATCHFunction.................................................................................................................................123
viii
Contents INDEXFunction....................................................................................................................................124 BlockConditionalFormatting...............................................................................................................125
EXAMPLE8:ResistorColorCodeDecoderUsingSpeechInput................................ 127 ModelDescription..................................................................................................................................127 ImplementingSpeechRecognition.......................................................................................................129 ViewingandHidingtheLanguageBar..................................................................................................129 WorksheetSetup....................................................................................................................................130 Macros....................................................................................................................................................130 CustomToolbar......................................................................................................................................134 AddingSpeech.......................................................................................................................................137 EvaluatetheColorCode........................................................................................................................137 TexttoSpeech.......................................................................................................................................141 Conclusion.............................................................................................................................................142
EXAMPLE9:RTDto4–20mAConverter:XTR105.................................................. 143 ModelDescription..................................................................................................................................143 AcquiringRTDTables...........................................................................................................................144 LookupRTDValue................................................................................................................................148 CreatingaFunction...............................................................................................................................149 AccessingaFunction............................................................................................................................150 AddingaHelpDescriptiontoaFunction.............................................................................................152 CreatingtheModelinExcel..................................................................................................................152 StandardResistorValues........................................................................................................................155 CreationofAdd-In................................................................................................................................158 InstallingtheNearestValuesAdd-In.....................................................................................................158 BacktotheProjectAtHand.................................................................................................................159 PromptingforUserInput.......................................................................................................................161 Printout..................................................................................................................................................162 RunningMacroswhentheWorkbookisStarted..................................................................................163 RunningfromtheDesktop....................................................................................................................166
EXAMPLE10:VoltageRegulator:LM317................................................................. 167 ModelDescription..................................................................................................................................167 InstallingtheNearestValuesAdd-In.....................................................................................................168 InitialModel..........................................................................................................................................168 GoalSeek...............................................................................................................................................170 WorstCaseAnalysis...............................................................................................................................172 ThermalAnalysis...................................................................................................................................173 Half-WaveRectification........................................................................................................................179 TrueRMSandIntegration.....................................................................................................................179 MorePreparation...................................................................................................................................181 StandardCapacitanceValue..................................................................................................................184 Chart......................................................................................................................................................186 Conclusion.............................................................................................................................................189
EXAMPLE11:TL431AdjustableVoltageReference.................................................. 190 ModelDescription..................................................................................................................................190 InstallingtheNearestValuesAdd-In.....................................................................................................190
ix
ExcelbyExample InitialModel..........................................................................................................................................191 Solver.....................................................................................................................................................191 StandardResistorValues........................................................................................................................199 AddingaMacro.....................................................................................................................................199 Limitations.............................................................................................................................................204
EXAMPLE12:555Timer.......................................................................................... 206 ModelDescription..................................................................................................................................206 MonostableOperation...........................................................................................................................206 Setup.......................................................................................................................................................207 AddUserForm.......................................................................................................................................207 AddImageControl................................................................................................................................208 SecondImage.........................................................................................................................................210 ModifyingFormLocation......................................................................................................................212 MonostablePulseWidthEntry..............................................................................................................214 CommandButton..................................................................................................................................216 Solver.....................................................................................................................................................219 StandardValues......................................................................................................................................220 SolverSolve............................................................................................................................................220 UsingStandardCapacitorValues..........................................................................................................221 TidyingUp..............................................................................................................................................223 AstableOperation..................................................................................................................................223 WorksheetSetup....................................................................................................................................224
EXAMPLE13:PurchaseOrderGenerator................................................................. 229 ModelDescription..................................................................................................................................229 CreateaPurchaseOrder........................................................................................................................229 PrintMacro............................................................................................................................................231 UserForm...............................................................................................................................................233 InitialProcedure.....................................................................................................................................235 EventActions........................................................................................................................................236 AutoStartup..........................................................................................................................................238 RunningPurchaseOrder.........................................................................................................................239
EXAMPLE14:InterfacetoaDigitalMultimeterUsingaSerialPort........................... 240 ModelDescription..................................................................................................................................240 DMMInterfaceProtocol........................................................................................................................241 MSComm32...........................................................................................................................................243 InitializingtheSerialPort......................................................................................................................248 ConversionofDMMDisplaytoData....................................................................................................258 AnalogMeterChart...............................................................................................................................260 ZoneIdentification.................................................................................................................................267 DataPlot—ChartRecorder...................................................................................................................271 FoodForThought..................................................................................................................................279
EXAMPLE15:VernierCaliperInterface.................................................................... 281 ModelDescription..................................................................................................................................281 Pinout.....................................................................................................................................................282 HardwareInterface.................................................................................................................................282
x
Contents TimingDiagram......................................................................................................................................283 InstallingIO.DLL...................................................................................................................................284 PCParallelPort......................................................................................................................................284 FirstSteps...............................................................................................................................................286 ActualInterface.....................................................................................................................................287 AcquiringData.......................................................................................................................................287 AddingSound........................................................................................................................................292 ThoughtsonImprovement....................................................................................................................293 Statistics.................................................................................................................................................294
EXAMPLE16:FunctionGeneratorInterface............................................................. 301 ModelDescription..................................................................................................................................301 SerialInterface.......................................................................................................................................302 WorkbookOpenandClose....................................................................................................................302 AddingVBAControls:Granularity......................................................................................................305 AddingVBAControls:Frequency........................................................................................................309 WaveformSamplingFrequency.............................................................................................................311 BumpFrequency.....................................................................................................................................313 GeneratingFrequencyTables.................................................................................................................315 AddaChart...........................................................................................................................................319 DownloadWaveform.............................................................................................................................322 SettingtheAmplitude...........................................................................................................................326 Skew.......................................................................................................................................................327 AverageVoltage,RMSVoltage..............................................................................................................330
APPENDIXA:VBAandExcel................................................................................... 333 APPENDIXB:ParallelandSerialI/O........................................................................ 349 References................................................................................................................ 354 AbouttheAuthor..................................................................................................... 357 Index........................................................................................................................ 358 ListofInParenthesisSidebars CopyingWithandWithoutFormat...................................................................................................6 AutofillofNonnumericSequences.....................................................................................................7 MultipleSelections.............................................................................................................................8 AddingColumns/Rows.......................................................................................................................9 DeletingColumns/Rows/Cells..........................................................................................................10 CellNames........................................................................................................................................13 WorksheetNavigation......................................................................................................................14 Zoom..................................................................................................................................................20 MergeCells.......................................................................................................................................28 NumberBaseConversion.................................................................................................................29 SplitScreen.......................................................................................................................................30 Lookup...............................................................................................................................................31 ConditionalFormatting....................................................................................................................34 MultipleWorksheets.........................................................................................................................42
xi
ExcelbyExample CommaDelimitedFiles....................................................................................................................45 Comments.........................................................................................................................................46 INDEX...............................................................................................................................................49 TableFunctions.................................................................................................................................51 RecalculationandAuditingFormulas..............................................................................................65 FormsControlsinaDifferentVersionofExcel................................................................................72 CellProtection..................................................................................................................................77 CellsNotationVersusStringManipulation.....................................................................................78 FormsControl...................................................................................................................................87 ExcelWarningDetection..................................................................................................................99 ROUND..........................................................................................................................................101 CommunicatingCustomListsBetweenDifferentComputers.......................................................119 DataTables......................................................................................................................................119 TransposingData.............................................................................................................................121 MATCH..........................................................................................................................................123 INDEX.............................................................................................................................................124 SpeechRecognition........................................................................................................................129 InstallingSpeechRecognition........................................................................................................129 ExportingaToolbar.........................................................................................................................136 CONVERT......................................................................................................................................154 InputBox..........................................................................................................................................162 MessageBox.....................................................................................................................................163 CHOOSE.......................................................................................................................................177 SolverOptions................................................................................................................................197 UseofConstraints...........................................................................................................................198 MoreonComboBoxes..................................................................................................................213 ControlToolbox..............................................................................................................................218 SolverSolveFunction......................................................................................................................221 CallinganExcelFunctionfromVBA............................................................................................221 AdditionalControls.......................................................................................................................245 MSCommProperties.......................................................................................................................246 Timer...............................................................................................................................................250 DoEvents.........................................................................................................................................251 OnCommEvent..............................................................................................................................252 CustomToolbarLimitation............................................................................................................257 OFFSET...........................................................................................................................................275 COUNTA/COUNT/DCOUNT/DCOUNTA/COUNTBLANK.................................................275 SERIESFunction............................................................................................................................276 FREQUENCY.................................................................................................................................296 NORMDIST...................................................................................................................................297 ControlsinExcel............................................................................................................................305 ComboBoxControl........................................................................................................................307 StringFunctions..............................................................................................................................309 FourierAnalysis...............................................................................................................................316 Fill...................................................................................................................................................319 VBAandBitManipulation............................................................................................................323
xii
Acknowlegments TheideaofthisbookwasintroducedbyCarolLewis,andherguidanceandexpertisehave piloteditthroughtopublication.Conversionofmymanuscripttotheproductyouhavein yourhandswasdonebyKellyJohnson.MythanksgoestothembothandTiffanyGasbarrini, andtothosewhoseworkatElsevierhasremainedunseentome,forwhatIhopeyouwill agreeisanoutstandingeffort. Iwouldalsoliketothankthemanagementandmyco-workersatEmphatecInc.(previously WeidmullerCanadaLtd.),especiallyErnestoGradinandDonRobinsonfortheirsupport, adviceandencouragementformyoriginalarticlesandsubsequentlythisbook. Thanksarealsodueto: AlbertoRicciBittiforpermissiontousehisidea,whichformsthebasisofExample6,Fred BulbackforpermissiontoincludeIO.DLLontheCD-ROM,CircuitCellarandEDNfor providingtheformattoallowmetodevelopmyideasandhonemywritingskills. Tomychildren,parentsandsister,allofwhomencouragedmetotacklethisprojectand whosecontinuedinterestcontinuedtomotivate,thankyou. Inherusualself-deprecatingmanner,mywife,Nicky,hasaskedthatshenotbementioned, andthatacknowledgmentisnotneededforhersupport,bothspiritualandlogistical.Farbe itfrommetocontradicther,butnevertheless,ThankYou.
xiii
Introduction Whenfacedwithanewsoftwaretool,mostofuslearnwhatweneedtoaddressour immediateproblem,andthenarmedwith10%ofthetoolsthatareavailableweattempt tosolveallfutureproblems.Inmydiscussionswithcolleagues,Ihavefoundthatthe spreadsheetisthequintessenceofthiseffect.AlmosteverybodyhasMicrosoft®Excel ontheircomputer,yetfewuseitforanythingbutthemostmundanetasks,ratherlike asophisticated,butunwieldycalculator.Infact,Irecentlysawanewspaperarticlethat heraldedthedemiseofthecalculatorasaresultofthespreadsheet,PDAsandother electronictools. Mostoftheliteratureonthesubjectofspreadsheetsingeneral,andMicrosoftExcelin particular,dealwithgenericcasesofhomeeconomicsorfinancialprojects.Veryfewhave directanalogiestotheworkdoneinelectronics.Yet,thespreadsheetisideallysuitedtoallow theelectronicsengineer(indeedanyengineer)to“worksmarter,notharder.”Overtheyears IhaveworkedwithSupercalc,Multimate,Lotus1-2-3,Framework,Symphony,Quattroand QuattroPro.Intheend,theyallareverysimilar.Mostofwhatiscoveredinthisbookcanbe implementedinanyoneofthecurrentcompetitorstoExcel,withouttoomanychanges. Thegenesisofthebookwasalittlecircuitous.Mysupervisoratworksuggestedthatwe shouldrunseminarsondifferentsubjectssharingeachindividual’sexpertise.Ithoughtsome referencenotesonExcelmightbehelpful.Thisledtoaseriesofthreearticlesthatwere publishedinCircuitCellarOnlinestartinginJanuary2002.Severalreaderscontactedmeand suggestedadditionalsubjectmatterthatwouldbeinteresting.Then,outoftheblue,Iwas approachedbyElseviertowriteabookbasedonthesearticles.Sincetheformatofabook allowsformorescope,Ihaveexpandedontheoriginalideas,addedafew,andIhavealso triedtoincorporatemuchofthefeedbackthatIreceived. IfyouonlybuyonebookonExcel,thenofcourse,Ihopeitismine.However,itisnotmy intentionthatthisbookbetheonlybookonthesubjectthatyouwilleverneed.Ihaveonly triedtoexplaingeneralsubjectsthatIuseintheexamples,sinceIhavefoundthemuseful.I leavethedetailedexplanationstothemoregeneralbooksthatareavailable,sinceIamsure
xiv
Introduction theyarebetteratitthanI.SinceIamwritingthisbookforelectronicsengineers,Ipresumea degreeoffamiliaritywithacomputer,includingprogramming,andIjumpintomacrosfairly early.Ihavetriedtomakemostofthemacrosintoa“blackbox”sothatifyoudon’treally wanttoknowwhatgoesoninside,butstillneedthefunction,youcan.Inaddition,Ihave triedtomaketheexamples“standalone,”whichmeansthatsomeofthebasictechniques likeinvokingtheVisualBasic®Editor(VBE)aredescribedquitefrequently. TheexampleshavebeendevelopedforthisbookunderExcel2002.Nodoubtbythe timethebookispublishedtherewillbeatleastonenewrevision.Someoftheoriginal developmentworkwascreatedunderExcel97,somostofthisshouldworkonanyversion fromthattime.WhereIamawarethatafeaturehasbeenaddedsince‘97(suchasspeech input)Ihopetopointthemout.PleaseforgivemeifIamlessthanaccuratewiththis information. Likemostofus,afteraperiodofuseIhavebecomesettledwithinmyknowledgeofthe subject.IamguiltyofnotextendingmyknowledgeusingmoreofthefeaturesofExcel.Feel freetocontactmeandletmeknowwhatyoufindusefulandwhatyouthinkismissing. Betteryet,whydon’tyousubmittheideatoEDNorElectronicDesignandseeyournamein print(plusmakealittlemoneyontheside).That’showIstarted;perhapsyoutoocanwrite abook. AnEnglishengineeroncetoldmethatmywritingstyleremindedhimofSomerset Maugham,aBritishnovelistfromthe1930s.ThisisnosmallfeatconsideringthatIwas writingspecificationsforaroboticarmontheInternationalSpaceStationatthetime. WhilstIamsuremyeditorwillcorrectallmyanglicizedspellings,thestylewilllikely remain.Ihopeyoudon’tfindittoodistracting. Ithasbeenmyexperiencethatinanytechnicalpresentation,whentheapplicationhas someglamouraboutittheaudienceisfarmoreinterested,irrespectiveofhowmundane thetechnologymightbe.Inthatlight,Ihopethatyoufindtheideasincludedinthisbook original,provocativeanduseful.Dependingonworkcommitments,Icannotpromisea speedyordetailedresponse,butfeelfreetocontactmeat[email protected]with commentsandsuggestions.
RulesofEngagement Conventions: IhaveadoptedafairlytraditionalapproachtodocumentingdataentryintoExcel.Unless otherwiseindicated,aclickonthemouseisaclickontheleftmousebutton.Notwithstanding thatitispossibletochangetheallocationofthemousekeys,Iamreferringtothedefault configuration.Whereaclickofthe(left)mousebuttonexecutesthedesiredactionitis printedinboldtext,forinstance:Save.Wherethereisasequenceofmenusthatrequire severalmouseclickstheactionsareinboldandarecombinedbyaverticalbar,forexample File|Saveas.Sometimes,aseriesofselectionswillresultinthepresentationoffiletabs.I feelIambeingconsistentindocumentingthisclickinboldaswell.Thingsgetalittlegreyer xv
ExcelbyExample whentryingtodescribeclickingonacheckboxoranoptionbutton.Ihavetriedtomaintain theboldtexttodescribethisaction.Thingsbecomeevenmurkierthoughwhentryingto describeclickingonacontrolthathasbeensetupbytheuser.IftheuserhascreatedaCombo Boxandmydescriptionistoclickononeoftheoptionsinthedrop-downmenuthatappears, isitpartoftheapplicationandthereforedefinitelyinboldarepartoftheapplicationand perhapssomeotherformattingisneeded.Inthissetofcircumstances,Idon’tuseformatting. Certainactionsareinitiatedbyacombinationofkeystrokes.Theseareindicatedinbold withanglebracketsasin.Wherethereisacombinationofkeystrokesthatmust occursimultaneously,theyarejoinedbyaplussymbol.Thekeycombinationtobringup theVBAeditorcopywouldbe+asanexample.InExcel(andanyMicrosoft Officeapplication),itispossibletorunamacrofromakeycombination.Althoughthisis notpartoftheapplication,thiscombinationwillappearinexactlythesameway. Anytextthatisenteredeitherasdata,formulaorascodeinVBAappearsinitalics. VBAHelp/Add-Ins: WhenExcel/Officeisinstalled,theVBAhelpisnormallyomitted.Typically,youwould changethisbygoingtoControlPanelandAdd/RemovePrograms.ThenselecttheOffice entry.YouwillprobablybegivenanoptiontoChangetheinstallation.UnderAddfeatures, searchfortheVBAhelpinstallation.Onmymachine,itwasundertheOfficeShared Featuresfolder.SelecttheRunfrommycomputeroption,andfollowthepromptstoinstall. Whileyouarehere,alsogototheMicrosoftExcelforWindowsfolderintheAdd-inssubfolder,andsetthefollowingoptionstoRunfrommycomputeraswell:AnalysisToolpak, Solver.GoonelevelbackupthetreeandenableTexttospeechaswell.Continuewith theinstallationsupplyingtheCDsasrequested.Ifyoudon’tdothis,thefirsttimeyoutryto accessoneofthefunctionsyouwillbepromptedfortheCDtocompletetheinstallation. AnalysisToolPakAdd-In: ManyofthefunctionsthatIwilluseinthebookareavailableintheAnalysisToolPakaddin.Youmayaswellgoaheadandadditnoworyouwillstarttopickup#NAMEerrorsthat indicatethefunctionwasnotfound.Thisishowtodoit: 1. InExcel,ontheToolsmenu,clickAdd-Ins. 2. IntheAdd-Insavailablelist,selecttheAnalysisToolPakbox,theAnalysis ToolPak–VBA,andtheSolverAdd-in,andthenclickOK. 3. Ifnecessary,followtheinstructionsinthesetupprogram. MacroProtectionMessage: WhenyoufirststartExcelandyouopenafilewithamacroorprocedureinit,Excelwillask ifyouwanttogoaheadanddothis.Thisisasaresultofaproliferationofvirusesthatwere passedinmacros.YoucanmodifythelevelofsecuritytobypassthisinExcelbyfollowing thesequenceTools|Options|Security|MacroSecurity.Choosethelevel(anddegree ofintrusion)thatyouarecomfortablewith. xvi
Introduction
Figure1:AnalysisToolPakAdd-Ins. VBAVariableDeclarationandNamingConventions: Theytellmethatgoodprogrammingpracticerequiresthateveryvariablebeexplicitly declared(inVBAusingtheDimstatement).VBAdoesnotrequirethisinitsdefault state,probablyasahangoverfromtheoriginalBasic.ThisoptioncanbesetintheVBA environmentunderTools|Options|EditorandselecttheRequireVariableDeclaration option. ItisalsoconventiontofollowHungariannotationwhennamingvariablesandobjects.In thismethod,objectnamesareprefixedbyathree-characteridentifier(Form1wouldbecalled frmForm1),andavariablewouldbeprefixedbyasinglecharacterthatidentifiesitsdatatype. iVariablewouldbeaninteger. SomeofmyexamplesweredevelopedbeforeIwasawareofthisnotationandinothers Isimplyforgotorwasnotdisciplinedenoughtoemployit.Inaddition,mostofmy programmingisself-taughtandwasbasedonsmallmicrocomputers,soIamsureIcommit allmannerofsoftwarecodingsinsfrompublicvariablestogotostatementstoinsufficient comments.Iamafraiditisverymuchacaseof“DoasIsay,notasIdo.”
xvii
Introduction DocumentingWorksheets: IfinddocumentingExcelquitedifficult.Normally,youonlyseetheendresultwhilethere isactuallyaformulabehindtheresultandthereisa“knockoneffect”asresultsdependon othercells.Formattingisevenmoredifficultbecauseitmaynotbeobviousthatthecell hasbeenformatted.TherearetechniquesinExceltounmaskthesehiddenfactors,but theyrequireexplicitactions.UsetheFormulasoptioninTools|Options|Viewtosee theformulasused.AntecedentsandprecedentscanbetracedusingtheTools|Formula Auditingsequence.Conditionalformattingcanbeidentifiedbyclickingonanycelland thenEdit|GoTo|Special|ConditionalFormats.Itispossibletofindconditional formattinglikethecurrentcellorallconditionalformatting.PayattentiontotheotherGo Tooptionshere.AllcommentscanbemadevisiblewithView|Comments.Tofindout whatrangeanamerefersto,usethedrop-downarrowbythenameboxtofindthenameand thenclickonthename.
What’sontheCD-ROM? IncludedontheaccompanyingCD-ROM: • •
AfullsearchableeBookversionofthetextinAdobepdfformat Readytorun,customizableExcelworksheetsforeachapplicationcovered
xviii
EXAMPLE
1
Voltage-to-CurrentConverter ModelDescription AverycommonuseofExcelistoenterdataintotheworksheetandthenuseitspowerto analyzethedata.Tostartwith,letmepresentasimpleapplicationtodemonstratesomeof thetoolsincludedwithExceltoenhanceproductivity. Intheindustrialautomationfield,analogsignalsarestilldistributedusingthevenerable4 to20mAcurrentloop.Inthistechnique,theoutputfromanytransducerisconditionedby meansofsomeelectronicstogenerateacurrentof4mAatthebottomofthescaleandvary continuouslyupto20mAatthetopofthescale.TheblockdiagraminFigure1-1describes justsuchanapplicationwherea0Vdcto+10Vdcinputsignalistranslatedto4–20mA output.ThetransferfunctionisIout=((Vin/Vfullscale)*16)+4.Thecurrent,Iout,ismeasuredin milliamps.SinceVfullscaleis10V,thisfunctionreducestoIout=16*(Vin/10)+4. Figure1-1: 0Vdcto+10Vdcisconverted to4–20mAthroughthismodule.
V to I Converter Vin
Iout Thisapplicationwilltakethemeasuredinputvoltagesandoutputcurrentsandanalyzethe linearityofthesystem.Eventhoughthisisasimpleapplication,Iuseitquitefrequently.It isusefultobuildamodelsincethemeasurementsaretakenatdifferentambienttemperaturestoestablishperformancespecifications.Inthisexample,thedataiskeyedinbyhand. Itissimpleenoughtodo,butwewillseeinalaterapplicationhowthedatacanbeacquired automatically. 1
ExcelbyExample
StartingExcel ThisearlyexampleincludesseveralverybasicfeaturesinExcelthatInormallyfinduseful.In manycasestheyareintuitive,inotherstheymaybewellknowntomostofus.Nevertheless, Ithinkitisbeneficialtogothroughthem,slowthoughitmaybe.Pleaseforgiveme.Wewill movealotfasterinlaterexamples. WhenwefirstopenExcel2002,theremaybeanextrawindowontherightsideofthe screenthatsimplifiesthecreationofanewfileasshowninFigure1-2.Iamnotpartialto thisscreen,sothisistheonlytimeyouwillseeitinthisbook.Wecangetridofitbyuncheckingtheappropriatebox,orwecanturnitonoroffthroughthemenus:Tools|Options, andintheViewtab,selectordeselecttheboxnamedStartupTaskPane. Aswithmostapplications,wecanclosethewindowusingtheXinthetopright-handcorner.
Figure1-2:StartupscreeninExcelwithStartupTaskPane. Excelreferstoaspreadsheetasaworkbook.Insidetheworkbooktherecanbeseveralsheets (referredtoasworksheets),andtherecanbeseveralworkbooksopenatatime.Openanew workbook.IftheStartupTaskPaneisstillavailable,simplyclickonthe“BlankWorkbook” selection.Otherwise,wecanstartanewworkbookinseveralwaysdependingonourpreference. Thereisthemenuoption:Files|Newselection,thekeyboardshortcut(+) aslistedinthemenuoption,andthereisalsoaniconontheextremeleftofthetoolbar(see Figure1-3). 2
Example1:Voltage-to-CurrentConverter
Figure1-3:Blankworkbookshowingthelocationofsomeoftheitemsdiscussedinthis example.
DataEntryintoaWorksheet Enteringinformationintoanycelloftheworkbookiseasy.Excelautomaticallypresumes anydataistextandleftjustifiesit.Anyinformationthatispurelynumericalisinterpretedas anumberandisenteredrightjustified.Anyentryprecededbyamathematicalsymbol“+”, “–”or“=”isinterpretedasaformula.Anumbercanbemanipulateddirectlyusingformulas andsoforth,whereastextisnormallyprocessedthroughstringmanipulationinformulas. Ofcourse,itispossibletochangethejustificationaswellastheformatofacelloragroup ofcellsusingformattingcontrolsandthestandardMicrosoft®Windows®techniques.Ifwe wantanentrytobeinterpretedasastringwhenthedefaultwillinterpretitasanumber,we prefixtheentrywithanapostrophe’.Ifweenteranumberthatincludesnonnumericcharacters,Excelwillsimplyidentifyitasanerror. Ifatextentryinacellistoolongtofitwithinthecellitwillappeartoflowovertothe adjacentcell,ifthatcellisempty.Iftheadjacentcellisnotempty,thetextwillbetruncated. Therearesometechniquesthatallowustoimproveonthiswhichwewillseelateron.Editingtheentrythoughstillrequiresclickingontheoriginalcell.
3
ExcelbyExample Itispossibletosizethewidthandheightofcolumnsandrowsbymovingthecursoroverthe linethatdemarcatestheseparationofthecolumnsinthecolumnselectionbar(orrowsin therowselectionbar)untilthesymbolchangestoabarwitharrowsoneithersideandthen clickinganddraggingtheline.OneofthesecretsofWindowsisthatitispossibletoautomaticallysizethecolumn(thisworksinWindows®Exploreraswell).Insteadofclickingand draggingtheline,simplydouble-clickwhenthedoublearrowsymbolappears.Thecolumn willadjusttofitthelargestentryinthatcolumn. Enteringdataintoacellisintuitive,buttherearesomefeaturesthatcansimplifytheprocess.Itispossibletoterminatetheentrybypressingthekeyoroneofthedirection arrows.Thearrowsareakindofshorthandindataentry,sothatonekeystrokebothenters theinformationandtakesustothenextcell(inthedirectionofthearrow).Actually,they onlyworkontheoriginalentryofdataandnotwhenthedataisedited.TheTabkeywill alsoenterthedataandmoveonecolumntotheright.Theactionofthekeyafter usingtheisquiteinteresting.Inthiscase,Exceldeterminesthatweareentering tabulardataandthekeywillvectorustothecellbelowthecellwestartedthehorizontaldataentry.Thisisgreatwhenweareenteringseveralcolumnsofdata,linebylineas itactslikeacarriagereturnandlinefeed. AsidefromtheTabtechniqueabove,itispossibletodecidewhichwaythecursorwillmove afterEnteringinformation.ItcanbechangedintheTools|OptionsmenuandtheEdittab. Editingdatainacellrequiresthatweclickinthecellandthenclickintheformulabar inordertoeditthere.Alternatively,wecandouble-clickonthecellinquestion,andedit directlyinthecell.Wecannowresorttotheusualeditingprocedures. Letusviewsomeofthisinaction.Openanewworkbook.IncellA1,enterthetextVoltagetoCurrentConverter.NownavigatebacktocellA1usingthedirectionarrowsormore simply,clickoncellA1.Itispossibletoformattheappearanceusingthecontrolsonthetask barorthemenucontrols.Changethefontsizeto12,andmaketheappearanceboldusing thedrop-downboxbyusingtheformatoptiononthetaskbar. ClickoncellA5.EnterthetextInputVoltageandpresstheTabkey.Noticehowitoverlaps intoB5.IncellB5(whichshouldbeselectedalready),enterthetextOutputCurrentfollowedbytheTabkey.ThetextincellA5isnowtruncated.EnterthetextProportionincell C5followedbytheTabkey.EnterthetextTheoreticalCurrentincellD5,followedbythe Tabkey.IncellE5,enterthetextErrorfollowedbytheTabkey.Finally,enterLinearityError,followedbytheEnterkeyincellF5.NotethattheselectedcellisnowA6.Thescreen shouldlooklikeFigure1-4. Rightclickontherowselectbuttonforrow5.ClickonFormatCellsandthenclickonthe Alignmenttab.IntheTextControlsection,checktheWraptextoptionandthentheOK button.Movethecursorsothatithoversoverthelinedemarcatingtwocolumnsinthecolumnselectionbaranddragthelinesothatthetextsplitsintotwocolumnswiththedesired visualeffect. 4
Example1:Voltage-to-CurrentConverter
Figure1-4:Tableheadingsshowingthetruncationofthetext. MovethecursorsothatithoversoverthejoinofcolumnsAandBinthecolumnselection bar.Double-clickandnoticehowthecolumnwidthchanges.Itactuallychangedtoaccommodatethewidestentryinthecolumn,thetitleincellA1.ReturntothejoinofcolumnsA andBandclickanddragthelinesothatcolumnAisasuitablewidth.Ofcourse,theUndo featurecouldalsobeused. Let’sdoalittlemorebulkformatting.Clickontherowselectionbuttonforrow5onthe extremeleftofthescreen.Noticehowthewholerowisselected.NowclickontheB(for Bold)buttononthetaskbarandthewholerowisinstantlyconvertedtoaboldtype.
Autofill Let’sassumethatwearegoingtoapply0voltsto10voltsattheinputofourconversion moduleinstepsof1V.ThisdatawillbeenteredincolumnA.Nowwecouldsimplytypein 0inA6,1inA7andsoonallthewaythroughto10incellA16.Thiscouldprovetedious, andExcelprovidesanextremelyeasymethodofautofilling.Enterthevalue0incellA6and 1incellA7,providingtheseedofthestartingnumberandtheincrement(ordecrement)for theautofill.NowclickonA6withoutreleasingthemousebuttonanddragtocellA7sothat bothareselectedasshowninFigure1-5.
5
ExcelbyExample
Figure1-5:Preparingforautofill.CellA6istheinitialvalue,andthedifferencebetween A7andA6providesthestepincrement. Noticethelittleblacksquare(calledthefillhandle)atthebottomright-handcornerofthe framesurroundingtheselection.Movethemousecursoroverthissquareandthecursorwill transformfromalargeunfilledplussigntoasmallersolidplussign.Whenthishappens,click anddragthefillhandledown.Noticeasmallyellowboxthatpopsupnearthecursor.Thisis themaximumnumberthatwillbe“autofilled”whenwereleasethemousebutton.Dragthis untilthepop-upnumberreads“10”asinFigure1-6andreleasethemousebutton. InParenthesis:CopyingWithandWithoutFormat . Thereisasmallsymbolatthebottomcorneroftheblockthathasjustbeenfilled ThissymbolisonlypresentonlaterversionsofExcel.Clickingonitallowsustomodify the waytheformattingofthecellsinvolvedin the autofill is affected. We can safely ignoreitforthemoment. InearlierversionsofExcel(andMicrosoft®Word),therewasanoptionofcopyingwithor withouttheformatting,butitwasburiedinthemenusystem.Thisisnowmoreexplicitascan beseenbythisandsimilarsymbolsthatappearontheworksheetafteranautofillorcopy operation.Itcan,however,bedisabledintheTools|OptionsmenuandtheEdittab. Whilewebuildthemodelwedon’thaveanyrealdata,butithelpstohavesomenumbersto workwith.Enter4representingtheintialcurrentof4mAincellB6and4.5inB7.Autofill usingthesecellstocellB16.
6
Example1:Voltage-to-CurrentConverter
Figure1-6:Autofillinaction.Notethepop-upshowingthenumberthatwillbeplaced inthelastcelloftheselection.Releasingthebuttonatthispointwillresultintheentries runningfrom0to10inunitincrements. InParenthesis:AutofillofNonnumericSequences Theautofillfunctionisquiteintelligentandwillrecognizedates,daysandsomeother normalsequences.Ifyouenteraseriesoftextentries,theautofillwillfilltherangewith thesametextinthesameorder.
BulkFormatting TheformattingofthecellsincolumnBisnotfixed,sothenumberofdigitschangesand theappearanceisunappealingaswellasphilosophicallyincorrectsincethedigitalammeter thatwewillbeusingreportsthecurrentto3decimalplaces.Wecanbulkformatthisaswell. Clickonthe“B”columnselectionbuttonandthewholecolumnisselected.Nowrightclick onittobringupsomeoptions(actuallywecouldachievethesamethingbysimplyrightclickingonthe“B”columnselectionbutton).SelecttheFormatCellsoptionandthenthe Numbertab.Inthescroll-downmenu,clickonNumberandsetitto3decimalplacesand 7
ExcelbyExample clickonOK.Iknowthat,dependingontheaccuracyofthemeter,weshouldn’tplacetoomuch trustinthelastdigit,butthatisanotherissue.Eventhoughthecolumnheadingisintext,Excel issmartenoughtoleaveitsformattingalone,modifyingonlythenumericalentries. Ifacolumnistoonarrowtodisplayanumberintheselectedformat,Excelresortstodisplayingthesymbol“#####.”Toseethiseffect,movethejoinofcolumnsBandCsothatB becomestoonarrowtodisplaythefullnumber.Resizethecolumnbydouble-clickingthe columnjoin. Wewillbemeasuringtheinputvoltageonadigitalvoltmeterwith3decimalplacesaswell, soformatcolumnAto3decimalplacesasbefore. InParenthesis:MultipleSelections ItispossibletoselectmanygroupsofcellsforbulkactionsusingstandardWindowstechniquesbyusingtheCtrlandShiftkeysinconjunctionwiththemouseblockselection.
Formulas Inordertocalculatethetheoreticalcurrentoutputforagiveninputvoltage,Iamgoingto breakthecalculationinstages.Aswithallprogramming,itispossibletoembedcalculationswithincalculationsanditquicklyconfusesthings.Maintainingembeddedcalculations (althoughprovidingjobsecurity)canbetroublesome.Forinstance,tryfiguringoutwhat =IF((DCOUNT(AL7:AX31,1,AX33:AX34)>0),DAVERAGE(AL7:AX31,1,AX33:AX34),””) refersto,especiallyfouryearsafteryouhavewrittenit. Themodelwearedevelopingisasimpleexample,andseveralofthestepscouldeasilybe compressed,butthiswillallowmetheopportunitytodemonstratesometechniquestoimprovereadabilityandreliability. Thethirdcolumnwasentitled“Proportion,”andthiscalculationwillresultintheproportionofthemeasuredinputtothefullscale.Inotherwords,aninputof3voltsonaspanof 10volts(0to10)wouldgiveanumberof3/10.Sothecalculationwouldbe:
(Vin–Vmin)/(Vmax–Vmin)
whereVmincorrespondstotheminimuminputvoltageof0V,andVmaxtothemaximuminput voltage,10V. Toenterthisintheworksheet,clickoncellC6.Nowenterthefollowing:
=A6/A26
The“=”signmustbethere(ora“+”)toindicatethatitisaformula.A6istheinputvoltage inthiscolumn,andA16containsVmax.Noticehowthisappearsintheformulabaratthetop
8
Example1:Voltage-to-CurrentConverter oftheworksheetandinthecell,untilwepress(orofcourse,thedirectionarrows ortheTabkey).Thecellshowstheresultofthecalculation.Whenweclickonthecell,the formulawillappearagainintheformulabar.Figure1-7showswherewe’reat.
Figure1-7:ResultofformulacalculationincellC6,andtheformulausedinthecalculation appearsintheformulabar.
CopyingFormulas Wecouldnowenterthisformulaforeverycellinthecolumn,butofcourseitissimple enoughtocopyandpaste.ClickoncellC6andcopytotheclipboardwithstandardWindowstechniquessuchas+.NowclickoncellC7andpaste.Ignoretheerror thatappearsforthemomentandclickonC7tochecktheformulaintheformulabar:
=A7/A17
ExcelhasmadetherelativetranslationforthecellandthisisveryhandyexceptthatA17 doesnotcontainVmax. InParenthesis:AddingColumns/Rows Itisaneasymattertoinsertacolumnorarow.SimplyusethemenufunctionInsert |Columnandeverythingwillmovetotherightbyonecolumn.Insertingarowisvery similar. All the relative addresses and absolute addresses are all maintained without missingabeat. 9
ExcelbyExample InParenthesis:DeletingColumns/Rows/Cells Thedeletecellsfunctionisverysimilartoaddingacolumn/row,exceptwegothrough theEdit|Deletemenuandthendecidewhetherweneedtodeleteacolumnoracell andwhattheresultwillbe.Ofcourse,ifyoudeleteanentitythatisbeingreferenced elsewhere,Excelwillreportaproblem.Fortunately,thereisalwaystheUndobutton. Dependingonhowacellisdeletedinfluencestheresidualeffectonthecell.Ifweselect thecellandpressDeleteorBackspace,thecontentsaregone,buttheformattingremains.Togetridoftheformatting,weusethemenuaction:Edit|Clear|Formats.To clearboth,usethemenuaction:Edit|Clear|All.
RelativeandAbsoluteReferences Obviously,weneedsometechniquetoreferenceaparticularcellwithoutallowingforthe automaticadjustment.Simplyenteringthecellcoordinatesisknownasrelativereferencing. Inordertomakeanabsolutereference,usetheprefix“$”tothecolumnortherowidentifier, orboth.Theabilitytocreateanabsolutereferenceinonedimensiononlycanprovevery handy. Double-clickoncellC7toedittheformulainthecellorclickontheformulabartoeditit there.Modifytheformulatoread:
=A7/A$16
The“$”symbolonlyreferencesthelinessincethereisnocopyingacrossthecolumnsyet. Wecouldhaveusedthefollowingformattofixthechangesineitherdimension:
=A7/$A$16
TerminatetheentryandthencopycellC7totheclipboard.BlocktherangeC8toC16,by clickingontheformeranddraggingtothelatter,thenpaste.Figure1-8shouldbetheresult. Clickingonanyoneoftheentriesinthecolumnwillshowthatonlythefirstcellreference isrelative.Thenumberslookreasonable,butnotformatted.Iamnotgoingtobotherdoing thatatthemoment.Thisisatransitionalcalculationandwillbehiddenlater. ThenextstageofthecalculationistotakethenumberfromeachcellintheProportion columnandmultiplybytherangeoftheoutput,16mAandaddtheoffsetof4mA.Clickon cellD6andenterthefollowing:
=(c6*16)+4
Itshouldresultinacalculatedvalueof4.NowcopythiscelltotherangeD7toD16.The entryinD16shouldbe20correspondingtothetopendoftheoutputcurrentrange.Format thecolumnfor3decimalplaces.Figure1-9istheresult.
10
Example1:Voltage-to-CurrentConverter
Figure1-8:Theresultofaformula(includingabsoluteandrelativeaddressing)copied toablockofcells.
Figure1-9:Theoreticalcurrentcalculatedfromamathematicaloperationonthecell inthepreviouscolumn. 11
ExcelbyExample Thecalculationoftheerrorofthemeasuredoutputcomparedtothetheoreticaloutputis simple,subtractingthemeasuredvaluefromthetheoreticalvalue.ClickoncellE6andenter theformula:
=d6-b6
andcopythistotheothercellsE7–E16. Thedefinitionoflinearityisnotabsolute.Generally,itisgivenasapercentagebasedoncalculationoftheerrordividedbythefullscalevalue,althoughon4–20mA,itcouldbeargued thatthemaximumrangeisonly16mA.Optingforformerdefinition,weenter:
=E6/FullScale
incellF6.ThisisalsocopiedtotherangeF7toF16. Thereisanalternativemethodtofillablockofcells.Toseeadescriptionofthefeature,see “InParenthesis:FillBox”inExample16. Enterthetext“FullScaleValue”incellA3.InB3,enterthevalue“20”.Itwilltakethe3 decimalplaceformatalreadyexistingforthecolumn.InordertofitthetextinA3intothe cell,anotheroptionispossible.Right-clickonthecell,selectFormatCellsandclickonthe Alignmenttab.IntheTextControlsection,checktheShrinktoFitoption,followedbythe OKbutton.
NamingCells AnyreferencetotheFullScaleValuewouldbeanabsolutereferencetoB3,thatis$B$3.On anycomplexworksheet,tryingtoskipbackandforthtryingtofigureoutwhat$B$3refers toisexceedinglyinefficient.Excelallowsustoprovideacontextualnameforeitheracellor agroupofcells.Itcanbedoneintwoways.Thefirstismoregeneric,andishelpfulwhere therearemultiplepagesormultipleworkbooks.Itisaccessiblethroughthemenusequence:
Insert|Name|Define
Itispossibletonavigatetothecellorrangeofcellswithinthedialog,althoughitdoesconvenientlystartatthecurrentcellselection.Wewillneedthisdialogtoremoveaname. Ifindthesecondmethodquickerforsimpleapplications.Simplyselectthecell(orgroup ofcells)ontheworksheet.Inthecurrentexample,thiswouldbecellB3.Thenclickinthe Nameboxatthetopleft-handcornerofthespreadsheet(seeFigure1-3)justtotheleft oftheformulabar.Enterthenameofthecellhere,FullScale,withtheresultappearingin Figure1-10.
12
Example1:Voltage-to-CurrentConverter
Figure1-10:NamingcellB3to“FullScale”. InParenthesis:CellNames Youneedtoexercisealittlecautioninnamingcellsusingthenameboxbecausethename boxalsoservesasaGoTobox.Clickingontheboxandenteringavalidcellcoordinate willresultintheaddressedcellbeingselectedandnotthecurrentcellbeingrenamed. Youwillseethislaterwhentryingtonameacellforaresistor,forexample,R17.There areahugenumberofpossiblecolumnsinExcel.TheyrangefromAthroughtoZ,AA onpastAZfollowedbyBAandonuntilyougettocolumnIV.Onapositivenote,the drop-downcontrolatthesideshowsallthenamedcellsandclickingonthatwilltake youtoyourdestinationratherquickly.Therearerulesfornamingcellsasyouwould expect.Thenamecannotstartwithanumber,norcanitincludespacesorotherspecial characters.Referencetothecellnameisnotcasesensitive. Usingacellnameofcourseisanabsolutereference. 13
ExcelbyExample InParenthesis:WorksheetNavigation Whileweareonthesubjectofmovingaroundtheworkbook,asidefromtheNamebox, itispossibletogotoacelllocationusingtheEdit|GoTomenusequenceor+ willbringupthesamedialog. Ctrlplusthedirectionarrows,HomeorEnd,resultingrandmovements.Theyaresometimescontextual,dependingonwhereyouareinaworksheet.Forinstance,ifyouhave cellA1selectedinthespreadsheetwearecurrentlyworkinginandyoupress+ youwillarriveatcellIV1.Ifyouareinthebodyoftheworksheet,cellC8say,the samekeycombinationwilltakeyoutothelastvalidcolumnofdata.Repeatingthekey combinationwillthentakeyoutoIV8. +returnsyoutocellA1. Anyreferencetothecellcansimplyusethenameasahandle.ClickoncellF6.Enterthe formula:
=(e6/fullscale)
Thatistheerrordividedbythefullscalerange.NowcopythiscellfromF7toF16andthen formatcolumnFasapercentagetotwodecimalplacesbyright-clickingonthecolumnFselectionbutton,choosingFormatandselectingthePercentageentryundertheNumbertab. ThereferencetoFullScaleisanabsolutereference.Figure1-11shouldbetheresult.
Figure1-11:Fullmodel. 14
Example1:Voltage-to-CurrentConverter
HidingCells AsIpromisedearlier,columnsCandEareintermediatestepsandsodonotneedtobe visible.ColumnselectbothbyclickingoncolumnselectbuttonCandthenpressingthe keyandclickingoncolumnselectbuttonE.Thenright-clickoneitherandselect theHideoption.SeeFigure1-12.
Figure1-12:Theprocessofhidingcells. Thecolumnsnowdisappear,althoughtheirpresenceisdenotedbythediscontinuityofthe columnlettering.Itisalsoindicatedbythethickeningofthedividerlineonthecolumn buttons.Toretrievethecolumn,selectthecolumnsoneithersideofthe“divide.”Simply clickontheonecolumnadjacenttothesplitanddragtotheadjacentcolumnontheother side.Right-clickandselectUnhide.Multipleselectionswiththekeywillnotwork successfullytounhidethehiddencolumn.
Borders Inordertoenhancethetabularappearance,wemustaddlinesaroundtheentries.Blockthe areawherethisformattingistobedoneasshowninFigure1-13.
15
ExcelbyExample
Figure1-13:Preparingtoaddborders. Wecandothisinanumberofways.Inthissimplecase,itispossibletoclickanddragfrom cellA6toF16.Whereatableisbigger,thiscansometimesbeinconvenient,because,asyou willdiscover,draggingtheselectionoveralargenumberofcolumnsorrowsresultsinthem whizzingpast.Itbecomesdifficulttogettoexactlywherewewanttogo. ClickincellA6andthennavigateusingthecontrolbarstillthelastcellisvisible.Pressthe Shiftkeyandclickinthelastright-handcellofthetable.Thistoo,canbeinconvenientif thetableislargesincenavigatingtothelastcellcanlosetheinitialcellselection.Hereisa reallyquickway.ClickincellA6.Usethekeycombination++and ourselectionisdone. Backtothejobinhand.Withintheselection,right-clickandselectFormatCellsandthe Bordertab.Forthecurrentselection,thedialogallowsustoselectlinewidths,whichsideto havealine,hatchingandcrosshatchingandmanyotheroptions.Notethatwecoulddothis foranygroupofcellsstartingfromanindividualone.Whilewearehere,noticetheother taboptionsthatallowbackgroundcolortobemodified,cellalignment,textfontsandso on.ReturntotheBordertabandclickfirstonthelinestyle—Iamusingthelightestweight (bottomleft-handcorner).ThenclickonOutlineandInsideandtheOK,andthemodelis readyforoperation. 16
Example1:Voltage-to-CurrentConverter
BellsandWhistles Whilewearehere,whydon’tweaddsomefeatures?Mostofthetimeweonlydowhatis necessarytocompleteajob,butIwanttowhetyourappetiteforsomeofthesubjectsthatwe willcoverlater.
ConditionalIFandAbsoluteValue Let’ssettheupperlimitoflinearityperformanceto±1%.Insteadofscanningeachresult, whydon’tweaddamarkerontherightofthetabletoindicatewhenthereadingisoutof limits? Sincetheerrorcouldbepositiveornegative,weneedtolookattheabsolutevalue.The ABSfunctionworksexactlyasifweareworkinginacomputerprogramminglanguage (whichisofcoursewhatwearedoing)returningtheabsolutevalueofthenumberitis handedasaparameter.TheIFstatementisperhapsalittlemorecrypticthantheIF,THEN, ELSEconstructionofahigh-levelprogrammingstatement,butthat’swhatitdoes.Ithas threeparametersseparatedbycommas.Thefirstparameteristhelogicaltest,thesecondis thevalueofthecellifthetestistrue,thethirdifthevalueofthecellifthetestisnegative. ClickoncellF3andaddthetext“MaximumTolerance.”IncellH3,addthevalue1and namethecellMaximumTolerance.Formatthecellforpercentage.NowclickoncellG6and entertheformula:
=IF(ABS(F6>MaximumTolerance),”