You are on page 1of 238
GMa uee as) Rese) mmm onisanrnercrn texas your guide, you can significantly enhance Microsoft Excel capabilti ns needed to sole a varity of chemical biochemical, physial engineering bislogeal ond problems. The tert begins with two chapters that introduce you to Eaves Visea aerc for 2s (VBA) programming language which allows you to expand Excel capabilites, althoudh Following the author’ step-by-step instructions, here ‘ew ofthe calculations you lea to perform: rAsheet functions to work with matrices 1 solve systems of simultaneous equations ftential equations and partial differential equations linear end non-linear egresion dom numbers and the Monte Carl methac s loaded with examples ranging rom very basic to highly sophisticated solutions. More than er problems help you test and put your knowledge to practice solving real-world rs and explanatory notes for most of the problems are provided in an append OM that accompanist provides several useful festures: spreadsheets, charts and VBA code needed to performn the examples from the text 15 to most of the end-of-chapter problems sm workbook with more than twenty custom functions itis suitable for both undergraduate engineering wil find tha his guide saves alculatons with one Familiar spreadsheet E. JOSEPH BILLO, 2 former associate pro’ College is the author of Excel f (ley). He has | Engineers” and “Exc! has presented to thousands of scient Europe for organizations such as The Am Institute, Procter & Gamble, Shell and Texaco, ighout the United States, Canada, and Chemical Society, the National Cancer LEY- (ERSCIENCE eyo, Biblotecs Insttuctonal TT 70942 @WILE' UL WLR IZ AG ror SCIENTISTS ano ENGINEERS NUMERICAL METHODS ach genraton hast unique ee and asians. When Charles Wie fist ‘opened hs smal pring shop i lowee Matha in 107, we generation of boundless potesalserching fran ientiy. And we wie ther, blpng fo define «new American literary tation. Over half’ contary ter in th mids ofthe Seood Industrial Revlon, it as & generation fected on bing the fare. Once agin, we were thee, suplyng the erica sient tele and gineering Knowiedge that helped fame the world, Thaoughout the 20 (Cetus, and into the nsw millensor,mations began to seach ot beyond tee om borders and new international commusity wat torn Wiley was there, expanding it operations around the ward to enables global exchange of iss, pains, ne know-how. For 200 years, Wiley tas been an itegeal part of each genecatons jours, enabling te ow of information and undetaning nessa to et he de sof fl their apratons. Toy, bold new technologie ae ngng the way ‘Iv and lean. Wiley wil be tee, providag you the must-have knowledge oueed to imagine ne sold, ae pose, nd new epportnites, (neon come and go, bt you can always cous on Wiley to roid you the “nowedge you nee, when and where ou sedi Excel® for Scientists and Engineers Numerical Methods E. Joseph Billo 1807E ewuev: 2007 WILEY-INTERSCIENCE Adon iy 8 Sone Pubcon Copii 0207 ty on Wey & Sa a A ei, hy a Wey Se, i, Hao, New Pte muon fe ost i polin maybe podiatrist cb lest sesh joussping orang sang ove ese oscar Scone ‘Tid Suis Coi a, wit ie rw one ee ser ese ech [meter e exon paca Cpr Caan: Coane 22 ReormnouDeoe Deen MA {9825 07875880 f(T) 5-470, be es awe apices te Paine pain ‘nidbe ated e Pisin Depa sey & Sale tReet Hate NON G01) 74, G1 Ts rene aw coos nf LnktnyDetiner of Wary: Wile buses aurea ee prep is Denk hy a naan wt pee cognac ok sce cn ingen cy ans Reape pope Ne ee ‘leet yi pene wts oer mas Te vst coger roasndneoeoeyo SHANE pret eens font he pn hp Seep wcbecnnge a nee era issn on ou te pra eve fr ech gp ect nae Coe ‘Dep wih nt Ss) 9D297, use Uta Se 317) 12 97 eT) TOAD ‘Wea pinion ina ayo ac ot Some cae ht spent ay lien lesz ft Friant Wy pss tar we tes or wy ‘We Bm Lag Rn 2 ace rer of Come Calpine Paitin Date mx srsogisenta woareses Detailed Table of Conte. Preface Acknowledgment, About the Author.. Summary of Contents ‘Chapter 1 Inrodcing Visual Basic for Appliations an (Chapter? Fundamentals of Programming with VBA. ‘Chapter3 Worksheet Functions for Working with Matrices Chapter Number Series (Chapter 5 Interpolation Chapter6 Differentiation (Chapter? Integration Chapter 8 Roots of Equations ve Chapter9 Systems of Simultaneous BQUIIONS ween Chapter 10 Numerical Integration of Ordinary Differential Equations Part: Initial Conditions en CChaptee 11 Numerical Ftegration af Ordinary Ditfecenial Equations Part: Boundary Conditions e Chapter 12 Partial Differential Equations enn a (Chapter 13. Linear Regression and Curve Fit ecnnnon ‘Chapter 14 Nonlinear Regression Using the Solver (Chapter 15 Random Numbers andthe Monte Carlo Method APPENDICES. Appendix} Selected VBA Keyword ono eeets ‘Appendix? Shortut Keys for VBA 387 Appendix3 Custom Functions Help File connie 389 ‘Appendix 4 Some Equations for Curve Fit nn 409 ‘Appendix 5 Enginoering and Other Functions — Appendix ACT Codes nn = = 427 Appendix 7 BIbIOgEapBY Ann ns es) Appendix 8 Answers and Comments for End-of Chapter Problems on 431 INDEX .. —— 4a Preface Acknowledgment. About the Author. * Chapter Introducing Visual Basie for Applications ‘The Visual Basic Editer. Visual Basie Procedures. There Are Two Kinds of Macros. The Structure of Sub Procedure. ‘The Structure of «Function Procedure... Using the Recorder to Create a Sub Procedure. ‘The Personal Macro Wotkb00k enn ‘Running a Sub Procedure... ‘Assigning a Shorteut Key 7 @ Sub Procedure. Entering VBA Code ‘Creating a Simple Custom Function, 10 Using @ Function Macro... A Shortcut to Enter a Function, Some FAQS nn = 5 + Chapter2 Fundamentals of Programming with VBA 18 Components of Visual Basic Statements... 15 Operatars... a 16 Variables. Objects, Properties, and Methods Objects : Properties Using Properties, Functions. . Using Worksheet Functions with VBA. Some Useful Methods. Other Keywords BRERREBBES we xcet NUMERICAL METHODS, For ESC Me Loop Nested Loops ono Bil fom asprin io, VBA Deis ypes “The Vans Data Subroines enna Scoping Subroutine. BA Code for Conmand Macros. Obj and Colton of Obi “Objects That Are Realy operon’ You Defoe Your Ovn Sc Matos Some Usefil atiod Two Ways to Specify Argunens of ties Arguments with orihut aendees MalizgaRafrnce to 2 Calor a Range ‘Aeierence tothe Active Cll or Slcicd Range. ‘A Refene‘9 a Cal Ott the Active al efectos Using te Union or nsec Meio Eels ores ters alors Getig Values Soma Worksheet Seni Vass to = Wokshet Ioatng with tbe Use nee Megbox Retina Valo into Visual Baste Ana Dinessonng an Le ei fb Ary Varo Spi Wk Ay asinensinal rays Du te Vite pax Ay ening the Sz ofan ray see Dynami Arrays Preserving Vas in Bye Aaya Working with Arrays a Sub roceducs essing Values Som Wola o VBA Module ‘Rene Specifi ina SubProcedare Can Be Used sen Ais Some Werke Functions Used Winn VBA Crestean Anay Automata Some Woraest Funeons Used Within VBA ‘reatan Array Aufonatially. ‘An Array of Object Vata. sonmets_ lg ‘Working with Arrays in Sub Procedures: Passing Values ffem a VBA Module toa Worksheet... ‘Qu Dimensional Anny signed to Workbe! Range, (Can Cause Problems... (Custom Functions nnn ‘Specifying the Data Type of an Argumen. Specifying the Data Type Returned by a Function Procedure, ‘Returning an Err Value from a Function Proceduewiw.sn ‘A Custom Function that Takes an Optional Argument ssn Arrays in Function Procedures. ‘A Range Passed to a Function Procedure Can Be Used as an Arey. Passing an Indefinite Number of Arguments Using the Paramvray KeyWOtd nen Retuming an Array of Values asa Result (Creating Add-In Function Macros . : How to Create an Add-In Macro ‘Testing and Debugeing. ‘racing Exeoution.- : a ‘Adding a Breakpoint.. Examining the Values of Variables While in Bresk Mods. ‘Examining the Values of Variables During Execution... CChaptor3. Worluhect Functions for Working with Matrices ‘Arrays, Matrices and Detemminaats Some Types of Matrices... ‘An Introduction to Matrix Mathematics. Excel's Builtin Matrix Functions Some Additional Matrix Functions Problems. : Chapter 4 Number Seriés [Bvalustng Series Formal... Using Array Constants to Create Series Formals Using the ROW Worksheet Function to Create Series Formulas The INDIRECT Worksheet Functon.. Using the INDIRECT Worksheet Function ‘vith the ROW Worksheet Function to Create Series Formulas n The Taylor Serie nes = ‘The Taylor Series: An Example. Problems. mn Chapter 5 Interpolation Obtaining Valves from a Table. Using Excels Lookup Functions to Obtain Values from a Fab Using VLOOKUP to Obtain Values from a Tabl Using the LOOKUP Function to Obtain Values from a Table... (Creating = Custom Lookup Formula to Obtain Valves ffom ¢ Table. Using Excel's Lookup Functions {to Obiain Values from 2 Two-Way Table. Interpolation... : Linear Interpolation ina Table by Mans of Worksheet Formulas 83 Linea Interpolation in a Table by Using the TREND Worksheet Function 85 Linear Interpolation in a Table by Means of a Custom Function uous 86 Cubic Interpolation 7 Cubic Interpolation in a Table by Using the TREND Workshect Function. 89 Linear Interpolation in a Two-Way Table ‘by Means of Worksheet Forms. (Cubic Intepolstion in a Two-Way Table by Means of Worksheet Formula, (Cubic Interpolation in a Two-Way Table by Means of a Custom Funetion.. Problems... Chapter Diferentiation 9 Fist and Second Derivatives of Data in 8 Table sen ‘Calculating First and Second Derivatives Using LINEST asa Fisting Function . Derivatives of a Worksheet Form un Derivatives of Worksheet Formula Cau VBA Function Procedure. First Derivative of a Workshost Formula Calculated aby Using the Finte-Difference Method... ‘The Newton Quotient. Derivative ofa Worksheet Formula Calelated by Using the Finite Difference Method. ‘First Derivative of Worksheet Formula Calculated by Using a VBA Sub Provedue Using the Finite-Difference Method. First Derivative of a Workshoot Formula Calculated by Using ‘a VBA Function Procedure Using the Finite Difference Method. Improving the VBA Function Procedure. ‘Second Derivative of a Worksheet Formula. : Concent Coie of forte Finite Difence Meted Problems. a) 09 110 Mt 12 vol S ay 120 “123 gonments lg Chapter 7 Integration 37 Are unde @ CU CCaloulating the Area under a Curve Defined by a Table of Dats Points bby Means of a VBA Fusetion Procedure, Integrating « Function. Integrating a Function Defined by a Workeheet Formula bby Means of a VBA Function Procedures Gaussian Quadrature. Integration with an Upper or Lower ini faint Diane Traveled Along a CVE Path nn Problems... Chapter Roots of Equations ‘A Graphical Method, ‘The Interval Halving or Bisection Method... ‘The Interval Method with Linear Interpolation (the Regula Fast Method)... soe SL ‘The Regula Fals! Method with Correction for Siow oerce 183 ‘The Newton-Raphson Method, aeatisg Using Goal Seek ann sl 56 ‘The Secant Method. 160 ‘The Newton-Raphson Method Using Circular Reference and eration 161 ANewton-Raphson Custom Function wenn vente 168 Bairstows Method to Find All Roots ofa Regular Polynomial 165 ing Valuos Other than Zeroes of a Function 174 ‘Using Goal Seek. to Find the Point of Intersection of TWo Curves .n174 ‘Using the Newton-Raphson Method. to Find the Poin of intersection of TW0 Lines ne ‘sng te Newion Rainn Method Find Malle Tntersections off Straight Line and & CUNE nn soul snl TS A Goal Seek Custom Function. 180, Problems... ae == 7185 Chapter Stems of Simultaneous Equations 18 Cramers Rule... so 190 Solving Simultancous Equations by Matrix Inversion en 19T Solving Simultaneous Equations by Gaussian Elimination... “19 ‘The Gauss-Jordan Method ee “196 Solving Linear Systems by Iteration. 200 ‘The Jacobi Method Implemented on a Worksheet ne 200 7634 si excen:nuvmucat mertions ‘The Gauss-Seidel Method Implemented on s Worksheet. ‘The Gauss-Seidel Method Implemented on a Worksheet Using Circular Reference. ‘A Custom Funetion Procedure forthe Gauss Seidel Method. Solving Nonlinear Systems by tration... ‘Newton's eration MethO9 nan Problems es ‘Chapter 10 Numerical Integration of Ordlaary Dierential Equations Part: Initial Conditions Solving a Single First-Order Differential Equation uler's Method. ‘The Fourth-Order : Fourth Order Runge-Kuta Method implemented ona Wako ‘Runge-Kutta Method Applied to a Differential Equation Involving Both x andy Fourth-Onder Runge-Kutta Custom Function fora Single Difterenial Equation with the Derivative Expression Coded inthe Procedure. Fourt-Onder Runge-Kutta Custom Function fora Single Dffereatil Equation with the Derivative Bresson Passed as an Argue mn ‘Systems of First Order Differential Equations. Fourth-Order Runge-Kutta Custom Function {for Systems ot Dtterental Equations. Predictor Corector Methods, ‘A Simple Predictr-Corrector ‘A Simple Predictor Corrector Method Uiilizing an Intentions Circular Reference... Bah One Diffie Eutons Problems... ‘Chapter 11 Numerical integration of Ordinary Dilleratial Eqwatons Part TE: Boundary Conditions ‘The Shooting Method ‘An Example: Deflection of Simply Supported Beam... Solving a Second-Order Ordinary Differential Equation by the Shooting Method and Euler's Method se... Solving a Second-Order Ordinary Differential Equation by the Shooting Method and the RK Method. FiniteDifference Methods... : Solving a Second-Order Ordinary Differential Eaton by the Finite Difference Method om, 203, ‘CONTENTS = — Another Example. - 258 ‘A Limitation onthe Finite-Difference Method. 261 Probiems.. —— 7 262 (Chapter 12 Partial Differential Equations 263 Ep, abot an Hypa alien Equation 269 lliptic Partial Differential Equation - 264 Solving Elipsic Partial Differential Equations Replacing Derivatives with Finite Differences, a ‘An Example: Temperature Distribution ina Heated Metal Plate 267 Parabolic Paral Differential Equations... ‘Solving Parabolic Partial Differential Equations: The Bl Method.270 ‘An Example: Heat Conduction in Brass Rod Solving Parabolic Partial Differential Equations: ‘The Crank: Nicholson of Implicit Metiod ‘An Example: Vapor Diffusion in a Tube, ‘Vapor Diffusion ina Tube Revisited ‘Vapor Diffusion ina Tube (Agaia) A CrankeNicholson Custom Function. ‘Vapor Diffusion in a Tube Solved by Using a Custom Function “3a Hyperbolic Paral Diffecental Equations. aga Solving Hyperbolic Partial Differential Equations Replacing Derivatives with Finite Differences, sen DBD ‘Example: Vision of Sui. Problems ear Regression. ‘Least Squares Fit toa Staight Line ‘Least Squares Fit toa Straight Line Using ‘SLOPE, INTERCEPT and RSQ... Multiple Linear Regression... Least Squares Fit to # Straight Line Using LINEST. ‘Maliple Linear Regression Using LINEST - Handing Noncontiguous Ranges of known ia LINEST. ALINEST Shorteut LINESTs Regression S Linear Regression Using Trending. Limitations of Treeline. Importing Trendline Coefficients into a Srondint by Using Worksheet Formulas... Using the Regression Too! in Analysis Tools. imitations ofthe Regression Tool xiv EXCEL: NUMERICAL METHODS ro f boing the Trendline Equation fom a Char into a Worksheet, Chapter 14 Nonlinear Regression Using the Solver Non Lest Sars Cae ting Introducing the Solver. How the Solver Works. Loading the Solver Add-in ‘Why Use the Solver for Noalinear Regression? Nonlinear Regression Using the Solver: An Example Some Notes on Using the Solver. Some Notes on the Solver Parameters ‘When to Use Mental Sealing... Sttistos of Nelinear Regression ‘The Solver Statistics Matto wn ono Whe Ug ited Forms of Nonlinear Eat ‘Chapter 15 Random Numbers andthe Mont Carlo Method Random Numbers in EX2el. ven Using Random Numbers in Exel. ‘Adding "Noise" toa Signal Generate ty a Formule. Selestng tems Randomly from a Lit. Monte Ca ategraon ‘ee ofan repr Polygon. Problems. - APPENDICES ‘Appendix 1 Selected VBA Keywords . Appendix2 Shortcut Keys f0f VBA. wenn Appendix3 Custom Functions Help File... Appendix Some Equations far Curve Fitting Appendix Enginesring and Other Funetions ‘Appendix6 ASCII Codes Appendix? Bibliography... Appendix 8 Answers and Comments for End-of Chapter Drablems INDEX Preface ‘The solutions to mathematical problems in science and engineering can be obtained by using either analytical or numerical methods. Analytical (or direst) ‘methods involve the use of closed-form equations to obtain an exact solution, in a nonrepetitive fashion; obtaining the roots of a quadratic equation by application of the quadratic formula isan example of an analytical solution. Numerical (or, indiest) methods involve the use of an algorithm to obtain an approximate solution; results of a high level of accuracy can usually be obtained by applying the algorithm ina series of successive approximations. As the complexity of a scientific problem increases, it may no longer be possible to obtain an exact mathematical expression as a solution tothe problem, Such problems can usually be solved by numerical methods. The Objective of This Book Numerical methods require extensive calculston, which is easly accomplished using today’s desktop computers. A number of books have been ‘writen ia which aumarical methods ae implemected. using a speific Programming language, such as FORTRAN or Cr. Most. scientists and Sngioers received some taining in computer programming in their college ys, but they (or their computer) may no longer have the capability twit or ran progams ia, for example, FORTRAN. This book shows how to implement fumercal methods using Microsof Exca®, the mast widely used spreadsheet Software package. Excel? provides at last tree ways for the scientist ot engineer apply numerical methods to problems: + by implementing the methods ona worksheet, sing worksheet formulas + by using the builtin tools tha are provided within Exoel + by writing programs, sometimes loosely refered to as metros, in Excel ‘Visual Basic for Applications (VBA) programming language. Allof these approaches ae illustrated in this bok ‘This is a book about numerical methods. Thave emphasized the methods and have kept the mathematical theory behind the methods to a minimum. In many cases, formulas are introduced with litle or no description ofthe underlying theory. (Cassume thatthe eader will be familiar with linear interpolation, simple calculus, regessioa, ete.) Other topics, such as cubic interpolation, methods for solving differential equations, and sooo, ae covered in more detail, and e few pl ct ners METHODS ‘opie, such as Bairstow’s method for obtaining the roots of «regular polynomial, ae discussed in detail In this book Ihave provided a wide range of Excel solutions to problems. In ‘many cases I provide a series of examples that progress from a very simple implementation of she problem (useful for understanding. the logic and construction of te spreadsheet or VBA code) to a more sophisticated one that s ‘more goneral. Some of the VBA macros are simple “stating point” and T encourage the reader to modify thems; others are (ora least | intended them t0 be) "finished products" that Ihope users ean employ on areguler basis Nearly 100% of the materi in this book spplies equally to the PC or Macintosh versions of Excel. In a few cases I have pointed out the different [keystrokes requires forthe Macintosh version, A Note About Visual Basic Programming ‘Visual Basic for Applications, or VBA, is "dileet” of Microsofts Visual Basic programming language. VBA has Keywords that ellow the programmer to ‘work with Excel's Workbooks, worksheets, ceils, chars ete. 1 expect that although many readers of this book will be proficient VBA programmers, others may not be familiar with VBA but would ike to lear to rogram in VBA. ‘The first two chapters of this book provide an introduction to ‘VBA programming — not enough to become proficient, but enough to understand and pethaps modify the VRA code in this book. For readero who haven faniliarty With VBA, and who do not wish to lear it, do not despair. Much of the book (perhaps 50%) doesnot involve VB. In addition, you ean sil use the ‘VBA custom functions that have been provided, Appendix 1 provides a lst of VBA keywords that are used inthis book. The sppencix provides 2 desripton of the keyword, its syntax, one of more examples ofits use, and reference to related keywords. The information is similar to what can be found in Exeels On-Line Help, but readers may find it helpful at those times when they ae reading the book without simultaneous access toa PC. A Note About Typographic Conventions ‘The tppographic conventions used in this book are the following: Menu Commands. Excel's menu commands appear in bold, as in the following examples: “choose Add Trendline.. fom the Chart menu..." of "Insert—Fanetion..." PREECE ng Excel's Worksheet Functions and Their Arguments. Worksheet functions are in Arial font; the arguments sre italicized. Following Microsofts convention, required arguments are in bold font, while optional erfurments are in nonbold, a in the following \VLOOKUPUookup_value,table_array,column_index_num, range_ookue) ‘The syntax of custom functions fellows the same convention Excel Formulas. Excel formulas usually appear in a separate line, for example, SI TFACT(1)+ VFACTI2}+ FACTO} UFACTIA}IFACTIS) [Named ranges used in formulas or inthe text are not italien, to distinguish thom from Excel ergumest name, for example, ~VLOOKUP(Temp, Table MATCH Percent P_Row4}+,1) VBA Procedures. Visual Basic code is in Arial font, Complete VBA procedures are displayed ina box, asin the following. For ease in understanding the code, VBA keywords ae in bold. vate Futon Dan) "User codes the axrasson fr the derivative ere Dent sOexe2 9 10°x-5 Problems and Solutions ‘There are over 100 end-of-chapter problems. Spreadsheet solutions for the problems ste on the CD-ROM that accompanies this book. Answers and explanatory notes for mos af the problems are provided in Appendix 8 The Contents of the CD ‘The CD-ROM that accompanies this book contains a number of folders oF other documents + an "Examples" folder. The Examples folder containg a folder for each chapter, eg, 'Ch. 05 (Interpolation) Examples’ The examples folder for each chapter contains all of the examples discussed in that chapter: spreadsheets, charts and VBA. code, The location of the Excel file pertinent to each example is specified in the chapter text, usually in the caption of a gore, e.g, ‘Figure SS, Using VLCOKUP and MATCH oobi a vas fm ceo ler 'Chape OS Inepaitan’ wortooeInuelason sb Vissiy) sic suericaL Memions. "Problems folder. The Problems folder contains folder for each chapter, 8» ‘Ch. 06 (Diseesition) problems’ “The problems folder for each hapter contains solutions to (almost all of the endof-chapter problems in ‘that chapter. VBA code required forthe solution of any of the problems is provided in each workbook that requies if; the VBA code willbe identical to ‘he code found inthe Examples folder + en Excel workbook, "Numerical Methods Toolbox," that contains ll ofthe important eustom fonctions inthis book. copy of "Numerical Methods Toolbox” saved as an Add-In workbook (an xa fil). IFyou open this Add-In, the custom functions willbe availabe for ‘sein any Excel workbook. * Two Face workbook containing the ulites Solver Statistics and Trendline toCell Comments Are Welcomed J welcome comments and suggestions from readers. I can be contacted at ‘mumerial_mettods.billo@verizon net, E. Joseph Billo PREEAGE ag Acknowledgments Dr. Richard N. Fell, Department of Physics, Brandeis University, Weltham, MA; Prof. Michele Mandrioli, Department of Chemisty and Biochemistry, University of Massachusets-Dartmouth, North Dartmouth, MA; and Prof. Christopher King, Department of Chemisty, Troy University, Troy, AL, who ‘ead the complete manuscript and provide valuable comments and corrections, Prof. Lev Zompa, University of Massachusett- Boston, and Dr, Peter Gans, Protonie Software, for UV-vis spectral dat. ‘Edwin Strver and Nicole Stedel, Frontline Systems Inc, for information about the inner workings ofthe Solver. ‘The Dow Chemical Company for permission to use tables of physical properties of heat transfer Muids About the Author E. Joseph Billo retired in 2006 as Associate Professor of Chemisty at Boston. College, Chestnut Hil, Massachusetts. He i the author of Excel for Chemists: Comprehensive Guide, 2nd edition, Wiley-VCH, New York, 2001. He has presented the 2-day short courses "Advanced Excel for Scientists and Engineers" and "Excel Visual Basic Macros for Scientists end Engineers” to over 2000 Sclentnes at corporate clients i the United States, Cauada sud Earoye Chapter 1 Introducing Visual Basic for Applications In addition to Excel extensive list of worksheet functions and aay of calcuiation tools for scientific and engineering calculations, Excel contains programming language that allows users to create procedures, sometimes referred to as macros, that can perform even more advanced calculations or that can automate repetitive calculations, Excel's first programming language, Excel 4 Macro Language (LM) was introduced with version 4 of Excel. It was a rather eambersome language, but it 4d provide most ofthe capabilities of a programming language, suchas looping, branching and so on. ‘This frst programming language was quickly superseded by Exeels current programming language, Visual Basie fer Applications, introduced with version 5 of Excel. Visual Basic for Applications, o VBA, is “ialest” of Microsofts Visual Basic programming language, a dislect that hes keywords to allow the programmer to Work with Excel's workbooks, worksheets, sells, charts, ete. At the same time, Microsoft introduced a version of Visual Basie for Word; it was called WordBasic and had keywords for characte, paragraphs, line breaks, ec. But even st the beginning, Microsofts sated mention was to have one version of Visual Basic that could work with all its applications: Excel, Word, Access and PowerPoint. Each version of Microsoft Office has moved cioser to this goal The Visual Basic Editor To create VBA code, or to examine existing code, you will need to use the ‘Visual Basic Editor. To access the Visual Basio itor, choose Macro from the ‘Tools menu and then Visual Basic Fitor from te subment The Visual Basic Editor sereen usually contains thee important windows: the Project Explorer window, the Properties window and the Code window, as shown in Figure I-L. (What you see may not look exactly like thi.) ‘The Code window displays the active module sheet; each module sheet can contain one or several VBA procedures. Ifthe workbook you are using does not Figure 11, The Visual Basic Editor window. tain ay mi heats, the Code window wil be cut. To Insert a module shes, choose Mode from the Insert mens. folder icon labled Moles Wil be inserted if you eli on this fon, the module sheet Module will bedisplyed. Excal gives these module shests the defast names Mocuct, Module? and soon Use the Project window to selet » paiculr code module fom all the availible modules in open workbooks. "These are displayed io the Project ‘window (Figure 1-2), which is usally located on the left side ofthe sersn’ It the Project window is not visible, choose Project Explorer ffom the View tment, or click on the Project Explorer toolbuton So display it The Projet Explorer tolbuton isthe ith button from the right inthe VBA toolbar. 1a the Project Explocer window you will see a hierarchy tee with «node for cach open workbook. In the exanpie illustrated in Figure 1-2, x new workbook, Boot, hs been opened. The node for Gookt bas anode (a folder ison) labeled ‘oso Exel Object click on the folder icon to delay the nods it contain an icon for each sheet in the workbook and a0 edition! one labeled ‘isWabook. you double-click on anyone ofthese nodes you will display the ade shet for it. These code shots ae for special types of procedures alled sumac procedures or event-handerprocedares, whith are not covered nts Figure 1-2. The VBE Proje: Explorer window. book. Do not use any ofthese sheets to creste the VBA. procedures described in this book. The hierarchy tee in Figure 1-2 also shows a Modules folder, containing one module sheet, Module. ‘The Properties window wil be disused later. Right now, you ean press the ‘Close button to get rid of if you wish Figare 1-3. The Proper window. —_EXCEL:NUMERICAL METHODS ual Basic Procedures VBA macros are usualy refered to as procedures. ‘They are writen or ‘weordel on & module sheet. A single module sheet can contain many procedures, ‘There Are Two Kinds of Macros There are two different kinds of procedures: Sub procedures, called omtmand masros in the older XLM macro language, and Funeton procedures called function macros in the XLM macro language and offen refered te at ‘custom funetions or user-defined functions. “Although these procedures can use many ofthe sume set of VBA commands, {hey are distinctly diferent. Sub procedures ean automate any Excel action, Lec xazaple, a Sub procedure might be used to create a report by opening new IRorkshect copying selec ranges of eels fom ether worksheets and pasty them into the new worksheet, fonmiting the dala in the new worksheet ‘roving headings, and printing the now worksheet. Sub procedures are usvaly “tun" by selecting Macro from the Tools menu. They can alo be run by means of an assigned shortcut key, by being called from another procedure, ar it several other ways. Function procedures augment Excel's library of builtin fanetions by adding werdefined ‘functions. A custom or user-defined function is used ine ‘Worksheet in the same way asa built-in function like, for example, Excel's Sone function it i entered ina formula in a worksheet Gell, porfurs & cleat fand returns a result tothe cell in which iti located. For example, a custo, fimetion named Flot could be used to convert Fahreahelt temperatincs ty Celsius. stom funetions cant incorporate any of VBA's “action” commands. No ‘experienced user of Excel would try to use the SORT function in a worksheet ‘lltocaleulte the square root ofa number and also open & new workbook ead insert the esul there; eustom funetions are no different, However, both kinds of macro can incorporate dession-mekiag, branching, 'ooping, subroutine and many other aspects of programming language, The Structure of a Sub Procedure ‘The structure of a Sub procedure is shove in Figure 1-4. The procedure begins with the Keyword Sub and ends with End Sub, It has a ProcedueNewe, ¢ Unique identifier that you assign to it. The name should indicate the purpose of the fimetion. “The name can be long, since after you type it once you will ‘Probably not have to type it again. Sub procedure has the posiiliy of wing ‘one oF more arguments, Argument, ete, ut for now we will not crate See ‘CHAPTER |_ INTRODUCING VISUAL BASICFOR APPLICATIONS __s procedures with arguments. Empty parentheses are stil required even if a Sub procedure uses no arguments [Sub ProseaureNamerargument, 7 Va sitements lena Sub Figure 1-4. Since of ¢ Sub proce The Structure of a Function Procedure ‘The structure of-8 Function procedure is shown in Figure 15. ‘The procedure begins withthe keyword Function and eas with End Function, tt has a FunctonName, 2 unique identifier that you asign to it.The name should be tong enough to indicate the purpose ofthe function, bit not tos long, since you will probably be typing it in your worksheet formulas, A Function procedure usually takes one or mare arguments; the names of the arguments should alo be Aeseriptive. Empty parentheses ar required even if Function procedure takes no arguments [Faneion FanctooName(agumeat, Vat sitoments FuncaooNome = result lena Function igure 13. Stocure ofa uer-detned Faton ‘The function's ret starement directs the procedure fo retura the result to the caller (usully the cell in which the fimction was entered), ‘The return statement consists ofan assignment statement in which the name ofthe function is equated toa value for example, FunctonName = result Using the Recorder to Create a Sub Procedure Excel provides the Recorder, a usefl tool for cresting command macros. ‘When you choose Macro fiom the Tools menu and Record New Macro... fom the submena, all subsequent menu and Keyboard actions will be rvorded Until ‘You press the Stop Macro bution or choose Stop Recording from the Macro Submenu. The Recorder is convenient for ereting simple macros that involve only the use of menu of Keyboard commands, but you can‘ use it to incorporate logie, branching o looping. ‘The Recorder creates Visual Basic commands. You dont have to know snything about Visual Basic to recond a command macro in Visual Basic. This provides a good way to gain some familiarity with Visual Basic. § crt terra MeTODS, To illosuate the use of the Recorder, Jets record the action of epplying scientific number formatting to a number in a cell, Firs, select ¢ call n'a ‘worksheet and enter a number. Now choose Macro from the Tools menu, then Record New Macro... ftom the submenv. The Record Matro dialog. box: (Figure 1-6) will be displayed. ‘The Record Macro dialog box displays the defsult name that Excel has assigned to this msero: Macro!, Macro2, ete, Change the name in the Mecro ‘Name box to SeientifcFormat (no spaces are allowed in @ name), The "Store Masro In” box should display This Workbook (the default location) if not choose This Workbook. Enter "e" in te box forthe shorteut key, then press OK. Figure 16, The Record Maer nog hx ‘The Stop Recording toolbar wil appear (Figure 1-7), indicating that a macro is being recorded. If the Stop Recording toolbar doesnt appear, you can always Stop recording by using the Tools menu (in the Macro submen the Record New ‘Macro... command willbe replaced by Stop Recording). [its] Figure 17. The Stop Recording tole, Now choose Cells. fom the Format menu, choose the Number tab and choose Scientific number format, then press OK. Finally, press the Stop Reeording baton, ‘To examine the macro code that you have just recorded, choose Macro from ‘he Tools menu and Visual Basic Editor from the subment. Click orithe node “for the module in the active workbook. This wil display the cade module sheet containing the Visuel Basic code. The macro should look like the example shown in Figure 1-8 (CHAPTER 1_INTRODUGING VISUAL BASICFOR APPLICATIONS —_7 (Sab Scone omTaND | Scientiterormat Macro | Macro recorded 6722/2008 by Boston Cotege | Keyboar Shoneut Cute Selection NumberFonm lena sub Figure 1-8, Macro fo scientife numbar- formating, revorded in VBA. ‘This macro consists of a single line of VBA codo, You'l lem about Visual Basic code in the chapters that fllow. To tun the macro, enter 2 number in a eel, select the coll, then choose ‘Macro from the Tools menu, choose Macros... font the submenu, select the ‘ScientscFormat macro from the Macro Name listbox, and press Run, Or you can simply press the shorteut key combination that you designated when you recorded the macro (CONTROL in the example above). The number should be Aisplayed inthe cell in scientific format. o.00E+00" ‘The Personal Macro Workbook ‘The Record Macro dialog box allows you to choose where the recorded ‘macro will be stored. There are three possibilities in the "Store Macro Ia" list box: This Workbook, New Workbook’ and Personal Macro Werkbeok. The Personal Macro Workbook (PERSONALXLS in Excel for Windows, or Personal Macro Workbook in Excel for the Macintosh) is a workbook that i automatically ‘opened when you start Excel. Since only macros ia open workbooks are available for use, the Personal Macro Workbook is the idea! location for macros that you want o have available all the time. ‘Normally the Personal Macro Warkbock is hidden (choose Unbide... from fe Window menu to view it). If you dost yet have a Personal Macro Workbook, you can create one by recording a macro es described earlier, choosing Personal Macro Workbook from the "Store Macro In listbox. ‘As you begin to create more advanced Sub procedures, you'll find thatthe Revorderis 2 useful tool to ereate fragments of macro cade for incorporation into ‘your procedure. Instead of poring through a VBA reference, or searching through the On-Line VBA Help, locking forthe eorest command syntax, simply ‘um on the Recorder, perform the action, and look atthe code produced. Yow may find thatthe Recorder doesnt always produce exactly what yoo wal, oF Pethaps the most elegant code, bt i is almost always useful. [Note that, since the Recorder only records actions, and Funetion procedures can't perform actions, the Recorder won't be useful for ereating Function procedures. $c teria etsops Running a Sub Procedure Inthe presding example the macro was um by sing a shoreut ey, Tere are a number of other wayn rn ami. One way we the Maceo ding bots Again entra somber in ac eset hcl then hone Macs hoes ‘ool mend and Maeras.. fom he simens. The Mat daly box il Be dipleyed (Figre 1-9). This dialog bo its all maces in pes motos Gh now we only have one mcr sve) To hears, sl foe Shes hen ress the Ran baton Assigning a Shortcut Key to a Sub Procedure Ifyou didnt assign a shortcut key to the macro when you recorded it, but ‘would like to do so "after the fact” choose Maero fiom the Tools mem and ‘Macros... from the submenu. Highlight the name of the macro in the Macro ‘Name list box, and press the Options... button. You can now enter a letter for the shortcut key: CONTROL or SHIFTSCONTROL in Excel for Figure. The Macro dialog box. Windows, OPTION!COMMAND- or SHIFTSOPTION+COMMAND* in Excel forthe Macintosh. \ —— VISUAL BASIC Entering VBA Code Of course, most of the VBA code you create will not be recorded, but instead entered atthe Keyboard. As you type your VBA code, the Visual Basic Editor checks each line for syntax errors. A line that contains one or more erors will be displayed in red, the default color for errors. Variables usually appear in black. Other colors are also used; comments (se tater) are usually green and some VBA keywords (Function, Range, etc.) ususlly appear in blue. (These ‘default colors can be changed if you wish.) Ifyou ype a fong line of cod, will not automatically wrap to the next line but will simply disappear off the Sereen. You need to insert a linecontinuation character (ihe underscore character, but you must type & space follawed by the lndersore character followed by ENTER) fo cause a line beak ina line of VBA. ‘ode, a8 i tho following example: Wiorkshoets('Shoett RangoC A257") Copy _ (Worksheets('Sheet2).Ranget'CZ)) ‘The linecontinustion character cant be used within a sting, Le, within quotes | recommend that you type the module-level declaration Option Expt atthe top of each mociule sheet, bsfore any procedures, Option Explicit forces you tO declare all variables using Dim statements; undeclared variables produce a eror stcompile time. ‘When you ype VBA code in x module, its good programming practice ro tse TAB to indent related lines for easier reading. as shown in the following procedure. (sab roy Forms ToN Pose Next [End Sup Figure 1-10. A simple VBA Sub procedure, In order to produce @ more compact display of procedure, several lines of| code can be combined in one line by separating them with colons, For example, the procedure in Figure 1-10 can be replaced by the more compact one ia Figure 1-1 oreven by the one in Figure 1-12 [Sum ray [Ford 1 Tow: Puy = lend Sub ‘igure -11, A Sub procedure with several statements combined Next nm EXCEL: NUMERICAL METHODS (Sub iisaal: Ford= 1 Te NPS ON En SE Figure 1-12. A Sub procedure in one ie. Creating a Simple Custom Function As a simple first example of a Function procedure, well erste a custom function to convert temperatures in degrees Fahrenheit to degrees Celsis, even rsa cn be meni 08 me ope th oh # oie sheet. You can have several macros on the same module sheet, s recorded the Scirtotonat macro earlier in this chapter, you can type this custom function procedure on the same module sheet. Hf you do not have @ ‘module sheet available, insert one by choosing Module from the Insert ment. ‘Type the macro as shown in Figure 1-13. DegF is the argument passed by the funetion fiom the worksheet to the module (tie Fahrenheit temperature); the single line of VBA code evaluates the Celsius temperature and returns the result to the caller (inthis ease, the worksheet cell in which the inction is entered. Function FOCIDSSAy Foo = (Degr~32)"5/8 lend Function ‘igure C13. Fabrenbei to Ces cam Raa ‘A note about naming functions and arguments: function names should be shor, since you will be typing them in Excel formulas (that's why Excel's square- root worksheet function is SQRT) but long enough to coavey information about ‘what the function does. In contrast, command macro names can be long, since command macros are run by choosing the name of the macro from thelist of ‘macros in the Macro Run dialog box, for example. Argument names can be long, since you don' type them. Longer names can convey more information, and thus provide abit of selfdocumentation. (Ifyou look atthe arguments used in Excel's worksheet functions, youl see tat single Teter ae usually not used as argument names.) Using a Function Macro ‘A custom function is used ina worksheet formula in exactly the same way as any of Excels builtin functions. The workbook contsiing the custom function ‘mst be open, Figure 1-14 shows how the Foc custom fimetion is used, Cell A2c 212, the argument that the custom fimetion will use. Cell 62 contain} the formula with the custom function. You can enter the function in cell #2 by evi nm ‘yping it (Figure 1-14). When you press enter, the result calculated by the function appears inthe call Figure I-15) ‘igure 115. The funtion result You can als eter ston yorng th Ter Fanton log box, Select the wokaet elo he point ina worksheet formula whee you Wan fo ets the Rnton, nhs expe cel. Choe Fencton. So the Insert en fr press th Insert Function otron fs oly th Inet Fastin log box Serll ough the Pncion Category it aad select the User Defined CStogory. The Fee foncon wil appear nthe Insert Function lit box gue ilo) gure 16. The Pass Fusco dog oe ‘When you press OK, the Function Arguments dialog box (Figure 1-17) will be Aisplayed. ‘Enter the argument, or click on the call containing the argument 9 enter the reference (cell A2 in Figure I-14), thea press the OK bution, Figure 1-17. The Fanon Arguments dag box A Shortcut to Enter a Function You can enter a function without using Insert Function, but sil receive the benefit provided by the Function Arguments sereen. ‘This is usefl if the fonction takes several (perhaps unfailia) arguments. Simply type. *=" {followed by te funtion name, wit or without the opening parenthesis and then [press CONTROL*A to bypass the Insert Function dielog box and so directty to ‘re Puncton Arguments dialog box, you press CONTROL*SHIFTA, you bypass both the Insert Function dialog box and the Function Arguments, “The function will be displayed with is placeholder arguments). The first argument is highlighted so that you can enor ‘vale or reference (Figure I-18). Figure 1-18, Entering a custom funtion by using CONTROLSSUIFT+A, Unfortunately, if you're entering the custom function in a different ‘workbook than the one that contains the custom function, the funetion name ‘must be entered as an external reference (e.g, Book! XLSIFoc). This can make ‘yping the function rather cumbersome, and if means that youll probably eater the function by using Exeels Insert Function. But, sce "Creating Addn ‘Funetion Macros" in Chapter 2. »DUCING VI ION r Some FAQs ‘re are answers to some Frequently Asked Questions about macros. I Recorded a Command Macro. Where Did It Go? If you have trouble locating the code module contsning your macro, her's what todo "wien all else fails": choose Macro from the Tools menu and Macros... from the submenu. Highlight the name of the macro in the Macro Name list box, and press the Edit button, This will display the code module sheet containing the Visual Basic code. 1 Can't Find My Function Macro. Where Did It Go? if you're fooking inthe lst of macros in the Macro Name list box, you wont find there. Only command macros (macros thet can be Run) are listed. Function macros are found in a different place inthe lst of user-defined funtions inthe Insert Function dialog box. (Choose Funeton... from the Insert menu aad serll through the Function Category ist and slot the User Defined category) How Do I Rename a Macro? To rename » Sub or Function procedure, sce the Visual Basic Editor and click on the module containing the procedure, ‘The name ofthe macro sin the frst line of ode, immediately folowing the Sub cr Funeton keyword. Simply edit the ame. Again, no spaces are allowed in the How Do 1 Rename a Module Sheet? You use the Properties window to lange the name of « module. ‘The module slcct whose nase you Walt (0 change must be the asive sheet. If the Properties window isnot visible, choose Properties Window fom the View menu, or click onthe Properties Window ‘wotbutton GH to display it The Properties Window toolbtton isthe fourth bution fom te righ in he VBA toolar. Figure 1-19. Changing the nme ofa module by using the Propertes window, M4—_____excen: wuwerican Metions Wien you display the Propertiss window, you wll sete single property of nats ntl ms dled ae vid. Sapp dlc othe name (here, Moot, eft the mame, and psa ater” Ws spaces ae allowed in the name. sane = How Do Add a Shortcut Key? Ifyou decide wad shore key oa Gormand macro “fer the fac,” choos Tools-Maero-Macrov a the Macio Nane lit box, click onthe name ofthe mace whan yu wast odes sortsut key, ten press the Options baton, In the Shortcut Key bon ees & Jet, iter lower or uppercase. To rin the mato, use CTRL ctr fe 6 lowercase shorsut ey of CTRLSSHIFT-leter>for apperane Naming: Te sore key wl verses bitin shoreat key tha uses the same lets For example, if you tee CTRLts for he Seiatromat aces you wont be able to use CTRL*s for Save” This willbe in eb slong as te ‘erkbook thet contin the mac is open. How Do 1 Save a Macro? A macro is part of a workbook, just like @ Worksheet ora chart. To save the macro, you simply Save the workbook, Are There Some Shortcut Keys for VBA? Yes, thete are several, Heres 8 usefil one: you can toggle between the Excel spreadsheet andthe VBA Ealtor by presing ALT#F1I. A lis of shortout keys for VBA programming is found in Appendix Chapter 2 Fundamentals of Programming with VBA ‘This chapter provides an overview of Excel's VBA programming language, Because of the specialized nature of the programming inthis book, the material is onpanized in a way that is different from other books on the subject. This book deals almost exclusively with creating custom or userlefined functions, and a significant fraction of VBA'S keywords cannet be used in custom functions. (For example, custom functions cant open or close workbooks, print documents, sort lists on worksheets, ec, —these are actions that are performed by command macros.) Therefore, that portion ofthe VBA language that can be used in custom functions is introduced in the frst part of this chapter, and programming concepts that are applicable in command mactos appear in the latter part ofthe chapter If you are familiar with programming in other versions of BASIC ot in FORTRAN, many ofthe programming techniques deseribed in this chapter will be familiar. Components of Visual Basic Statements VBA macro code consists of statements. Statements ate constricted by using VBA commands, operators, variables, functions, objects, properties, methods, or other VBA keywords. (VBA Help refers to keywords such a8 Loop ‘or Exit a statements, but here they'l be refered to as commands, nd well use “statement” in a general way t refer to line of VBA code.) Much of the VBA code that you will ereate will consist of assignment statements. An assignment statement assigns the result of en expression to & variable or object; the form ofan assignment statement is vasable = expression 90000001 xValue 15 6 ——______picet:NuyERicaLMETHODS == G{APTER2_FUINDAMENTAILS OF PROGRAMMING WITHVBA 37 Kek+t ‘which, inthe second example, says "Store, inthe memory location to which the ‘ser has assigned the label K the value caresponding tothe expression K 1." Operators VBA operators include the arithmatic operators (+, — *, ®, the text ‘concatenation operator (@), the comparison operators (=, <>, <=, >2, =) and the logical operators (And, Or, Not) Variables ‘Variables are the names you create to indicate the storage locations of values orreferences. There are afew rules for naming variables or arguments + You cant use any of the VBA reserved words, such as Formula, Function, Range or Value, + The first character must bea eter. + Axame cannot contain a space or a period. + The characters % S,#, |, & cannot be embedded in a name. If one of these characters is the'last character of a variable name, the character seives asa type-declartion character (ee late). ‘You con use upper and lowercase leters, Ifyou declare a variable type ‘by using the Dim statement (See "VBA Data Types" lates ia this chapter, ie eapitalizason of the variable name will be “fixed” — no matter how ‘you type it in the procedure, the variable name will revert to the ‘capitalization as originally declared. In contest, ifyou have not declared 8 Variable by using Dim, changing the case ofa variable name in any line of code (eg, from formulasrng 19 FormulaSving) will cause al astances ofthe old form ofthe variable to change tothe new form. ‘You should make variable names as descriptive as posible, but avoid overly Jong names which ate tedious to type. You ean use the underscore character to indioate a space between words (eg. formula_stng), You eant use a period 10 indicate «space, since VBA. reserves the period character for use with objects, ‘The most popular form for variable names uses upper and lowercase laters (ee, Formulasving), Long variable names like Formulating provide valuable self documentation; months later, if you examine your code in order to make changes, youl probably be more able to understand it if you used (for examnple) Formuiasirng as a variable name instead of F. But typing long variable names i time-consuming and prone to errors. Tike to use shore names like F when Tm developing the code. Once Im done, I use the Visual Basic Editor's Replace, ‘menu command to convert all these F's to Formulating ‘To avoid insdvercently using a VBA keyword a8 a variable name (there are hundreds of VBA keywords, 3 this is easy to do),1 suggest that you pe the variable name in all lowercase letters. If the variable name becomes eapitlize, ‘this indicates that iti a reserved word. For example, you may decide to use FV ssa variable name. Ifyou type the variable name "Win a VBA. statement, then press Enter, you will see the variable booome "FV," a sign to you that FY is 8 reserved word in VBA (the FV finction calculates the future value of an annuity ‘based on periodic, fixed payments and a fxed interest rate) In fact it's also 8 good ides to type words that you know are reserved words in VBA in lowercase also. IF you type "actvece,” the word will become “AativeCell” when you press the Enter key. If it doesnt, you have typed it incorreely Objects, Properties and Methods VBA is an object-oriented programming language. Objects in Microsoft Excel are the familiar components of Excel, such at a worksheet, a chart, a toolbar, ora range. Objects have properties and methods associated with them, Objects are the nouns of the VBA language, properties are the adjectives that ‘modify the nouns and methods are the verbs (he action words). Objects are ‘sed almost exclusively in Sub procedures, while properties and some tnethods can be used in Funetion procedures. A discussion of objects end methods can ‘be Found in the section "VBA Code for Command Macros" ater inthis chapter. Objects Some examples of VBA objects are the Workbook objec, the Worksheet object, the Chart object and the Range object. Its very likely theta custom function would include any ofthese keywords. But if custom function takes as ‘an argument a cell or range of eels, the argument is @ Range object and has all ‘ofthe properties ofa Range object. Properties Objects have properies that can be set or read. Some properties of the [Range object ae the ColumnWidth propery, the NumberFormat property, the Font property and the Value property. A. property is connected tothe object it modifies by 8 peti, for example CColFmt = Range('ES") NumberFormat ‘tums the number format of ell ES and assign itto the variable CelFm, and Range('E5") NumberFormat ="0,000" Sets the number formatting of call ES. ws "EXCEL: NUMERICAL METHODS, Some properties, such as Column or Count, are read-only. ‘The Column property of a Range object is the column number ofthe leftmost cell in the specified range; it shouldbe clear thet this property can be read, but not chen ged. ‘The Count property ofa Range object is the number of ells in the range; again, itcan be read, but not changed, Properties can also modify properties. The following example Range(’At") Font Bold = True makes the contents of cell Af bold ‘There is large and confusing numberof properties, a diferent list foreach object. For example, as of this writing (Excel 2003), the list of properties pertaining othe Range object contains 95 entries: ‘Adaindont Font Mergenves ow adress FomstCondtons Mergecots RowHeight ‘aero omits Nome Rowe at Formulakray Net. ‘ShowDetst ‘appton Formuldden NumberFormat Smoot ‘eas Fomdalabel" NumberFarmatLocal Smart ags, Boraere Formatosel Ofte. Scundtate Gate FomuaRtct Orientation syle Charecters FomuatCtLocal Outieuevel Summary ‘aur Hecaray agesreak Tot Satins Hesromua Parent. To. Gauneiwa Height Phonetic Usestanderteight Comment Hazen Prone Uses: Sour HorzonaiAsgament. Protas vatoaton Groat Fypertnts Proto valu Gurentaray Pieters Value GurenfRegen —ndanthevet Pherae VeeatAignment Dependents Interior Precedents at DeectDependents em PrefxCharactor Worksheet Drecirocouents) Let Previous Wreptex Ene UetosderRowe — Gueryfeble XPath Eniecolumn —_UstObeat, Renge Enirerow" LecaterinTatle ReadingOrder Enore Ueeke Resize ‘This large number of properties, just forthe Range object, is what makes VBA so difficult for the beginner. You must find out what properties are associated with a particular object, and what you ean do with them, For out _urposes (creating custom functions), only a limited number of these properties of the Range object ean be used. Somo ofthe properties ofthe Range object ‘hat can be used in a custom function are liste in Table 2-1. Note that, when ‘sed ina custom function, these properties can only be read, not set VBA 19 ‘Table 2-1. Some Piopsities ofthe Range Object Column ‘Retums a number corresponding tothe first column in the range. ColumnWidth —Retums or ses the width of al columns inthe range count ‘Returns the numberof fam in the range. Font Returns or sets the font ofthe range. Formula Return or sets the formula. Name ‘Returns or sets the name ofthe range. NumberFormat Retums or sets the formet code forthe range Row ‘Returns a aumber corresponding to the fist row in the range. RowHeight Returns or set the eight ofall rows inthe renge, Toxt RRetums or sets the tet digplayed bythe cel Value ‘Returns or sets the contents of the cell or rang Using Properties Ina Sub procedure, ropertns ran be stor ead, Ina Funetion prosodurc, properties can only be read, not changed. To retum an object's property, use the folfowing syntax: VariableNtame = ObjectNvame.PropertyNeme For example, to obtain the number of cells in range of cells passed to @ function procedure as the argument mg, and store i in the variable Nel, use / the following: | Noets = mg.Count ‘ropeties cam have values that are numeric, sting, a logical Functions Many of the functions available in VBA. are similer to the functions available in Excel itself. There are 187 VBA functions listed in Excel 2003 VBA Help. Tables 2-2 through 2-4 list some of the more usefal ones for mathematical or scientific caloulations, If you are reasonably femiliar with Excel's worksheet functions, you will dave litle trouble using VBA's functions. The names of many VBA functions, such @s Abs, Exp, Int, Len, Left, Mid and Right, are identical to the a EXCEL: NUMERICAL METHODS corresponding workshect functions (ABS, EXP, INT, LEN, LEFT, MID AND RIGHT, respectively). Others, such as Ase, Chr and Sqr, are spelled a litle diferent (the comresponding worksheet functions are CODE, CHAR and SQRT, respectively) or completely differently (Lease and UCase correspond 10 LOWER and UPPER). These VBA functions ate used in exactly the same way. that they are used in worksheet formulas; they take the same type of arguments and retum the same typeof values. Note that although Excel has three worksheet functions thet retun Togarithms (LN retums the natural or base-e logarithm, LOG'0 returns the base- 10 logarithm, and LOG retums a logarithm toa specified base), VBA has only ‘one logarithmic function, Log, that returns the base-e logarithm. If you need ‘9 ‘work with base-10 logarithms in your VBA code, use the relationship logu(a) = Toga) loa 0), VBA does not provide a function to evaluate x, but you can calculate it ina fonction by using the expression 4°Atn(t). Or, you can use the worksheet function Pi, in the manner described inthe following seston. ‘Table2-2. Some VBA Mathematical Functions es Retums the absolute value of a number. atn Retums the stctangent of a number. The results an angle in radians, cos. Retums the cosine ofan angle in radians Exp Retain ruied ta power. Int Retums the integer part ofa number (rounds down), Log ‘Retums the natural (base-e) logarithm of a aumber, Rnd ‘Retums @ random number equal to or greater than 0 and less than 1 Returns the sine ofan angle in radiens. Retums the square root ofa sumber. Retums the tangent of an angle in radians. ‘The above mathematical functions, except for Rnd, have the syntax FunetionNeme/argument).. Rnd takes no argument, but requires the empty parentheses VBA provides funetions for working with text; some ofthe more useful ones se listed in Table 2-3. Most of these are identical to Excel's text worksheet functions. Ifyou ae unfamiliar with the use of txt functions, se the syntax and examples in Append | (CHAPTER 2_FUNDAMENTALS OF PROGRAMMING WITH VBA, 21 ‘Table2-3. Some VBA Tex Functions ‘Kec Returns the ASCII character code of s character. chr [Returns the character corresponding to an ASCII code. Format Formats a number according to a built-in or user-defined number format exprestion. The result is string Inte Returns the first occurrence of a substring within a string. Similar to Excels FIND worksheet function, Len Retums the length (numberof characters) in a string. Left Returns th leftmost characters ofa string, Right Returns the rightmost characters of string. Mia Returns a specified numberof characters from a string. LTrim Returns a sting without leading spaces. Rivim Returns a string without trailing spaces Trim Returns a string without leading o tiling spaces. str Converts «number toasring. A leading space is reserved forthe sign ofthe number; ifthe numbers positive, the string will contain leading space. Lease Converts string into lowercase leters. UCase __Convertsa string into upperease ltrs VBA also provides 3 number of information functions, including eight “Is” fonctions, shown in Table 2-4, ‘Table 2-4. VBA Information Functions ‘Returns Truo ifthe variable is an ara. Returns True ifthe expression i a date YsEmpty Returns True ifthe variable is uninitialized. JsEror Returns True ite expression returns an eror IsMissing Returns True ifan optional value has not been passed to & Function procedure, {IsNull Returns True ifthe expression is nll (., contains no valid dat) [IsNumeric Retums True ifthe expression can be evaluated toa umber, IsObject Returns True ifthe exsression references a valid object. LBound Returns the lower limit of an eray dimension, UBound __ Returns the upper limit of an ersy dimension, _ All the above ts functions have the syntax FunetlonName(argument) and return either True or False EXCEL: NUMERICAL METHODS Using Worksheet Functions with VBA 2 attion to the 187 VBA functions, you cen make use of any of Excel's Rortshoet functions in your VBA code. To use one of Excel worksheet functions, simply use the syntax ‘Application. WorkshoetFuncttonName(argument..) nd supply arguments for the function just as you would in a worksheet, For ‘example, to use the SUBSTITUTE function in VBA, use the cafe FormulaSting = Application Substitute(FormulaSting,XRef, NewX) {G tlace all occurences, inthe sting contained inthe variable Formulating, ofthe variable XRef withthe variable New ‘Some Useful Methods ‘Although most methods can only be used within Sub procedures, there are a Em methods that can be used within Function procedures” Only methods tat do rot "change the appearance of the screea” can be used in Fonsten Frocedues it shouldbe obvious that methods like Cut, Pace, Open, Clove oe ‘cannot be used ins eustom function, Table2-5. Some Methods Applicable tothe Range Object ‘Thai Can Be Used in a Function Procedure Address Returns the reference ofa cll ur range, as txt Columns Retums a Range object that represen a single column or multiple columas. ConvertFormula Converts cell references in formula between Al. and RICI-style, and between relative and absolute, Evaluate Conversa formula toa value Intersect ‘Returns the reference that is the intersection of two ranges. Rows ‘Retums a Range object that represents a single row lormultipte rows Volatile ‘Mars a userdefined function as volatile. The function recaleulstes whenever ealeulation occurs in any cell of the workshext. $e ‘SHAPTER2 FUNDAMENTALS OF PROGRAMMING WITHEVBA 2 Other Keywords In addition to VBA's objects, properties, methods and functions, there ere addtonal keywords that des! with program contol: looping, ranching sod ce ‘on, These keywords are described in detail inthe following sctns, NBA keywords that will not be discussed inthis book inlude objets such 5 menu bars, menus and renu commands, tolbars and toolbutoe’ cad ‘many properties and methods pertaining to them Program Control If you are failiar with compute languages suchas BASIC or FORTRAN, ‘you will find yourself quite comfortable with most ofthe material inthis some Branching NBA supports t..Then statements very similar to the Excel worksheet function IF. The syntax of f.Then is If Logicalexpression Then statement! Else statoment2 ‘The lf..Then statement can be a Simple If ststemeat, for example H (c>0) Then numerator= 10 * 1f Logicalexprossion Cin thic rvample x ~ 0) is True, stotonentt ts caried (ut: if LapiatExpression is False, nothing is done (program execution moree c, the next line). acThen..Else structures are also possible. For example: WErr.Number= 13 Thon Resume ptt Else End Jn « Block If statement, f LogealExpression Thon is followed by multiple ‘Statement lines and is terminated by End if, sin Flgure 2 [fF ereNumber=13 Then ——— On Error GoTo 0» ‘Disable the eror handle Resume pt? ‘and continue execution lena i Figure2-1. Example of VBA Block fstctue. You can also create a Block-IFtype structure in a single tine, as in the following statement. '¥ LogicaiExprossion Then slatomentt : statement? Else statemonts H..Then... Elself structures are also possible, a illustrated in Figure 2.2. 2 ___Exce: wumepicat Meruops Wreterence Rows Count> 1 Then R= equation Row [Ele eference.Colummns.Count > 1 Then igure2-2. Exanple ofthe VBA It.Eleolt.End Wstrctre. Logical Operators ‘The logical operators And, Or and Not can be ued in LagicalExpression, as in the following example. WC>=0AndC-<=9 Then Select Case VBA also provides the Select Case decision structure, similar to the ON value GOTO statement in BASIC. The Select Case statement provides en ficient altemative to the series of Elslf condition statements when condltionN is a singe expression that can take various values. The syntax of the Select Case statement is ilustrated in Figure 23. [Select Case Tastexpression (Case Expressionist ‘sttements| Case Expressiontis ‘statements (case ExpressionList | statements case Else ‘Statements lEnd select Figure2-3. The VBA Select Case ance, TestExpression is evaluated and used to direct program flow to the appropriate Case. ExpressionLisN can be & single value (eg, Case 0), alist of values separated by commas (@g., Cage 4, 3,8), or a range of values using the To keyword (e.g, Case 6 To 8). The optional Case Else statement is executed if Testéxpression doesnt match any of the values in aay of ExpressionLisN Looping Loop structures in VBA sre similar to those evsilable in other programming. languages. (CHAPTER 2__FUNDAMENTALS OF PROGRAMMING WITH VBA. 2s For...Next Loop “The syntax ofthe For.-Next loop is given in Figure 2, [For Countar= Sta statements INext Counter Figure2-4, The VBA For..Nexteuctie, Forexample, Ford=1 T6109 statements ety igure. Example ofa For..Next lop. ‘The Step Incremont part of the For statement is optional. If Increment is ‘omitted, itis set equal to 1. Increment can be negative or nonintegral, for example ‘The Do...Loop is used when you don't know beforehand how many times Joop will need tobe executed. You can (oop While a condition is Tre or Unt condition becomes True. The tvo possibilities are shown in Figures 2-6 and 27, [Bo White LagioaiBxeression | statements ILoop Tigure2-6. The Do While..Loop szusnu, [be statements \Loop While LogialExpresson Figure2-7, Alternate for ofthe Do..Loop While rst, Note tht this second form of the De Wiile structure executes the loop at least once. For Each...Next Loop The For Each...Next loop is loop structure peculiar to an object-oriented EXCEL: NUMERICAL METHODS language. ‘The For Each..Next loop executes the statements within the loop for exch object in a group of objects. Figure 2-8 illustrates the syntax Of the sSatement, FFor Each Element in Group — Statements [Next Element Figure 2.8. The VBA For Each..Next srt The For Each. ext op retin objet aisle in ech pss ugh the lop, "You oan accessor weal ofthe popetes or nets a enat Fer otal os lop sch ste on show i Fp To Yara col sen objec ha has the prope fs cel a Renee oben Value, Formula, NumberFormat, etc. m= meee FormulaText= oo. Value ‘statements = Each cal in Selection Next cot Figure 2.9. Example of For Each. Next lop. NNote that there js no integer loop counter, asin the For Countor = Start To End type of loop structure. If an integer counter is needed, you will have to initialize one outs the loop, and increment inside Ure lose Nested Loops Often one loop must be nested inside anther, asilustated inthe following example, statemonts| Ford=1ToN2 Statements [wie i (*: TToNt Figure 2-10. Example of rested loops, Exiting from a Loop or from a Procedure Often you use a loop structure to search through an array or colfection of objects, looking for » certain value or property. Once you find & match, you dont need to cycle through the rest ofthe loops. You can exit from the loop (CHAPTER 2 FUNDAMENTALS OF PROGRAMMING WITHVBA __27 using the Exit For (irom a For..Next loop or For Each.-Next loop) or Exit Do (om a Do While... lop). The Ext statement will normally be located within an statement. Forexample, If CeliContents Value <= 0 Then Exit For Use the Exit Sub or Exlt Function to exit from a procedure. Ageia, the Ext statement will normally be located within an tstatement. Exit statements can appear as many times as needed within a procedure. VBA Data Types NBA uses a range of different data types. Table 26 lists the builtin data ‘ypes. Unless you declare variables type, VBA will use the Variant type, You can save memory space if your procedure deals only with integers, for exasaple, by declaring the variable as Integer. The keyword Dim is used to declare & -variable's datatype, es willbe described ina following section. ‘Table2-6. VBA's Builtin Data Types Dat Type Storage Required Range of Values Boolean (Logica) 2 bytes True or False Integer 2bytee 32,168 0 32,767 Lona integer 4 bytes 187 83,688 6 2,147 483,647 Single precision 4 bytee 3402823558 to-1.401298E-45 for negative value; 1.401298E-45 10 3.402823E*38 for positive values 1.797693 13486232E+308 to ~4194065665841247E-324 for negative values; 4.940656458412478-324 10 1.7976951348623261308 for positive values Double precision 8 bytes currency Boytes ~922,337, 203,685,477 5808 to 922,337,303,685,477.5807 Date 8 bytes Object bytes Any Object reference String 1 bytefcharacter Variant Is bytes Any numeric value up to the ___# I byte/character “range ofa Double or any text Pn EXCEL: NUMERICAL METHODS The Variant Data Type ‘The Variant data type is the default datatype in VBA. Like Excel itself, the Variant data type handles and jnterconverts between many different kinds of ia: integer, ating point, string, ete. The Variant data type automatically ‘oases the most compact representation. But if your procedure deals with only fone kind of data, it will be more efficient and usualy faster to declare the variables as, for example, Integer. Subroutines By “subroutine” we mean a Sub procedure that is "called" by another VBA program. In writing a VBA procedure, it may be necessary to repeat the same {nstrections several times within the procedure. Instead of repeating the same lines of code over and over in your procedure, you can place this code in @ Separate Sub program; this subroutine or subprogram is then executed by the ‘main program each time it required ‘There are several ways to execute a subroutine within a main program, The ‘so most common are by using the Call command, or by using the name af the subroutine. These are illustrated in Figure 2-11. MainProgram calls subroutines TTeskt and Task2, each of which requires arguments that are passed from the ‘main program to the subroutine and/or are retumed from the subroutine to the sain program. [Sub WainProaram) ot [call Task (argument argument2) _ [Testa arguments ergumenta ete lend Sub [Sub Teski(AreNamet ArgName2) ete lend Sup |sub TaskaareNames,Arghames) ee (End Sub__ ‘igure2-11. A main progam Husain the cteent syntax of subroutine calls ‘The two methods use diferent syntax ifthe subroutine requires arguments Hf the Call command is used, the arguments must be enclosed in parentheses. If ‘only the subroutine name is used, the parentheses must be omitted. Note that the \SUAPTER2 FUNDAMENTALS OF PROGRAMMING WITH VBA, 29 variable names of the arguments in te calling statement and in the subroutine do not have to be the same, ‘There are several advantages to using subrovtines: you eliminate he repoition of code, and you make the programming clearer by edopting a moduler approach. Perhaps most important, «subroutine tat is of general usefulness cea be called by several different procedures. Scoping a Subroutine ‘A Sub procedure ean be Public or Private. Public subroutines can be called by any subroutine in any module. ‘The default for any Sub procedure is Public. ‘A Private subroutine can be called only by other subroutines in the same module. To declare the subroutine Tasks as a private subroutine, use the statement Private Sub Tasks() ‘A Sub procedure that is declared Private will not appear inthe list of ‘macros that can be run in the Macro dialog box. The name of « Sub procedure that takes arguments (i. a subroutine), will also not appear inthe Macro dialog box; only Sub procedures without arguments, that i, with empty parentheses following the procedure name, appear in the Macro dialog box. VBA Code for Command Macros. ‘Command macros (Sub procedures) are "action" macros: they can enter of Modify data on a spreadsheet, create a ropor, display # dialog box and 0 on The CD that accompanies this book includes some examples of Sub procedures, so the material in the following sections willbe useful in understanding the VBA code in these procedures. Objects and Collections of Objects Some examples of VBA objects are the Workbook objec, the Worksheet cbject the Chart object and the Range object. Note thatthe Range object ean specify a single cell, such as ES in the preceding example, ora range of cells, for example, Range(’A:E10"). There is no "cell" keyword in VBA to refer 10 8 single cel; that would be redundant, You can also refer to collections of objects, A collection is a group of ‘objects of the same kind. A collection has the plural form of the objest's name (6, Worksheets instead of Worksheet). Worksheets refers to all worksheets in particular workbook. To reference a particular worksheet in a collection, you can use either Worksheets(\ameText) or Worksheets(index), For example, you can refer to 2 [EXCEL NUMERICAL METHODS 4 spssife worksheet by using iter Worksheets Book) or Workshecta(3) ‘Tae late form i useful, for example, f yu want fo examine al he wonthosts ina workbook, without having to know het ext sn each set ub Thetis hlerarchy of objets. A Range object is contnined within a Worksheet objet whichis contined within WorRbook sac, You apsty ‘an object by specifying its location in a hierarchy, separated by periods, for example, ‘Workbooks(‘Scokt") Worksheots('Sheet") Range('E5") nthe above example, if you dont specify a workbook, but just use Worksheets(‘Sheets") Ranget’E5) ‘you are refering to the active workbook. Ifyou don't specify ether workbook or worksheet, eg, Ranget'es*) ‘you ae referring to cll ES inthe active sheet. Instead of the Keyword Worksheets, you may sometimes need to use the keyword Sheets, Sheets is the collection that includes all sheets in a workbook, both worksheets and char sheets, ‘A complet list of objecs in Microsoft Excel is listed in Excel's Online Help. You can also use the Object Browser to see the complete list of objects. ‘To display the Object Browser dialog box, choose Objeet Browser from the ‘View menu inthe VBE. "Objects" That Are Really Properties Although ActiveCell and Selection are properties, not objects, you can teat them like objects. (ActiveCell isa property ofthe Application cbjec, or the ‘ActiveWindow propery ofthe Application objet.) The Application object has ‘the following properties that you can treat just as though they were objects: the ActiveWindow, ActiveWorkbook, ActiveSheet, ActiveCel, Selection and ‘ThisWorkbook properties. Since there is only one Application object, you can ‘omit he reference to Application and simply use ActiveCell. You Can Define Your Own Objects “The Set keyword lets you define a variable 8s an object, 50 thet you can use the variable name in your eode, rather than the expression for the object. Most often this is done simply for convenience; is easier to typo or remember a variable name rather than the (perhaps) long expression for the object. The variable will have all ofthe properties ofthe object type, ‘CHAPTER 2 FUNDAMENTALS OF PROGRAMMING WITH VBA___31. [Note the difference between identical expressions with and without the use ofthe Set keyword. Inthe expression Valves = Workbooks(‘Bookt") Workshests(‘Sheets") Range E2:E32") the variable XVeiues contzins only the values in cells £2:€32, while the expreseion ‘Set MyRange = Workbooks("Bookt") Worksheste(‘Sheels") Range("E2:E22") creates an object variable MyRango, a Range object that allows you to reed (or se) any of the properties of this object. For example, in addition to the value of any cell in the range E2132, you can obtain its number form, column width, ‘ow height, font and so on, Remember, VBA will allow you to equate a variable to an object in an sssigamentstafement, but te variable does not automatically become an object. Ifyou then atempt to use the variable in an expression that requires aa bec, ‘youl et an "Object required” error message. You must use the Set keyword in “order to create an object variable. Methods. Objects also have methods. ‘The Excel 2003 VBA Help lists 71 methods, listed below, that apply tothe Range objet. Many ofthese methods correspond to familiar menu commands. Activate Ciestotee Fnatont onDiterencee fAdoConmert GiearOvtine._—~ndPrevicus ‘Ran ‘AdiancedFiter —Caluriferences FunctonWiead Select ‘epyNames Consolidate Goalseek SePhonee AeerOutinesivlee Cony Gop Shou ‘AuioCorplete” GopytromRacordeet aor Stouependents ‘aor SopyPctu Inserindent ‘Showers ‘tater GreateNamos Just ShouProaedens ‘tort cut UsNames Son ‘utoFonmat Satasaries Merge Sonspecah, ‘ateoutioe Betete Nagotorrow Speak Borderaroond ——_DiogBox Natere Spectacels Cateiate Diy Perse Stbiot CheckSpeting ——Flbown PeseSpecat Fabio Star et Prout “Teatfocotimns Glesicomments Fight Uneroup GlearConants” Fup Usihsige Clearemets Find ‘Some Useful Methods Methods can operate on an, object or on a property of an object. Some ‘methods that can be applied tothe Range object are the Copy method, the Cut method, the FilDown method or the Sort method, Statements involving cer mesican rons methods usually do not appear in an assignment statement (that i, no equal sign required). For example, Rango(’AtiE1".Clear lers the formulas and formatting in dhe range A1:£1 ‘Some useful VBA methods are listed in Table 27. ‘Table 2-7. Some Useful VBA Methods ‘Retivate—Acivates an objet (sheet, et). Clear Clears an entire range. Close Closes an object. Copy Copies an object toa specified range orto the Clipboard. cut Cuts an objet oa specified range ort the Clipboard, FillDown Copies the ces) inthe top row into theres of the range Select _ Selects an object. ‘Two Ways to Specify Arguments of Methods ‘VBA methods usually take one or more arguments, The Sort method, for example, takes 10 arguments. The syntax ofthe Sort method is ‘object Soriheyt,ordert,key2, order, key, order, header, orserCustom, ‘matehCase, ofentation) ‘The object argument is required all other arguments are optional ‘You cen specify the arguments of a method in two ways, One way isto list ‘he arguments in order as they are specified in the preceding syntax, ie Range(’A%:€150} Sort "Last Name", xiAscending Wich sors the data contained inthe range A‘:E160 in ascending order, using 8s the sortkey the values in the column headed by the label LastName, Ascending is one of many built-in constants. You ea look them up in the On line Help or use the Recorder to provide the eomect one In the preceding example, only tho arguments hey and order? were specified; the remaining arguments are optional and are not required. ‘The second way is to use the name of the argument as it appears in the preceding synine, with the = operstor, to specify the valve ofthe argument, 3 in ‘the following: ‘Seloction Sort Key’ Key2'=Ranget’22"), Orders: \CHAPTER2 FUNDAMENTALS OF PROGRAMMING WITHVBA__33 When using this method, the arguments can appear in any order, and optional ones canbe omitted if you do not seed to specify a vale. Arguments with or without Parentheses ‘The arguments of « method sometimes eppear within parentheses, sometimes ‘without parentheses (see the examples immediately preceding). Sometimes either syntax will wor, sometimes one or the other fails. Why is his? ‘As well as performing an ection, methods create a return value, The return value can be either True or False: True means the method worked False means that it filed, Even the ChartWizard method creates a return value: True ifthe chart was created successfully, False if the method failed. Usually you arent ‘nterested in these return values; if your procedure executed successfully, you are happy. But occasionally the return value is important ‘An example of method thet creates a useful retum value is the CCheckSpelling method. The CheckSpelling method has the fellowing syntax: Application CheckSpellingiwors) If you use this method, you'll need the return value (ether True or False) to determine whether the word is spelled corretly, If you want to use the tetun value of a method, you must enclose the arguments of the metiod in parentheses. Ifthe arguments are not enclosed in parentheses, ten the return value will not be available for use. Put another way, Geeapression ‘esult= Application CheckSpelling/ActiveCell Value) does not produce a syntax error, while the expression result= Application CheckSpelling ActiveCell Value does give a syntax eror. Making a Reference to a Cell or a Range One of the most important skills youll need in order to create Sub procedures that manipulate data in workbooks isthe ebilty to make reference toa cell or range of cells. Yeu need to be able to send values from a worksheet to. module sheet so tat you can perform operations on the worksheet dat, and youll need to be sble to send the results buck from the module sheet to the ‘worksheet, A Reference to the Active Cell or a Selected Range (Often a macro will be designed to operate on a user-selected cell or range. & LIOTECA DEL gp EXCEL: unenicaL mernops Zo refer to the active cell or selected range of cells, use the ActiveCell or Selection keywords. ‘The ActiveCell keyword is usualy used witen the user as selected a single call, whereas the Selection keyword is used whea the wer has seleced a range of cells. However, Selection can refer to a single cell or a range. A Reference to.a Cell Other than the Active Cell ‘Sometime « macro will be designed to operate on values from specified rows and columns in a worksheet, independent of where the eursor has been "parked" by the user. To refer to a cell or range other than the selection, use either the Range keyword or the Colls keyword. The syniax of the latter is Ccells(Rewindex, Columnindes), ‘The following references both refer to cell BS Rango('e3") Cotts(3.2) ‘The preceding are “absolute” references, since they always refer to, in th sxample, cell 83. You can also use what could be called a "eomputed reference, in which the reference depends onthe value ofa variable. The Calls Keyword is conveniently used inthis way. For example, the expression Catlse2) allows you to select any cell in columa B, doponding onthe value asigued tothe variable x, The Range keyword can be used in'a similer way by using the ‘concatenation operator, eg, Range('S" & x) 1s usually good programming practie not to use the Select keyword unless ‘you actually need to Select ces ina workshest, For example, to copy a range of cells from one worksheet to another, you could use the statements shown ia Figure 2-12, and in fact this is exactly the code you would generate using the Recorder. But you can do the same thing much more efficiently. and without Switching from one worksheet to another, by using the code shown in Figure 2- 8, Range OTO20) Select Selection. Copy ‘Sheets(‘Sheat 5), Select RangeCAt") Select, ActiveShoot Paste ‘igure 2-12. VBA code fagment bythe Recorder. (CHAPTER? _ FUNDAMENTALS OF PROGRAMMING WITH VBA 38 (Rage OEDIO Copy hes Shes RangacAT]———] Figure 2-13. A more efficent way t aecomplish the same thing, withour elecng cells References Using the Union or Intersect Method VBA can create references by using methods that are the equivalents of the amion operator (the comma) or the intersection operator (the space characte) ‘that can be used in worksheet formulas. The worksheet union operator ereates » ‘reference that includes multiple selections, for example, SUM(A1,82,03,04,65), The syntax of the corresponding VBA Union method is Union(range', range?,... The worksheet intersection operator creates a reference that 1s ‘common to two references (e.g, the expression F4:FO ESS returas the reference F5). The syntax of the’ corresponding VBA Intersect method is Intersect(renge', range2}. Both range’ and renge2 must be range objects. Examples of Expressions to Refer to a Cell or Range 1. Using the Range keyword with an address Range('B1:010") 2. Using the Cells keyword with ow and column numbers cots(15,5) This expression rofrs to cell E45, 3, Using the Range keyword with a range name Rangey'adr’ ‘The range name adr! was assigned previously using Tnsert»Name~+ Define, This method is useful ifthe user can possibly modify the spreadshest so that the addresses of cells needed by the procedure are changed 4, Using the Ces keyword with variables Cals(RowNum, ColNum) 5. Using the Range keyword with a variable Range(ecd2) ‘The variable adér2 was previously defined by means ofa sttemeat such as ader2 = Selection Address se xce ruericaL eODS 6 Using the Range Keyavord with ampersand TopRow=2: BinRow = 12 RangeF& Topow & "6" & BinRow) ‘The Range argument vauatssoF2:6121) 7. Using th Range keyord with to Cols expressions ange(Cel(s, 1), Cat, 5) This expression refers tothe ange AYES. This meth is wsefil when bth row and com nimbers of the reference mst be "omputed” 4. Using the Range keyword wth Cetsindex) ‘Range("A5:A12").Cells(3) ‘This expression fest cell 7: it provides away to slet individual els witina specied range) Range(a"J107 Cali) Accesses fist across ows thn by columns this example eects ol C2. 9. Using the Range keyword with Oneet Range("A1").Offset(3, 1) This example sets el Ba Range A1-8177.0fee(9, 1) This example sets the ange 24.16. 10, Using the Range keyword with Ost and Resize Range ht:A12).Ofen(, 1 Reste(t 1) Use the Resize keyword to slat a single cell offiet from a range, This example sets el 34, Getting Values from a Worksheet ‘To transfer values from worksheet cells toa procedure, use a reference to @ ‘worksheet range in an assignment statement like the following, variabloname = ActiveCelLValue variabiename = Workshoots(‘Shestt") Range("AS") Value ‘The Value keyword can usually be omit: varobloname = Cels(StarRowtx,StartCo) ‘The corresponding Formula property is used to obtain the formula ina cell, rather than is value, Sending Values to a Worksheet ‘To send values from a module sheet back to a worksheet, simply use an assignment statement like the ones shown in the fllewing examples. You ean send a label Range(*Et") Value constant Cells, 2} Value = 5 jana: the value of variable Worksheets('Sheett"| Rango(*A1")= variabe2 ‘oacell ina worksheet. Again, the Value keyword can usually be omited. Interacting with the User VBA provides two builtin log bones for spay of messages or for input, MsgBox and Inputtiox. These aceon incurported ix Sub paces, ey Should never be used in Function provades MsgBox ‘The MsgBox dislog box allows you to display a message, such as "Please ait." or "Access denied.” The box can displey one of four message icons, and thre ate many possibilities in the mumber and funeson of buttons that etn be Alisplayes. The syntax of the MsgBox function is MsgBox (prom text, buttons, tile toxt hepfe, context) ‘here prompt text is the message displayed within the box, buttons specifies the burns to be displayed, and tdo_tor isthe tite ta be displayed inthe Tite Bar ‘of the box. For information about holpfle and context, refer to Microsoft Excel Visual Basic Reference. The value of buttons determines the type of message ce rere eins icon and the number and type of response buttons; it also determines which Dutton is the default button. The possible values are listed in Table 2-8. The values 0-5 specify the number and type of buttons, values 16-64 specify the type cof message icon and values 0, 256, $12 specify which button is the default Dutton. You add together one number from each group to form a value for ‘buttons. For example, to specify a dislog box with a Watning Query icon, with ‘Yes, No and Cancel buttons, and with the No button as defnult, the values 32 +3 +256=291. ‘Table2-8, Values forthe buttons Pazameter of MsgBox ‘utans Equivalent Value Constant Description ‘0 vBOKOniy ‘Display OK button only. 4 weOKCancel_ Display OK and Cancel buttons 2 woabortRetyignore Display Abort, Retry end ignore butons. 3 whYesNoCancel Display Yes, No and Cancel buttons. 4 veYesNo Display Yes and No buttons. 5 vbRetyCancel_ Display Retry and Cancel buttons. ° No icon. 18 vocriteal Display Critica! Message ion, 32 veQuestion Display Warning Query icon. 45 voExciamation Display Waring Message oon 54 voinfermation Display Information Message icon. 0 vpDefautautont First button is default, 256 veDefauitsuton2 512 _ veDefautButlond Second button is default, ‘Third button i default. For example, the VBA expression, MsgBox "You entered" & ince &"* & Chr(#3) & Chr(13) &_ "That value fs too large." & Chr(13) & Che(13}& Please ty again, 48 ‘here the VBA variable incr has the value 50, produces the message box shown in Figure 2-14, Figure2-14. A Msghox spy ‘The values of buttons are built-in constants—for example, the value 64 for ‘buttons canbe replaced by the variable name vbinformtion. The same result, = ialog box with a Warning Query icon, with Yes, No and Cancel buttons and ‘with the No button as default, can be obtained by using the expression, \olnformation + vBVesNoCancal + veDefauliButton2 inthe MsgBox function instead of he value 323 MsgBox Return Values MsgBox can retum a value thst indicates which button was pressed. This allows you to take different actions depending an whether the user pressed the Yes, No or Cancel butions, for example. To en the rien value of the message box, use an expression like ButtonVaiue = MsgBox (promot text, buttons, tle_text, halal, context) (Note thatthe argustents of MsgBox must be enclosed in parentheses in order Tor tto return a value.) ‘The retum values of the butons are as follows: OK, 1; Cancel, 2; Abort, 3; Retry, 4 Ignore, 5; Yes, No, 7. InputBox ‘The InputBox slows you to pause « macro and request input from the user, There are both an InputBox function and an Inputtox method ‘The syntax ofthe InputBox function is InputBox(rompt tort ttn, deux poston y potion hee, ‘Where prompt_text and tte_tert are as in MSgBox. Default is the expression isplayed inthe input box, a8 sting. The horizontal distance ofthe left edge of the box from the left edge ofthe screen, and the vertical distance of the top edge from the top of the screen are specified by x.posion end postion, a xcet unseat METHODS ‘respectively. For information about hepfie and context, refer to Microsoft Excel Visual Basie Reference If the user presses the OK button or the RETURN key, the Inputfox function ‘turns s a value whatever is inthe text box. Ifthe Cancel button is pressed, the function returns « nll string, The following example produces the input box shown in Figure 2-15, RetumiValu= InputBox("Entr validation code number "Validation of his copy of SOLVER STATS") li Figure 215. An InputBox display, ‘The syntax ofthe InputBox method is ObjectInputBox/promoltoxt, tile text, default x poston, y_ positon, hlple, context type), ‘The differences between the InputBex function and the InputBox method ‘are the following: (7) defeut can be any data type and (i) the additional argument fype_num specifies the data type of the return value, The values of ‘ype_num and the corresponding data types are listed in Table 2-9. Values of ‘ype_num can be added together. For example, to specify an input dialog box that would accept number or string values as input, use the value 1 +23 for ‘ype_num. ‘Table2-9. inputBox Data Type Values um ‘Da T Formula ‘Number String Logical Reference (as a Range object) Exor value = ‘CHAPTER 2_EUNDAMENTALS OF PROGRAMMING WITH VBA 4 ‘The following example causes the InputBox method to retum = Range object (60 that you can use its Address. property in ation to its Value propery, fr example}: Set Know, Ys = Application InputBox _ (Select the range of value, "STEP 1 OF 2, Visual Basic Arrays If you're familiar with other programming languages you are probably familisr with the concept of an array. An ary is @ collection of related variables denoted by a single name, such as Sample. You ean then specify any clement inthe aray by using an index number: Smple(1), Sample(7), ee Many stientists make extensive use of srays in ther calculations, Because some aspects of arrays in VBA can be confusing, this chapter provides detailed coverage ofthis important topic. Dimensioning an Array ‘The Dim (short for Dimension) statement is used to doclare the size of an array. Unless specified otherwise, VBA arrays begin with an index of 0. Thus ‘the statement Dim Samp(10) ‘establishes array storage for 1] elements, Sampie(O) through Sample(10). However, you can specify thatthe arrays in your procedure begin with an array index of I. Since worksheet ranges, worksieet functions and worksheet areys use (or assume) 2 lower aray index of 1, always specifying VBA arrays with Tower aray index of I can eliminate alot of confusion, ‘There are two ways to specify the lower array index. You can specify the lower bound of an array inthe Dim ststement. For example, Dim Sample (1 To 10) sets the lower array index = 1 for the array Sample. Its considered good Programming practice to put the Dim statements at the beginning of the procedure, Alternatively, you can use the Option Base 1 statement, which specifies that all aays in the procedure begin with a lower index of 1, The Option Base 1 statement is used at the module level: that is, it must appear in a module sheet before any procedures, 2 : EXCEL: NUMERICAL METHODS Use the Name of the Array Variable to Specify the Whole Array ‘You can refer tothe complete array by using the aray variable name in your code. The aray name can be used with or without parentheses, Multidimensional Arrays Arrays can be multidimensional. Two-dimensional arrays are common; to ‘reste a -D array called Spectrum, with dimensions 500 rows» 2 columns, use the statement Dim Spectrum (6002) Declaring the Variable Type of an Array Since multidimensional rays such asthe one above can use up significant amounts of memory, ifs good idea to define the datatype ofthe variable. The ‘complete syntax ofthe Dim statement is Dim VariableName(Lower To Uppet) As Type ‘The optional Lower To can be omited. Type can be Integer, Single, Double, Variant, e:- See the complete list of datatypes in "VBA Data Types" ‘carier in tis chapter) A Varlant aray can hold valves of different data fypes, ‘such as integer and string, inthe same ara, Several variables con be dimensioned in s single Dim statemcat, but these must be a separate As Type foreach variable. Thus Dim J As integer, K As Integer is OK but Dim J, KAs Intoger declares only the variable Jas integer. Returning the Size of an Array Use the LBound and UBound functions to obtain the size of an array during execution of your procedure. The LBound function returns the lower index of an amy. For example, for the array Sample described previously, LBound(Sernple) returns 1 and UBound\ Sample) returns 10, ‘The complete syntax of LBound and UBound is LBound{arrayname, dlmmension). For the aray Spectrum dimensioned thus Dim Spectrum (00,2) the statement UBound{Spectrum.t) retums 500 end UBound(Spectrum2) returns 2. (CHAPTER 2_ FUNDAMENTALS OF PROGRAMMING WITH VBA a Dynamic Arrays If you don't know what array size you will need to handle a pacticular problem, you can create a dhmamic array. This will allow you to declate ‘variable a8 an array but set its size later. Dimension the array using the Die command, using empty parentheses, and use the ReDim command later 19 specify the aray size as, for example, in Figure 2-16 [Dim RiaanX, Mean | etnumberof costo use in calculation Neots = xValues. Count [ReDim Meanx(Nals), MeanY(Noatis) Figure 216, Re-imensoning an eray ‘You can also use the ReDim command to change the number of dimensions ofan ara, ‘The ReDim command can appear more than once ina procedure, Ifyou use the ReDim corumand to change the sizeof an array afer it has been "populated ‘with values, the values wil be erased Preserving Values in Dynamic Arrays You can preserve the valuse in an exiting aray by ueing the Preserve keyword, 5 im Meanx0, Mean) ReDim Preserve MeanX(Neais 2), Mean¥(Neells 2) Burt, there's a limitation. Only the upper bound of the lat dimension of & ‘multidimensional array can be changed, Thus, the following code is valid: Dim MeanXanav(2, 1000) ReDim Preserve MeanXandY (2,Nee!s/2) ‘ut the following code will generate a run-time error: Dim MeanXand¥(1000, 2) ReDim Preserve MeanXandY (Nealis/2, 2) — (CEL: NUMERICAL METHODS 4 Lf you use Preserve, you can't use the ReDim command to change the ‘umber of dimensions ofan array Working with Arrays in Sub Procedure Passing Values from Worksheet to VBA Module There ae two ways to get values fiom 2 worksheet into a VBA array. You fan ether set up a loop to read the value of each worksheet cell and store the ‘aloe in the appropriate element of an aay, of you can assign the VBA army to a worksheet range, The former method is staightlorward the later meted escrbed inthe following ection, Depending on which ofthese to methods you use, there can be a definite ‘ference with respect to execution speed that could become important if you sr working with extremely large arays. An appreciable time is required to red values from a range of worksheet cells and store them in an intemal array, while ‘View menu and Debug from the submenu to display the Debug toolbar (Figure 22). ‘The hghljghed tine of code Is the statement tobe executed next Figure 2-23. The VBA Debug toler Adding a Breakpoint ‘A breakpoint allows you to helt execution ata specified fine of code, rather ‘han having to step darough the code from the beginning. There are several ways todd a breakpoint ‘+ Opposite the line of code where you want to set the breakpoint, click in the gray bar onthe left side ofthe VBA module sheet. The line of code will be highlighted (usually in red-brown) and & breakpoint indicator, a large dot of the same color, will be placed inthe margin (cee Figure 2-24), + Place the cursor inthe line of code where you want to seta breakpoint Presthe Tog rato ton lf on he eg ter — (CHAPTER 2_FUNDAMENTALS OF PROGRAMMING WITH VBA + Insert a Stop statement inthe VBA code. + Eater a break expression in the Add Watch dialog box (see "Examining the Values of Variables" leer in this chapter) Fanetion MYSLOPE(Rnawn_ye, kaw) N= known_ys.Count Ton ‘Sex + known x5(2)"2 Syy + known yale) 2 Say + keownes(2)* known_yste) (ESTES ES TESS MySLOPE = Slope End Funetion| igure 224, VBA code with a bresipoin. When you run the macro, the code will execute until the breakpoint is reached, a which point execution will stop. You can now step through the code ‘ne statement at atime oF examine the values of selected variables, as desecibed in the following sections. Since you cant "run" a Function procedure, the only way to step through a Function procedure ist add a breakpoint, then recaleulate a formula containing ‘the custom fonction To remove a breakpoint, click on the breakpoint indicator, or place the cursor on the highlighted line and press the Toggle Breakpoint button, or delete 8 Stop statement. Examining the Values of Variables While in Break Mode ‘You can examine the values of selected variables while in Break Made. You ietto bein Break Mode by one ofthe following: ‘© Your procedure generated a runtime error and halted. ** Your procedure reached a line witha breakpoint or a Stop statement To see the curent value of a variable, highlight the variable by double- clicking on itor simply place the cursor over the variable. The eurent value of the variable will be displayed in a yellow “InfoBox" next to the cursor, as illustrated in Figure 2-25. S| Function MySLOPEQenowa_ye, Known_7e) N= knews_ys.Count Forz=1 TaN Sk + known xo) Sy + known ys) ‘Sex + koown_e(2)*2 Syy= Syy + knawniyets)*2 =e eB + known-9a()-known_y(e) Netz WWtsyy-Se"S N/E SSRs MySLOPE = Slope Ens Function Figure 2-25. Displaying he value of varnble whl ia break mode Examining the Values of Variables During Execution ‘You can also display the values of selected variables as the code is executed, ‘There are several ways to select variables or expressions tobe displayed: *+ Highlight the variable or expression and then choose Quiek Wateh.. from the Debug menu or press the Ouick Watch button :62, on the ‘Debug toolbar, o display the Quick Watch dilog box Figure 2-26). *+ Highlight te variable or expression and then choose Add Wate from the Debug menu to display the Add Watch dialog box (Figure 2- 20). Figure 2-26. The VBA Quick Watch dilog box. 2 Fup, 55 ‘igere2-27, The VBA Add With log bor. To see the values of the selected variables or expressions, you must be ia ‘Step mode. The variables will be listed in the Watches pane (Figure 2-28), ‘which is usually located below the Code window. ‘The eurent values of the ‘variables will be displayed a you step trough the code ax? Figure 2-28. The VBA Watches pane, ‘To remove a variable or expression from the Watches window, selet it ia the Watches window, clioose Rdit Wateh fom the Debug menu and press the Delete button. Or you can simply select it in the Watches Window and press the Delete key. ‘Watch expression are not saved with your code Chapter 3 Worksheet Functions for Working with Matrices Arrays, Matrices and Determinants Spreadsheet calculations lend themselves almost automaticaly tothe use of arrays of values. Arrays in Excel ean be either one- or two-dimensional, For the solution of many types of problem, it ie convenient to manipulate an eatice rectangular array of values as unit. Such an ary is termed a matriz. (i Excel, the terms "range," "array" and "matrix are virtually interchangeable) An m x ‘matrix (er ows andr columns) of values is llustrated below Lent aap on Sy ‘The values comprising the array ae called matr operations on matrices have their owm special rule following seetions. lements. Mathematical to be discussed in the Some Types of Matrices ‘A matrix which contains a single column of m rows or a single row of m columns is called a vector ‘A square matrix bas the same number of rows and columns. The set of elements ay for which = J (at, age. dy) is called the man diagonal or principal diagonal. fall the elements of a square matrix ae zero except those on the main iagonal, the matrix ig tenmed a dlagonal mars. A diagonal matrix whose iagonal elements are all | is aust marie, 8 —___________exce narrican Metions ‘An upper triangular mati bas values on the main disgonal snd above, but the values ofall elements below the main diagonal are zero; similarly, a lower ‘wlangoar matrix has zero values for all elements above the main diegonal, A tridiagonal mais contains all zeros except on the main diagonal andthe ‘wo adjacent diagonals ‘A.gmmemic matrix a square matrix in which aj =. A determinant isa property ofa square matrix; there is a procedure for the ‘umerical evaluation ofa determinant, so that an Nx N'matix ean be reduced to 4 single numerical value. The value of the determinant has propestcs that make it wsefil in certain tests and equations. (See, for example, "Cramer’s Rule” in Chapter 9) An Introdu in to Matrix Mathematics Matrix algebra provides a powerful method far the manipulation of sets of numbers, | Many ‘mathematical operations, such as addition, subtraction, ‘multiplication and division, have their counterparts in matrix algebra, Out discussion will be limited to the manipulations of square matrices. For purpores of illustration, two 3 x3 matrices wll be defined, namely “EA AES Addition or Subtraction. The following examples illustrate addition or subtraction, and atg beg cog) Addion ofa constant: Atg=|d+g erg fxg) 4g hig ing. Addition of two matrices (both must have the seme ‘same numbers of rows and columns): Et teS 4 ensions, ie, contain the uAPTERS ___Mammices sp Multiplication or Division. Multiplication or division by 2 constant fax ab ae] gan led ge | ag gh Maliptication of two matrices can be either scalar or mate multiplication, Scalar muliplcstion of two matrices consists of multiplying the elements of a matrix by a constant, es shown above, or multiplying corresponding elements of ‘wo matrices: ES EE al ‘Thus it’s clear that both matrices most have the same dimensions m x m. Scalar multiplication is commutative, that ie, Ax B= Bx A. Matrix Multiplication. The matric multiplication of two matics is somewiist more complicated. The individual matrix elements of the matt product C oftwo matrices A and Bare Com Deda ‘where fis the fow number and jis te columa number. Thus, or example, et] farstuse areberay ot sbmtce pv wlsldtae sm dreeh drones sy 2) lesinste griney gether e, Matrix mliplcaon isnot generally commutative, that is AB 2 BA ‘Transposition. The transpose of marx A, most commonly writen as A, i the matrix obtained by exchanging the rows and cols ofA hati the matic element 5 becomes the element ay inthe transposed matrix. The wanspse of @ matric of Nowe and Mcolumas isa matix of rows and Wcolumss. Matrix Tnversion, The proses of marx version i analogous to obtaining the recipeal of number a. The matrix reainship that comesponds 10 the algebra relationship a x(a) Vis Aw =r gx anata METHODS ‘where A" isthe inverse matrix and Tis the unit matrix. The process for manvel talclation ofthe inverse of a matrix is complicated and need not be described here, since matrix inversion ean be done conveniently using Excel's workshee: fonction MINVERSE, Evaluation of the Determinant A determinant is « mathematical value ‘that can be calculated for a square matric. Detenminants are useful for the solution of systems of simultaneous equations, x8 will be discussed in chapter 9. ‘The "pencil-and-paper" evaluation ofthe determinant of a matrix of N rows x columns is tedious, but it can be dane simply by using Excel's workshee: funetion MDETERM, Excel's Built-in Matrix Functions Performing metrix mathematics with Excel is very simple. Let’ begin by assuming thatthe matrices A and B have been defined by selecting the 3R x 3C rays of cells containing the values showa in Figure 3-1 and naming them by sing Define Name. Remember, we're simply assigning a range name toa range of eels. We usually refer to its a range ar an arrays the fact that We are calling ‘tmatrix simply indicates what we intend to do with it Figure 3.1. Ranges of ells defined a A and, (Colder ‘Chapter 03 aioe) Examples, workbook Matix Mai, sheet Sheet) Addition or Subtraction. To aid « constant (2g, 3) to matrix A, simply select a range of cells the same size as the matrix, enter the formula =At3, thet ress COMMAND-RETURN or CONTROLSHIFTVRETURN (Macintosh) of CONTROL!SHIFTHENTER (Windows). When you “aray-enter* a formula by pressing e.g, CONTROL*SHIFT»ENTER, Excel puts braces around the formula, shown Below 3 cquapreR3 ____wammices, Do not type the braces if you do, the result will not be recogized by Excel asa formu, loess Figure32. Result marx (A +3). (older "Chapter 03 (Mariza) Examples, workbook Matrix Mat, sect 'Shet’) Subtraction of constant, multiplication or division by a constant, or addition ‘of two matrices is performed in the same way by using standard Excel algebraic operators. Scalar Multiplication. Scalar multiplication ean be either multiplication of the elements of a matrix by a constant, eg. a formula such a5 (=3°A}, or ‘multiplication of corresponding elements of two matrices, eg, (°A°8). The result ofthe latter formula i shown in Figure 33, Figure3-3. Resultmatrs (A> B) (Golder Chapter 03 (Murees) Examples, workbook Marx Mat, shet Sheet) Matric muliplication can be accomplished easily by the use of Excel's worksheet function MMULT(matriet, matrx2). For te matrices A and B defined above, entering the formula =MIMULT(A\B) yields the result shown in Figure 3-4 while the formula =MMULT(B,A) yields the result shown in Figure 35. pe 8 3 @ r] igure 34, Result matix AB. (Colder ‘Chapter 03 Mires) Examples, workbook Matrix Math, sheet Sheet) Figure 35. Result matric BA, (Coder ‘Chapter 03 (veces) Examples, workbook Matix Mi shoot "Sheet ‘Matrix multiplication of two matices is possible only if the matrices are conformable, that is, ifthe number of columns of A is equal tothe number of rows of B. The opposite condition ifthe number of rome of A is equal to the umber of eofunns of B, is aot equivalent. The following examples, involving rultiplication of matrix and a vector, illucrae the possibilities: MMULT (4x3 matrix, 3% 1 vector) =3 x 1 result veetor MMULT (43 matrix, 1 > 4 vector) = #VALUE! MMULT (1 4 vector, 43 matrix) = 1x 4 result vestor Incther words, the two inner indices must be the same Transposition, The transpose of a matrix may be caleulated by using the worksheet function TRANSPOSE(array) or obtained manually by using the ‘Transpose option inthe Paste Special... menu command, ‘The sizeof the aay thet canbe transposed is limited only by the size ofthe ‘Excel epreadchost the numberof rows or olan varios be eater than 256 Matrix Inversion. ‘The process for inverting @ matrix “manually” (Le, using pencil, paper and caleulator) is complicated, but the operation can be carried cut readily by wsing Excel's worksheet function MINVERSE(array). The inverse of the matrix B above is shown in Figure 3-6 Sia Figure 36, Result matic (older ‘Chapter 03 (Matices) Examples, workbook Matix Math, sheet 'Shet') ‘The size ofthe matrix must not exceed 52 rows by 52 columns. Evaluation of the Determinant. The determinant of « matrix of N rows x {Neeolumns can be obtained by using the worksheet function MDETERM(array, ce ae ‘The fimetion retums & single numerical value, not an array, and thus you do not have {© se CONTROLASHTFT-ENTER. The value of the determinant of B, represented by [Bis 2, Some Additional Matrix Functions ‘Some adiitional functions useful for working with arrays or matrices are provided on the CD that accompanies this book. The additional Fnetions are as follows: Identity Matrix. The fonction MIDENT(stze) retums an identity matrix of @ specified size. The size argument is optional. Use size when you want to use en ‘dent matrix ina formula. Omit size when you want to fil a range of cells oz 1 worksheet with an identity matrix; the sizeof the matrix is then determined by the size of the selection. If the selection is not « square matrix, the fnetion returns the #REFI error value. ‘The maximum allowable size is 63 x 63 (larger gives #VALUE! eror). Examples: ‘The expression MIDENT(8) rtums 1,0.,0,,0;0.0,. The formula entered in the range AQ:ES retums 0.0.1) ‘The formula =MIDENT() encered in the range ATES retams #REFI in the cells (the selection has five ows and six columns). Finding the Position of a Value in an Array. The function Mindex(lookup_value, array_, match typo) returns @ horizontal 2-clement arrey ‘containing the row and column numbers of a specified value in an aray. The _rgumentfookup_value isthe value you use to find the value you want in ary, ‘The argument aay. is a contiguous range of cells containing possible looleap values. The argument match_type is @ number (-1, 0, or 1) that specifies the value found in array_. If msich type is O or omitted, the fintion returns the position of the value that is exactly equal to lookup_value, or #NIA, If ‘metch_ype is 1, the funetion retums the position of the largest value that is oss than oF equal () fookup_valve. If matehppe is -1, the function returns the positon of the smallest value that is greater than or equal to fookup_ value Unlike Excel's INDEX worksheet function, if match_fype isI or I, the values do not have tobe sorted in descending or ascending oder, respectively. ‘The aray must contain only numbers. If any cells contain text or error values, Minx returns the #VALUE! error value, Empty cells are teated as ze "AL METHOD! Examples: In the following example the range B13:D15, containing the values (13.0 ~ 198.1222;-5 0,1}, was assigned the name A. ‘The expression Mindex(MAXi(A\,A) returns the array of values (2,3) ‘The expression Winéex(7,A) returns the array of values (@N/A#NIA, ‘The expression Mindex(15,A1)retums th aay of values (1,1. ‘Sealing Arrays. The function MSCALE(aray, scale tector Jogical calculates and applies sale factor fora Nx Mf matrix and returns a.» M scaled matrix, ‘All values ina row are scaled by dividing by the largest element in that row. The ‘unction also creates a column vector of W elements, containing the scale factors Ifthe optional argument scala_factr logical False or omitted the function returns the scaled mix; if sosle_fectorlogieal= True, retums the scale facter veetor. Example Is the following examples the range AS:C7, assigned the name B, contains the values (3,20,1000;-0.1,3,100;5,10,5). ‘The formula =MSCALE(S) retums the array (0.0080.02,1- 0.001 005,130,105), ‘The formula =*MSCALE(B, TRUE) returns the array (0.001;0.0130.1), Combining Separate Ranges into a Single Array. An array in Excel _mvst bea contiguous range of cells. It sometimes happens that one would lke © combine noncontiguous ranges into a single aay. The function Ac(ranget, ‘renge2..) combines individual 1-D or 2D arrays into w2-D array. Al individual ‘rays must be vertical and must have the same number of rows. ‘The VBA code for the funetion is shown in Figure 3-7 ‘This custom function makes use of the ParamArray Keyword, hich allows the function to accept an arbitrary numberof ranges. ‘Some uses fr this eustom function include the following: In the solution of a system of simultaneous equations by the Gaussian Elimination method (see Chapter 9), an augmented matrix of N rows x N+ 1 columns is crested by combining the N’x N matrix of coefficients withthe rows x 1 column vector of constants. This can convenieatly be dane by using the ‘custom funetion. ‘The LINEST worksheet function for multiple linear regrestion (see Chapter 13) requires thatthe argument Anown_x's be a contiguous selection of cells, The ccestom function can be used to convet a series of noncontiguous ranges into aa aay that can be used asthe argument known_x's ia LINEST, TRICE, ss ‘pon Expt ‘Option Bese 1 Funeton Ar(ParamAreay a0) ‘Combines insaual -D oF 2. aay nto anal 2-0 aay. {nth version alin! arays must be "vera ‘Andon aye mosthave same number cons. Bim resus ‘im As Integer, J As Intoger,K Ae Int ‘im TorsX As integer, Temp As Intager, XDim As Intger, Din As Integer im YStart As Intoger, Size As Intoger “Fist, gt sees of individual aay, check to make sure aller same sz, Ford =0 To UBounding) “Hanies ether range, name or aay constant arguments Ilsobjecting() = True Then eteronco toa range ora name “TemeX = ma(d) Rows Count “TompY = ma(J,. Columns. count Elst leAray(ng() Then “TempX = UBoundlng(), 1) TemeY = UBeunding(), 2) Ena HJ=0 Then XOm= Tempx 'XDin © TompX Then Ber = CVErisErrRe: Et Function ‘Yo = Yim Temp Next) “Now combine each il aay let st aay. ‘Tindex s sed to slet within aay ofaray. °Keand Jae corn & roe ndons finda arays, ReDim Resulixoin, Yim) Year=0 Fer|=0 To UBounding) "Size = ma) Colurns. Count Fork= To YSze ForJ=1Toxom ‘Reculid, YSiz-+K) = Application index(ra(, Next JK ‘Yat = Yotart + ¥Sie Wert! ara Rast) End Funeton Figare3-7. VBA futon procodure to combine separate ranges into a single aay (folder Chapter 03 (Matrices) Examples, workbook ArayMaker, module Module) econ erica METHODS Problems ‘Answers tothe folowing probems ae found in the folder "Ch. 03 (Mitre) inthe “Problems & Solution” flderon the CD. 1. Find the inverse andthe detemminant ofthe following matrices: ® © the determinant ofeach ofthe following, me ‘caAPTER MATRICES. eee, Chapter 4 Number Series [Number series, such as 1 Laid ee a ted are important in mary ors of mathematics, such as the evaluation of Transconenal functions, ital or diferental equation, Often, he sum of ner saris is eed 8 a apponiation to «funtion tat ca be rust dire. The approximation beeomes mre and more accurate swore emma Be det the sums; for example, the vale of, the bse of sal logartme, cn be evalsted by means of the sum ofa nae seis: $1 wet 3s @ IF the sum of a sees approasies a fie value as the numberof tems spprasie nny, he snes i ahd be converge. A series is dtergent iF the sum approaches infty (r doesnt converge to definite val) wien the Inter of tems approaches fat. Only converge! aie wl be disused Sb cape, An acauting Series in ene in which the sgn ofeach scene fer isthe opposite ofthe preceding one Such sre wl lvay converge the asco value ofthe therm approaches zr, Instead of a series of constant oon, serie may consist of variables, os cxemplfid by he seis cetop tat tbat + a2 AA series of the form shown above, in which the temas are multiples of non- negative integral powers of, sealed a power series. Funetios such as e, sin x, cos x and others ean be expressed in terms of the sum of an infinite series. Of course, Excel already provides worksheet fimotions to evaluate ', sin x or cos x, but the ability to use number series in Excel {ormula increases the scope of calculations that you ean perform, ® mc NUMERICAL METHODS Evaluating Series Formulas ‘The obvious way to evaluate a series formula is to evaluate individual terms ‘in the series formula in separate rows ofthe spreadsheet, and then sum the terms, Figure 41 illustrates the evaluation of e by using equation 4-1, summing terms ‘ntl the contribution from the next term in he series is les than 1E-15, Figo ‘The sprendshet calculates the vale of by sng egation (1, ‘Note that some rows of calculation have been hidden. ‘A more compact way fo evaluate the sum of a series is by summing terms i 8 single worksheet formula. ‘For example, a value for e can be calculted from ‘equation 4-1 by using the fellowing worksheet formula S1SIFACT(1)IFACT(2)* UEACT(S)+1IFACT(4)HIFACT(S) ‘where we sum the frst $ terms of the series, The true value of ¢ to 15 decimal places) is 2.718 281 828 459 045. ‘The formula retums 2.717 (0.06% ero Unformnately, most power series converge much more slowly than this, and many more terms are required. Hence this isnot a practical way to evaluate a Series in a single cell — apart ftom the fact that it requires a lot of typing, & ‘worksheet formula is limited to 1024 characters. Fortunately there are oer ‘ways to evaluate the sum of series in a single worksheet formula, Using Array Constants to Create Series Formulas An aray constant isan array of values, separated by commas and enclosed in braces, used as an argument of a function. An example of an array constant, sometimes referred to as an aray literal, is (4021200.1), HATERS __wun@er seas ‘You can use an array constant to make the evaluation of e series formula ‘much more compact and accurate, For example, to evalusto equation 4-1, the Formula =1+SUM(UFACT(1.2.8.4,58,7.89,10)) returns the value 2.718 281 801 14638 (1x 10 ¥% ero. Using the ROW Worksheet Function to Create Series Formulas ‘The ROW worksheet funetion provides a convenient way to generate a secies ‘of integers. To illustrate the use of this function in forms, enter the formule =ROW(1:100) in a worksheet cell, Now highlight the formula in the formula bar or in the cell, and press F9 (Windows) of COMMAND'~ (Macintosh) to display the result ofthe formula. You will se the aray of integers fom | to 100, a shown below. {6 2,3:48:8,7:89:10:14:12:13,14:18;16,17:18;19,20:21 22:28:26 25,2627:2829, £80,51,82;38:54 35 36 97,98, 40;4 42:48:44; 46:46 47 48,46,50,51;52:555455 {56)57-58;59;60;81 62:05:64 56/57 8669,70,71,72.73:74,78.78,7:78 7808 i 85 9788590; 91:82:85; 5 87;88;98,100) Using this method you can evaluate series formulas conveniently. For ‘example, the formula fore becomes (21+SUM(UFACTIROWT:100))) and returns a value fore of 2.718 281 828 459 05, identical to the value returned bby Excel's built-in funtion. ‘This formula is an arey formula, so after typing the formule inthe cell, you must enter iby pressing CTRLASHIFT*ENTER, Excel indicates that the formula tn aray formula by enclosing it in braces. Don type the braces as part ofthe formula; they are added automatically by Excel. ‘One problem associated with using the ROW function in formula is thatthe row numbers wil be adjusted if you insert or delete rows For example, if you inser a row above the row in which the expression ROW(t;100) is entered, the expression will become ROW(2101). You can avoid this problem by using the INDIRECT worksheet function, described in the next section, ‘The INDIRECT Worksheet Function ‘The INDIRECT worksheet function creas « reference specified by a text string. Thus, for exemple, the formula SINDIRECTCAt") : 3 2 EXCEL: NUMERICAL METHODS entered in a cell (other than cell At, of cours) creates a reference to cell At and ‘etums the value contained in cell At. Since the reference is text, it will nt change to A2 if row is inserted above. The INDIRECT function ean be used 19 create powerful and versatile worksheet formulas. Some examples will serve ‘Taste, ‘The formula DIRECT(BA) (notes the absence of quotation marks) returns the value in cell A27 if cell 1 ‘contains the text vale A27 Since the argument of INOIRECT isa text string, the se ofthe concatenation ‘operior (the “& character) i common, For example, the formula DIRECTI"A" & 81) ‘Tetums the value in coll A27 if eel 1 contain the value 27 Using the INDIRECT Worksheet Function with the ROW Worksheet Function to Create Series Formulas ‘The INDIRECT function can be used with the ROW function to create formulas to evaluate number series, The series formule for e that was show previously becomes the formula (ETSUMUUFAGI(ROMINUIRECTCE207))) if you wish to evaluat the fist 20 terms, or /+SUM(TIFACTIROW(INDIRECTC*"881))) ‘ere the value in cell 61 specifies the number of ferms to be evaluated. For some, but not all, series you ean evaluate 65536 (2) terms conveniently in this wy, ‘Again, you must enter the array formula by pressing CTRLASHFTENTER. The Taylor Series ‘A series known as the Taylor series is frequently used in the evaluation ef functions by numerical methods. The Taylor series for the evaluation of a ficients Ph pe eect acne ease rasheree SEM sg ws (CHAPTERS [NUMMER SERIES a ‘where F) is the Kh derivative of the function at the pot s, and ¢ is the remainder or error term. As has beea illustrated by examples we have een care, the magnitude of ¢ decreases ask (the numberof terms) increases. ‘To obtain a result that closely approximates the true vale ofa fncton, we need to sum a number of terms. Clearly, we will aot have available t0 us (without a lot of work) values of large aumber of derivatives of the function F, up to the Ath derivative. Fortunately, we will usually need only the first derivative, the first and second derivatives, or the first, second and third derivatives to obtain results of sufficient accuracy. Wo will we the Taylor series ‘expansion ofa fonction in several ofthe subsequent chapters ‘The order of the approximation is determined by the highest-derivative term that is included in the approximation; thus the first-order Taylor secies approximation is Poe h)= FG) +E) 4) tsa grcinton 1,-<1 4, Evaluate the following: saints" 5, Evaluate the following: Sats 6. Evaluate Wallis series form: saath] over the fest 100 terms of the series 7. Evaluate Wallis series for x, summing over 65,536 tems. Use « worksheet formula that uses ROW and INDIRECT to create the series of intogers. 8. A simple yet surprisingly efficient method to calculate the square root of @ number is variously called Heron's method, Newton's method, or the divide- and-average method. Te find the square roct ofthe number a: 1. Begin with an initial estimate x. 2. Divide the number by the estimate (ie, evaluate a4), to get a new estimate 3. Average the original estimate and the new estimate (Le, (e + a4)2) ta get anew estimate _ EXCEL: NUMERICAL METHODS 4, Return to step 2. ‘Use this method to calculate the square root oF a number. The value of the ‘nil estimate x must be greater than ero. Inthe dividesand-averigeinethod, the better the iil estimate, the faster the ‘convergence. Devise an Excel formula to provide an effective initia estimate, The series rath) an) FORD Fok 39 proposed by Machin n 1706, converges quickly. Determine the value of to 15 digits by using this series Chapter 5 Interpolation Given a table of x,y datapoints, tis often necessary to determine the value of y at a value of = that lies between the tabulated values, This process of interpolation involves the approximation of an unknown function. It wil be up to the user to choose 2 suitable function to approximate the unknown one. The degree to which the approximation will be "correc" depends on the function that Js chosen for the interpolation. A large numberof methods have been developed for interpolation; this chapter illustrates some of the most wseful ones, ether in the form of spreadsheet formulas or as custom finetions. Although some interpolation formulas requie uniformly spaced x value, all of the methods described in this chapter ae eppicable to non-unifommly spaced values. Obtaining Values from a Table Since interpolation usually involves the use of values obtained from a table, ve begin by examining methods for looking up Values table Using Excel's Lookup Functions to Obtain Values from a Table Excel provides three worksheet functions for obtaining values ftom a tale: LOOKUP for vertical lockup ina table, HLOOKUP for horizontal lookup and LOOKUP. The first two functions are similar and have virally identical syntax. ‘The LOOKUP function i loss versatile then the others but can sometimes be used in sinatons where the others al The function VLOOKUP(lookup_value, fable_array, column_index_num, ‘ange_lookup) looks for a match between lookup_valve and values in the lefumost column of fable array and returns the value ina specified column inthe ‘ow in which the match was found. The argument colur_index_num specifies the column fom which the value isto be obtained. ‘The column number is relative; for example, a columr_index.num of 7 retums a value from the seventh column of table array. The optional argument range_fookup (I would have called this argument Iatch_type_logical) allows you tO specify the type of match to be found. If n canna METHODS ‘ange_lookup is TRUE or omitted, VLOOKUP finds the largest value that i less ‘than or equal to fookup_value; the values in the first column of table_aray must be in ascending order. If range_lootup is FALSE, VLOOKUP returns an exest ‘match or, fone is not found, the #NIA\ error value; in this cae, the values in {able_array can be in any order. Yeu can use 0 and I to represent FALSE and “TRUE, respectively. Using VLOOKUP to Obtain Values from a Table ‘The spreadsheet in, Figure 5-1 (se folder ‘Chapter 05 Interpolation, ‘workbook ‘nterpoition I sheet ‘Prezing Point) lists the feezing point, boli, point and refractive index of aqueous solutions of ethylene glyco: the complete fable, onthe CD-ROM, contains data for concentrations up to 95% and extends torow 54 ' Freezing and Boiling Points of Heat Transter Fluid (GHAPTERS ___ivregpouarion te, Using VLOOKUP to find the freezing point of 33% solution i illustrated in Figure 52. The formula LOOKUP(F2,8A89:808542,0) ‘was entered in cell G3 and the lookup value, 33, in cell F3. Figure 5-2. Using VLOOKUP to obtain value from table. (Goer ‘Cape 05 Tepes’, wortoonerplaon [abe rez Pio) ‘The third argument, column_index num, is 2 since we want to return freezing point values from relative column 2 of the database. If we wanted to return the refractive index ofthe solution we would use column_index_ num = 4 ‘The fourth argument, enge_foolup, is set to FALSE because inthis case we want to find an exact math, The formula returns the valve 2.9, HLOOKUP(lookup_value,table_array, row_index_num, renge_jcokup) is similar to VLOOKUP, except that it Mools mp in the first row of the aay and Feturns a value from a specified ow in the same column, Using the LOOKUP Function to Obtain Values from a Table ‘When yor use VLOOKUP, you must always “oak up” in the fist column of | the table, and retrieve essocisted information from columas to the right in the Same row; you cannot use VLOOKUP to lock up to the left. Ft is necessary to look tothe left in a table (maybe it's not convenient or possible to rearange the data table so as to put the columns inthe prope order to use VLOOKUP), you can sometimes accomplish this by using the LOOKUP function, LOOKUP(Iookup_valueookup_vector result vector) has bvo syntax forms: vector and array. The vector form of LOOKUP looks in a one-row or one ‘column range (known as a vector) fora value and retures a value from the same positon in another one-row or one-column range. ‘The values in fookup_vactor must be sorted in ascending order. If LOOKUP ean find lokup._ value, iets ‘the largest valu in fookup_vecto that is less than or equal to lookup_value, ——— so cts UNMERICAL, METHODS Creating a Custom Lookup Formula to Obtain Values from a Table ‘A second way £0 "Iookup" to the left in a table is to construct your own lookup formula wsing Excel's MATCH and INDEX yworksheet fumetions. The MATCH and INDEX functions are almost miror images of one another: MATCH Tooks up a value in an aray and returns its numerical position, INDEX Tooks inan say and returns a value ftom a specified numerical position. ‘The following example illustrates how fo use INDEX and MATCH to lookup to te leftina table. In the table of production figures for phosphoric aid shown in Figure $3 (eee folder ‘Chapter 05 Interpolation, workbook ‘interpolation T, sheet 'VLOOKUP to left), it is desired to find the month with the largest production, Figare 5.3. A table requting “lookup othe It ter ‘Caper03 interpola, wokooc Ttepltion Eset LOOKUP 1) Use Excel's MAX worksheet function to find the maximum value inthe range ‘of production figures. The expression IAX(SBSS:S8816) retums the value 83119. Now we want to retum the month value in the column to the left in the same row. We do this in two steps, as follows. First, use the MATCH finetion to find the position of the maximum value in the range. The syntax of MATCH is similar to that of VLOOKUP: MATCH\lookup_value,lookup_array,matct_type nur). If match_type_num = 0, MATCH returns the position of the fist value that is equal to fookup_valve ‘The expression TION 2 =MATCH(83119,$885:$B816,0) returns 4, the maximum value isthe fourth value inthe range. Second, use the INDEX fnction to retum the value ia the same position inthe aray of months: IDEXISASS'SASTE.4) “The specific values 83119 and 4 can now be replaced by the formulae that produced them, to yield the following "megaformula.” SINDEX(SASS.SAS 16 MATCH(MAX(SBS5:53516), S8S5:88516,0) ‘This example could not be handled using LOOKUP, since LOOKUP requires that the lookup values (inthis case in column B) be in ascending order, Using Excel's Lookup Functions to Obtain Values from a Two-Way Table ‘A two-way table i a table with two ranges of independent variables, usually inthe leRmost column (2 values) and in the top row (y values of the able; a two dimensional array of z values forms the body of the table. Figure 5-4 shows an ‘example of such a two-way table (se folder ‘Chapter 05 Interpolation’, workbook: “Interpolation T, sheet ‘Viscosity), containing the viscosity of solutions of etiylene glycol of various concentrations at temperatures fom 0 to 250°F. The table ean also be found onthe CD; the data extends down to row 32. “The desired z value from two way table is found at the intersection of the row and column whore the x and y lookup values, cxpectvely, are located. Unlike in the preceding example showing the aplication of VLOOKUP, wire column_index_num was the value 2 (e value was always returned from coluann 2 ofthe aay), we must calculate the value of column_index_num based on the Tookup value. There are several ways this can be done. A convenient formula is the following, where names have been used for references. Temp and Percent are the lookup values, P_Row is the range $883:SKS3 that contains the independent variable and Table is the table SAS4SKS32, containing the x independent variable ia column 1. The following formula was entered in cell M2 of Figure 5. =VLOOKUP(Temp Tabla. MATCH Peroent.P_Row,1}+,1) The corresponding expression using references instead of names is VLOOKUPINE, $AS4:SI832,MATCHIN2, SBS3:SKS3,1}+1,1) mex uM RICAL METHODS Viscosity of Heat Transfer Fluid (cps) _ i sox 708): 200 sox east iioralieen| | “soe eaaa|y31 22/840] staal eae sear Tra rc) fo ate [is 4) 183i g2) 20 [at S010" “ts8) 27 15] 0) 14a 38, 8 Tol 098| 1.18) 1.8 27 ea Gas) "1.04| 141) “184 208 tira) 09a) “t24) 00) 22a] (gga 111] atl iar fast) 07s) ~ogol 125114] a6 “a aan) 1416 1 aa 3 air 7 120s 3.80 4a BF foo 207) a “30 | 38a a i 140, 7] oral ogo) ar] 143189289) 27a a8 380) “043, “083) “ssl 08d] Tos) a9) 449] tae 225 220 160] “36 o4al”og3| 076) ass} 19) 1 470)037/ 46 aol “060! a7 Figure 5, Using VLOOKUP and MATCH to obtain a vale om a two-vay table, (olds Cpe 05 Ieper, workbook nutans Vicosiy) RS POL Interpolation Often its necessary to interpolate between values ina table, You can use simple lincar interpolation, which uses a straight line relationship between two adjacent values, Linear interpolation can be adequate if the table values are close together, a in Figure 5-6. Most often, though, an interpolation formula that fis a curve through several datapoints is necessary cube iterpelation, in whieh four data points are used for interpolation, is common. The following sections describe methods for performing liner interpolation or eubie interpolation. Linear Interpolation in a Table by Means of Worksheet Formulas To find the value of y at a point x that is intermediate between the table values yp and, yj, use the equation for simple linear interpolation (equation =). 224+ FDoy,-y) o- mm), Froezing point, °F ° 0 2 8 0 8 © WU%Ethylone Glycol Figure 5-6. Freezing poiot of etiyene glycol soluons (deta fom Figure 5-1), lds Cage 05 Intestin, workbook etepsains he Liner ntepoates) “ALMETHODS In the following example, well assume that values of the independent veriable x in the table are in ascending order, as in Figure 5-1, where the independent variable is wits ethylene plycol.. We want to find the freezing point for cersin wi% values. Figure 5.2 shows the data (00 folder ‘Chapter (5 Interpolation, workbook ‘Interpolation I, sheet ‘Linear Interpolation); ifs clear thot, since most ofthe points are close together, we can use linea iferpolatin ‘without introducing too much eror. You can create linear interpolation formula using Excel's MATCH ard INDEX functions. If match_type_num = 1, MATCH returns the position of the largest anay value that is less than or equal to lookup value. ‘The aay must be in ascending order, Use this value in the INDEX funeion to rtum the vals of 35.38.21 andy, s shown i the following: position =MATCH(lookup_vaive known_x's,1) x INDEXknown_»’s,postion) x INDEX (known_2s postions) be INDEX(known_y’s,postion) » -=INDEX(known_’s.postion*1) ‘The preceding formulas were applied tothe data shown in Figure 5-1 to frd the freezing point of a 33.3 wi% solution of ethylene glycol. The following ‘named ranges were used inthe calculations: known_ xs (SAS3;SAS47), known_ys ($835:35847), lookup_value ($FS8), positon (SGSé). The intermediee csleulations and the final INDEMVatues 08) INDEKQWalues,aBei) Fh igure 7. Linear atspolation: intermediate calultons. older Chapt 05 Ineo, workboakTnteolatnF, hex Liner Inplton) OLN 8s ‘The formulas in cells G6:G11 ean be combined into & single "megeformula! {or linear interpolation, shown below and used in eel G16. \OEX(YValues MATCH(LookupValue XVelues, 1) 15-INDEX(XValust MATCH(LookupVaive XVaives,1)/(INDEX( Values MATCH LookupVale, Valves, 1)+1}INDEX(YValues MATCH Lociupvalue,XValues 1) (INDEX Values, MATCH (LookupValue XValuss,1}+4)INOEX(XValues, MATCH Lookup xValues, 1) Figure 5-8. Linear interpolation: foal interpolated value, (Cte Cape OS aterpleonwerkboc nolan sheet Lins trol) Ifyou use the megaformula, the formulas in cells GB:G11 are no longer required. Linear Interpolation in a Table by Using the TREND Worksheet Function Excel provides the TREND worksheet function to perform linear interpolation in a table of data by means of a linea least-squares fit all the data points in the table. But TREND can be used to perform linear interpolation between two adjacent datapoints. ‘The syntax ofthe TREND funtion is TREND(known y's, known_x's, new x', const) ‘where known_y’s and sorown_»'s are one-roWw or one-column ranges of known values. The argument new_x' is a range of cells contsining x values for which you want the interpolated value. Use the argument const to specify whether the linear relationship y= mee +B has an intercept value; i const is set to FALSE or ‘2et0, bis set equal to 2e0, ‘The TREND worksheet function provides a way to perform linear interpolation between two points without the necessity of ereating e worksheet formula, Using the TREND function to perform the linesr interpolation calculation that Was illustrated in Figure 5-7 is shown in Figure 5.9. Cell G18 ‘contains the formula STREND(B20:821,420:421,F18,1) Figure 5-9. Using the TREND workshos inction for liner interpolation, (ole: Chap 05 inept, worktook atlas, shee Lines olin) [Note that sshough TREND can be used to find the least-squares straight tine Arough 2 whole set of datapoints, to perform linear interpolation you must selzct cnly two bracketing points, in this example in rows 20 and 21. It should be clear from Figure 56 thatthe least-squares straight line through all the dat points will not provide the correct interpolated value ‘You can also use TREND for polynomial (eg, cubic) interpolation by regressing against the same variable raised to different powers (see “Cubic Interpolation ina Table by Using the TREND Worksheet Function” Iter in tis chapter) Linear Interpolation in a Table by Means of a Custom Function ‘The linear interpolation formula can also be easily coded at custom {unetion, as shown in gee 5-10. Funetion ristpLfeokup_vae, roa Dim porta As intoger Dim X0 As Double, YO As Double, X1 As Double, V1 As Double or) point: = Application Matchookup value, known 0= known» (painter) Yi Skoowm-ysipiner © 3) tp = YO (ook, vase- XO} (1 = YO) x4 =X) End Funeton Figure 510. Function procure for linear interpolation (older Caper 5 lero, worbok Tatpaaon made Lineal) ‘The syntax ofthe Fonction is InterpLVookup_value,known_x's known y'). (SAE ee ee INTERPOL AT ee eT ‘The argument lookup_value is the value of the independent variable for which you want the interpolated y value; Anown_x’s and known. y's are the arrays of independent and dependent variables, respectively, thet comprise the table. The table must be sorted in ascending order of known_x's. Figure 5-11 lustrates the use of the eustom function to interpolate values in the table shown Figure £11. Using the Inter funecon for lines interpolation, lee Cape 5 Inert, workbook nerplatio fsb 'inea nerpoltn) ‘The custom function can be applied to tables in either vertical or horizontal format. Cubic Interpolation ‘fe, values tn stable change in such way tat liner interpolation isnot suitable, Cubic interpolation uses te values of four adjacent table etties (et 2, and) 0 obtain the coefcents ofthe cubic equation y= art Behe ++ to ue san interpolating function between and Fo example, to ind the feezing. point for a 33.3 wit solution of elene glycol using cubic interpolation requires the Zour table values in Figure 512 whose > values are Mighlighed. ‘A convenient way to perform cubic interpolation is by means of the Lagrange fourth-order polynomial Geom Mera) tera Kena )e—ey) Gia MeNG 5) GaN M2) 4 Greed Gap) gy Gorake aks 20 Baa ee yO) Freezing and Bolling Points of Heat Transfer Fiuid Figure 5-12, Four bracketing vals required ‘o pecfor eubl interpolation st x=33 5% (oles ‘Cspe 05 Itepaon, werabookTnerpoltin sheet Cob ntplaion) ‘The Lagrange fourth-order polynomial is cumbersome 19 wer in x worksheet fonction, but convenient to use inthe form ofa custom function. A compact and elegant implementation of cubic interpolation in the form of an Excel 4.0 Macro [Language custom function was provided by Orvis’. slightly modified version, jn VBA. is provided here (Figure 5-13). The syntax ofthe custom function is InteroCttookup_vatue, known x's, known_y's). The argument lookup. vale is the value of the independent variable for which you went the interpolated y value; known_x°s and known_y's are the arrays of independent and dependent variables, respectively, that comprise the table. The table must be sorted in ascending order of known x's. "Wii. Orvis Exc for Sets ond Engin, Sybex ne, Alena, CA 1953, Fanetion irteipCfeokae_vali, aim Xs, oan) Performs cic intepolation, using an aay of nnn x's, known. y's ‘The komm xs must bei ascending oer Based on XLM code fom Exel fx Chemin’, age 280, which wes based on WJ, On’ cose. im row As intoger Dim As integer | As integer Dim @ As Double, YAS Double Anplication Matchfockup vale, known x Tisow 2 Then om Fort row- 4 Torow+2 ast Forj=row-1Torow2 HT Then @ 0° Pooky vate frown xa) nom 0) -_ knowns) MPay +0 krow 3) Yeveos Ne . nro = End Function ‘igure 5:13, Cubic interpolation fusion procedure, (ole Chapt 63 ntplatn: workbook nepali, node Maen) Figure 5-14 illustrates the use of the custom fiction to interpolate values in the table shown in Figure $-12; call #2 contains the formula =Interp0(G22,SAS8:SA847,3883:98847) @ sag Tar Figure 5:14. Using the InterpC fintion procadue for bic nterplation, (Gober Shapers Interpelason, workbook nel ener Ineplacn) Cubic Interpolation in a Table by Using the TREND Worksheet Function In the TREND function, the array known_x's can include one or more sels af independent variables. For example, suppose column A contains x values. You can enter? values in column B and’ in column C and then regress columns A. trough C against the y values in column D to obtain a cubic interpolation { i exc McA METHODS ‘function, But instead of actualy entering values ofthe square and the cube ofthe > vals, you can use an arrey constant im an array formula, thus {STREND(C19:022,A18:A221,2.3,F9N(1,2.95.1)) ‘his example of using the TREND function ie found in folder ‘Chapter 05 Interpolation’, workbook Interpolation P, sheet Cubic Interpolation’. Linear Interpolation in a Two-Way Table by Means of Worksheet Formulas ‘To perform liner interpolation in a two-way table (a table with two ranges of independent variables, x and y and a two-dimensional aray of z values forming ‘the body ofthe table), we can use the same linea aterplaton formula that was ‘employed earlier. Consider the example shown in Figure 5-5; we want to find the viscosity value in the table forx = 76°F, y = 563 wi% ethylene glycol. The shaded eels are the values that bracket the desited x andy values. as) soi | ox ie co 7378) i934 0.13 Shas| aad | asad)” 353i) fat| 265 “a9 1205) Tal 9821 79) 1 638 NEL 4 80) 2.391 308 AonT sel igure 5.15. Linea inerpolition ina two-way able “The shaded collar the oes sein he interpola. (Gtr Cape Far, eps eb’ Conan? Wey) ‘We must perform three linear interpolations. First as shown in Figure 5-16, forthe two bracketing values of x we ealeulate the value of zat y= 563. The formula used in cell B32 is -sIntepL(0.563,SES3:SFS3,E11:11) Ties i Figure $16. Fst steps in linear intesplation na two-way able (Ge Caper 8 epttw, weak narpln se’ Lina Ie 2-8) ‘Then, in this one-way table (A32:839), we use these two iterpoated valves of to interpolate at x= 76°F, as illustrated in Figure 5-17, The formula in cell BBs interp(AS6,A32:439,692:850) Figure 5.17, Fal step in liner iterpolation in. two-way tbl, (6st Chap BS esa, webu naps Pea" Lone tpn 2.Way) ‘The resulting interpolated value suffers fom the usual erors expected from linea interpolation (and inthis example may be in error by as much as 3%). ‘more accurate value can be obtained by perforning cubic interpolation, using four bracketing values to obtain the coefficients of the interpolating cubic. There are atleast rwo ways to obtain these coefficients: by using LINES' (the multiple linear regression worksheet function, described in detail in Chapter 13), of bY using the evbic interpolation function. The later will be deseribed hee, in the following sctons. Cubic Interpolation in a Two-Way Table by Means of Worksheet Formulas ‘To perform cube interpolation between datapoints in a two-way table, we tse a procedure similar to the one for linear interpolation. Figure 5-18 shows the ‘able of viscosities that was used earlier. In this example we want to obtain the viscosity of a 63% solution at $5°F_ The shaded ces are the values that bracket the desired x and y values 60% |_70%|__an%! 90% 3008450) 6504. 70777) “ial | aaoa| saan sea 707 a es" 16 88) 9470"2e8| aaa me asa rer 2694 at 2 at 284 aa Gi a aa EA cer aT] Figure 518. Cubic interpolation ins two-vay tbl ‘Th shaded cls ate the ones used inthe itepoation. (Ge Chap 5 Tae, woe naps I alan 2:0) Well use the inisip¢ function to perform the intepotstion. Figure 5-19, shows the z vale interpolated at ~ 63% using the fous Lnacholny y vale, far ‘the four bracketing x values, The formula in cll Mi is Figure 5.19. Fis steps in cubic incerpolation in atwo-vay table (tide Chapa Sean, wank nope me Caeinpoes 2a) ‘Thea, in this one-way table, we use the formula -InterpO(L15,SL88:8L811,$MS8:5M811) ‘in cell Mito obtain the final interpolated result, as shown in Figure 5.20, Figure $20, Final step in cubic interpolation in x two-way table. tas Cape 05 eel, vate epi mode este 2a) Cubic Interpolation in a Two-Way Table by Means of a Custom Function ‘The cub interpolation macro was adspted to perform cubic interpolation in two-way table. “The calculation steps were similar to those described inthe preceding section. The eubie interpolation fonction shown in Figure 5-13 was converted into a subroutine Cl; the main program is similar o the Lagrange ‘fourth-order interpolation program of Figure 5-12. ‘The VBA code is shown in Figure 5-21, The syntax ofthe function is InterpC2(x_lookup,y_fookup,known_x’s,known_y’s;known_z's) ‘The arguments xJootup and y loop are the lookup values, The arguments foomn_xs and snow y's are the one-dimensional ranges of the x end y independent variables (in Figure 5.20, the column of temperature values and the row of volume percent values). The argument xoun.z's is the table of dependent variables (the to-dimensional body of te table). Tam Expt Option Base 1 Function itepC2tx lookup, ylcokup, known >, known y's, Known. 3) Kn x's ena column, kngum_ys are in aro, or vice vrs. "inthis version, knew xs and known y's must a ascencng err In fat cal to Sub, 3X18 aay f fur knoe. "and YY is ray of corresponding Z alu, pine isy ok. This calle ase «times nap, 5 baning 4 interpolated Z values, ZZ “in eacana alts Sub, XX sry of four known x's and YY is the aay of rtorplatea 2 value, por Jokup. Dim Mas integer, NAS integer Dim As integer © As Intogee Dim XX(4) As Double, YA) As Double, Z2(¢) As Double, items) As Double. R= Application Match: lookup, known xs, 1) Applestion Match lookup, kein 1) HR 2 Then > known 3 mcr err ETHODS Wo knowny's.Count-2 Then C= frown y'sCount-2 ForN=1704 Check vane oe whet aicancng or estan sede rota came sng or, toc aR he Fm ee ken 1'Then Feri io ‘ri nom ye Minownerseon es ‘oven Ext Function "END row aR 9H, C*M=2) eset cy Few 1t04 “rei = owe ue 3) Wn 2 ef Hed. o- 3) =" Then rtepc2=_ Covet) Ext Function Za) Tanown of N2,C-M3) eit ent ze = Cy okup, YY, 22) rs ay of ep lus ty. Lokup fest reac nin mh ence tn ma Fete ane ea pects tpt eb ery mye sae Pee ee mame tener Dim As integer, As integer im G.As Double, Y As Dou For|=To4 Wie] Then Q=Q* (ookup_vale known x'sQ) J known x50) -_ ‘own 30) +0 "anown ye) erm End Funetion Figure 21. Cubic interpolation finoion procedure for use witha two-way able. (Goler Cape 3 Incpoaer,workooenerpolation I, odse'Cabia Wey) SHAPERS __wrerpouamion os ‘The function InterpC2 was used to obtain the viscosity of a 74.5% weight percent solution of ethylene glycol at 195°F, as illustrated in Figure 5-22. The formula incall M7 was Intep02(K7 7 $AS4:$4$29,S855;8189 SES4-91520) ‘This custom function provides a convenient way to perform interpolation in a ‘wo-way table, Figure 5.22, Result reed by the cub interpoliton function. (tier Chap 05 pin, woe nut le ea 2p Cera Fe) 8 —_______pxcet americas wertions cUAPTERS ___nereppouariow Problems “Table S28. Reine nde ofczte a Various Waveegs a Pudtion of Prue Wsvelength ‘Dua, and ane, the following problems ound inthe folder "Ch, 05 : e754] as00A| soaaA] sose.| soee AT 50764 | o836A ‘Gsespoition inthe "Problems & Solitons folder en he CD. [550000 [2.50077 | soaps | a.souse | x s0ns0 | 1.4peas | 1aaene & | 246 [ast506 [1.51724 [1 i532 | sigs | 51206 | sone | u.s002s 1. Using the table "Freezing and Boiling Poin of Heat Transfer Fluid” shown 3 | cass | sz0e6 | 2.52762 |. sass7 [a szene | sonne [a stees | a.si0es in Figure 5-1 (also found on the CD-ROM), obtain the freezing point of E | 757 [1.002 | 53701 [1.59555 | esses | «990s [isons [asset 30.5% and 34.5% solutions of ethylene elycol. anos | 1ssi02| 1.54867 | 1.54657 [1.s36r6]| s-seaoe | 1.50480 | S305 3. Using the table "Freezing and Boiling Points of Heat Transfer Fluid," find 6 Using the following table aso found on the CD-ROM) ‘the wt ethylene glycol that has a freezing point of O°. “Table 5.29, Dun Table fr nerplton 3. Using the following table (also found on the CD-ROM) oa | 1.0000, “able 5.27, Dua Tele for Two-Way Intepsaon os | 229 ysoo | o4 | os | 43 us| 20 0 [2.7560 x=0.0| "100000 | “o.s210s| 0.667: | o35226 | 0.02020 | -o.ei6is 25. os_| 2.9016 | “2.0801 | 5911 | 1.3e7e7|_ 974730! 0.10003, 20 a.0_[ s.o0see | 4.7e105 | s.1s120| 3.27095 |_a.z0706 | 1.25815 25 as | sssas| ssses7 |" 75299 | e004 | «339501 2.60502 © z0_| isaura | aaszeee | 11ssses | 939603 | s.soa0e |_a.craee 35 2s | searsss| se.sii70| 152700 | is7os0| sans] 2226 40 ‘45 | 106 9697, so | -1902176 ss [oss ‘obtain an interpolated value for zat the following values of x and y by cubic interpolation: x 11,= 1 219;2=1.55,y= 1425, 4. Using the table "Viscosity of Heat Transfer Fluid” shown in Figure 5 (also found on the CD-ROM), obiain the viseotityof a 30.5% solution of ethylene slyeol at 95°C, and the viscosity ofa 74.5% solution of eiylene glycol at 195°C. obtain an interpolated value for y at the following values of x by cubic interpolation: 1.81,3.11, 52,54 ‘5. Using the following table (also found on the CD-ROM), obtain a value for ‘he refnctive index of benzene at the following pressure and wavelength values: 1 atm, 5000 A; 1 atm, 6600 A; 500 atm, $000 A; 900 atm, 5000 A: 1 st, 4600 A, Chapter 6 Differentiation ‘The analysis of scientific or engineerin data often requires the calculation of te frst (or higher) derivative of a funtion or of a eurve defined by a table of datapoints. These derivative values may be needed to solve problems involving the slope of a curve, the velocity or acceleration of an object, or for other calelations. Students in caleulus courses learn mathemetical expressions for the derivatives of many types of functions. But thee are many other functions for which it is dificult to obtain an expression forthe derivative, of indeed the function may not be differentiable. Fortunately, the derivative can always be obtained by numerical methods, which can be implemented easily on a spreadsheet. This chapter provides methods for calculation of derivatives of ‘worksheet formulas or of tabular data First and Second Derivatives of Data in a Table ‘The simplest method to obtain the frst derivative of function represented by a table of, y data points isto calculate ax and Ay, the differences between adjacent data points, and use ay/Ax as an approximation to dys. The first decivative or slope ofthe curve ata given data point x,y, ean be calculated cither of the following forward, backward, or central difference formulas, respectively equations 6-1, 6-2, and 6-3) (forward difforence) (6-1) (ackovard difference) (62) (central difference) (63) ‘The second derivative, ’yid?, of e data sot can be calculated in a similar ‘manner, namely by calculating A(ayszV/ax, dec ngeicAL METHODS Caleolaton ofthe frst or second derivative ofa dataset tends to emphasize fhe “noise” in the data set that is, small errors in the measurements become telatvely much more important, The central difference formula tends fo rede noise resulting ftom experimental err. Points ons curve of, values for which the fet derivative isa maximum, a ‘minimum, or zero are often of particular importance and ate termed critical ‘Points, tht is, points where the curvature (the second derivative) changes sign sare termed infection points. For example, in the analysis of data from an eid. ‘base titration, the inflection poin is used to determine the equivalence pois Calculating First and Second Derivatives ‘A pli tiation (measured volumes ofa base solution are added to a solution ‘of an acid and the pH measured after each adition) is shown in Figure 6-1, anda Portion of the spreadsheet containing the titration data in Figure 6-2. The end. Point of the titration corresponds to the point on the curve with maxiznem slope, ‘nd this point can be estimated visually in Figure 6-1. "The first and second derivatives of the data are commonly used to determine te inflection point ofthe ‘eurve mathematically 140 no 1900 ae 20 00 10 20 30 “0 Volume of 00006 NaOH Figure 6-1. Char of ration deta, (olée:"Chaper 0 Erample, workcok Dei of Toe Dae, woisbeet Der!) 101 9.856 (0.080 0.252. 70.125 [0.100 | 0.288 igure 6-2. Fis derivative of tration data, ner the endpoint. ole Cape 6 Esai, workbook Deis a Fiteion Dat woe Deis) Columns A through F of the spreadsheet shown in Figure 6-2 are used to calculate the fist derivative, apH/aV. Since the derivative has been calculated over the finite volume AY ~ Vy ~ Fy the most suitable volume to use When Plotting the apl¥/a¥ values, as shown in column E of Figute 62, is Vg Fit oo ‘The maximum in ApHV/AV indicates the location of the inflection point ofthe station Figure 63). roo 00 50.0 150 470 190 210 290 250 V,mt. Figure 63, Fist derivative of drason data, ner the enpoint, (olde Chapter 06 Examples, wrkieak De of Traian Dat, wore! Des) ions ‘The maximum in the frst derivative curve must sll be estimated visual ‘The second derivative, A(ApH/APYAY, calculated by means of columns E (rough J of the spreadsheet chown in Figure 6-4) can be used to locate the inflection point more precisely. The second derivative, shown in Figure 6-5, passes through zero a the inflection point. Linear interpolation can be used to ‘calculate the point at which the second derivative is zao. RESIGnG ‘pA | AV ae teal oie besa wots Data Ts Scions Dee) 200 g zo 3 2000 === 15 170 19 20 a0 200 Vem Figure 6-5, Second derivative of tation dats, neath endpoint. (ole "Chaper 06 Example, workbook Dev of Troe Da weseet Des) CHAPTERS DIFFERENTIATION 03 ‘There are other equations for numerics! differentiation tht use three or more points instead of two points to calculate the derivative. Since these equstions ‘usually require equal intervals between points, they are of lees generality. Again, their main advantage is that they minimize the effect of "aise." Table 6-1 lists ‘equations for the first, second and third derivatives, for deta from a table at equally spaced interval ‘These difference formulas can be darived from Taylor series, Recall from Chapter 4 thatthe first-order approximation ie Ft = FO) +H) 6 one notation used in Table 6-1 Pas 2410 os hich upon rearanpng, Becomes jaa =I in yates om daxitedly, an obvious sul ‘The second derivative can be writen at vi Ce) ‘When each oft y terms is expanded according tothe preceding expression for, the expression forthe second derivative becomes G1 =Yia A-Wra ~YIHA es 10) ‘The same result can be obtained from the second-onder Taylor series expansion Forth Fash o)+ EPG) en ‘which is writen in Table 6-1 as sc Ito ay 12) by substituting the backward-ifference formula for F from Table 6-1 Expressions for higher derivatives or for derivatives using more terms can be obtained ina similar Fashion, _ re dexter AL METHODS ‘Table 6-1. Some Formals for Computing Derivatives (Gort: win qual pce eres). First derivative, using to points Forward difference Cental difference Backard difference First derivative, using tree poins: Forward difference syne First derivetve sing four points: Central diference porta Bg Aes en Second dervsive, sing tee pols Forward difference Conant ference Beckward difference Second derivate, using fur point Forward difference yj BBS Yo Yon = ‘Second derivative, using fve pois: jo Ye 16 =30y, #1604 Yin * 1a CCeatal difference Third derivative, using four points Forward difference Yinn Bug * iY 7 Ri TION Using LINEST as a Fitting Function Instead of calelating a derivative at an x value corresponding to a table nity, it may be necessary to obtain the derivative at an intermediate x valu, This problem is related to the process of interpolation, and indeed some ofthe techniques ftom the preceding chapter can be applied here (gee "Cubic Interpolation” in Chapter 5). For example, we can obtain a piecewise fiting fonction that applies to a localized region of the data Set, end use the parameters of the fiting function to calculate the derivative. In this section end the following oe, we will usea cubic equation FQ) ad +bE textd 13) 1s the fiting function, using four datapoints to obtain the four coefficients of the cubic. (The fitted curve will pass exactly through all four points and f will be exactly 1.) Once we have obtained the coefficients, che derivatives are calculated ‘rom them; the fst derivative is P@)=302 +2hx+e oy and the second derivative is FI) bar +25 wy We can use the LINEST workshest function (the multiple Tinesr regression ‘worksheet function, described in detail in Chapter 13) to obtain the coefficients 2, 3, e-and d, then use the coetficents @, 6, and e in equation 6-14 or 6-15 0 calculate the fist or second derivatives. ‘The LINEST method will be illustrated using a table of absorbance data taken ‘1 S.nm increment, part of which is shown in Figures 6-6 and 67; the complete range ofx values is in $ASE:SAS85 and the y values in SBS5'SBSE5, We wish to ‘obtain the first derivative of this dataset at 2-am increments over the range 290 15am, Figure 6-6. Dat std to calelate fist and second derivatives. (otter Cape 08 Beal, work Dares Using INEST test Using msenfrm) 06. EXCEL: NUMERICAL METHODS osi0 Original data points 00 0580 0580 Absorbance sto 560 0580 300 908 400 405410415420 Wavelength, nm Figure 6-7. Char of some dats ued to caleult fst nd second dvvatives. (ole Capers Examples, workbook Der Using INEST, het Ug opr) ‘The steps required in the calculation of the first or second derivative at a specified valve of x areas follows: (Use the MATCH funetion to find the position of the lookup value x in the lable ofr values. The lookup vale is fn cell OS tn Figure 6-6 =MATCH(OS, $AS5:5A885,1) (Use the OFFSET function to select the four bracketing x values =OFFSETISASS.9A805,05-20,4.1) Use « similar formula to obtain the four bracketing y values: FFSETISBSS98585,05-20.4.1) (jv)Use these two arrays inthe LINEST formule, rasing the range of x values to ‘an aray of powers; the LINEST formula must be entered in a horizontal range of three cells, and you must press CONTROL SHIFT+ENTER: SLINEST[OFFSET(knoWn_ys MATCH(08 known_x5,1)2,0,4,1), OFFSET known _xs MATCH(OS known, 35,1)-2,03,4)%(1 28}, 1.0) (¥) Use the INDEX funtion to obtain each ofthe regression coefficients a, & and ¢ from the LINEST array. (To simplify the formula, the cells containing the preceding LINEST formula have been given the name LINEST_srray.) The following equation returns the coefficient =INDEX(LINEST_array,t) ‘CHAPTERS ____._DIFFERENTIATION. or (i) Use the coefficients a, 6, and cto calculate the frst or second derivative: [these formulas are combined into one "megaformula”, the result entered in coll ES in Figure 6-5) is ‘=S'INDEX(LINEST(OFFSET (known_ys. MATCH(D5.x_values,1)2, OFFSET)x_ values MATCH(DS x valves 1)-2,04.1)4,2.9)4.0)1) “SZINDEX(TINEST(OFFSET (known ys MATCH(D8,x values, 1}2,0.4.1, OFFSET|x_ values MATCH(D5.x values 1)-2.04,1)47,2.8),1.012)"% ‘INDEX(LINEST (OFFSET (known._ys/MATCH(OS x values, OFFSET(x_values MATCH(O5 x values, 1)-20,4,1)%1,2.9),0),3), which is rather confusing. A beter approach isto use named formulas. The following table lists the named formulas and ranges used to ealoulete the first derivative shown in Figure 6:7. Xyalues =Sheet2IS$s:sases yivalues =Sheot2IS8s5:s8565 Iookup_value =Shest2I$D$5:$0817 pointer =MATCH(NDIRECT(ROW()&""aROW)D) lookup_value x values, 1) known xs =OFFSET(X values,pointe2,04,1) knoun_ys OFFSET(y_values,ponte-2,0,4,1) UN_eray =LINEST(Sheet2tknown_ys,Sheettknown_xs%,2.3.1,0) a sINDEX(LINEST_array,1) te FINDEX(LINEST_array.2) ee SINDEX(LINEST_array'3} Using these named formulas, ce formula forthe frst derivative becomes sPaaWi2zrbb'etce [Note the formula used for pointer. It incorporates an "implicit intersetion” ‘expression. Since bot lookup_value and x values ae arrays, the formula =MATCH(ookup_value x values) retums an sray of values instead of a single value. Tae formula using the ‘expression INDIRECT|ROW(8""&ROW() fookup_value retums a single value, the value inthe aray lokup_valve that i in the sare row asthe formula 4), ska [| 0 oss oon | e-o3 Figure 6-8, Fist derivative calculated wsing INEST fiction. “They values indica the known experimental plas, (ter Caper 06 Ena, workbook Der slg INEST set Using named formu) ost SAF} 2010 Eee, = Bat i u fos oom $$ e 7 ost "3 o =D x ‘igure 69, Char of values of firs and second derivative ‘calculated using INEST. (old "Chape Os Example, woetbook Dest Using LINES, sheet Using nae formas) — CHAPTER 6 DIFFERENTIATION 09 Part of the tuble of calculated first derivative values is shown in Figure 6-8, and the values are charted in Figure 69. The formula used ia cell F5, for example, is sotaa 22" (One could use the x value where F(3) = 0 to locate the maximum in the retumed by this method may be as great es several percent. Derivatives of a Worksheet Formula Instead of calculating the frst or second derivative of a curve represented by ata points, we'may wish to find the derivative of a function (a workshect formula). In the following, two different methods are illustrated to calculate the first or second derivative of a worksheet formula by using a user-defined function. The calculation ofthe first derivative of the function y = 3x° + Sx? ~ Sx. 411 is used as the example for each method Derivatives of a Worksheet Formula Calculated by Using a VBA Function Procedure ‘The first example is a Function procedure that returns the frst derivative of a specific worksheet formula. ‘The expression fr the derivative is "har-coded” ia the VBA procedure. The user must be able to provide the expression for the derivative and must modify the VBA code to apply it toa different formula. ‘The funeton’s only argument is the value of the independent variable for which the derivative isto be celculated. The main advantage ofthis approach is that the returned value of the derivative is exact. This approach will execute the fastest snd would be suitable if the same formula is to be used many times in a worksheet. Faction Danv6] Use codes the expression fo the deiaive ee. Dent soK"2 = 10°%-5 End Funeon Figere 6-10, Funetion rocedue to demonsrat calultion ofa fist derivative, older Cane 6 Examples, wekcek Des by VBA (Part 1), de Modul) ug xcen wuneericaL METHODS First Derivative of a Worksheet Formula Calculated by Using the Finite-Difference Method The second example is a Function procedure that wes the fnite-difference method. The first derivative ofa formule ina worksheet cell can be obtained th a high degree of sccuracy by evaluating the formula atx and at‘ ax Since ‘Bacel cates 15 significant figures, ax ean be made very small. Under these ‘oncitions ayia approximates dh very well, ‘The user must "hard-code the worksheet formula in VBA, in a suitable form; the derivative is calculated by numerical differentiation. Again, the - TER 6 at [Excel caries 15 digits in its caloulaion, and it sums out that multiplying by a factor of 1.00000001 (a change in the 8th place) produces the minimum ceror, before round-of eror begins to have an effect. Figure 6-12 illustrates this using a quadratic equation as an example; other functions give similar results, ‘The values in Figure 6-12 show that we ean expect accuracy upto spproximately the tenth digit. function's only argument is the value of x, the independent variable. ‘pprosch would be useful if the use is unable to provide an express etivaive for the Funston BanvZy OY =r Dera (WY - O17) 6) Ena Function Function fi) ‘User coda the exaresion forthe function here. fn=aextsesnxnznSoxe tt End Function Figure 611, Penton procedure 6 emonstate calculation of fit deivatve, (older Cpe 6 Exarsies, westbook Dec by VBA (Pat 1). wale Malt) ‘The Newton Quotient Inthe previous section, the fnite-difference method was shown to provide an ‘excellent estimate of the frst derivative of a funtion expressed a2 2 worksheet formula. The multiplier used in the preceding userdefined function was 1.00000001. What is the optimum value ofthis multiplier, so thatthe Newton ‘quotient yx gives th best approximation to chide? ‘There re two sourees of eror inthis fnte-difference method of computing idx: the appraximation error, inherent in using finite value of A%, and the rowsdof’ error, éve 10 the limited precision of the numbers stored in the computer. We want to find the value of ax that strikes the best balance between ‘these two eros. If xis made too large, then the approximation error i large, since dys > aylax only when ax -> 0, If x is made too smal, then the oundofferor is large, since we are obtaining ay by subtracting two large and nearly equal numbers, M(x) and FUx + 42), a] G. D E E STH 7 2 S[rsiines 1a ime oe eee ars itieze eon eso 3 |e S fretieze i [ers tomo Patera ‘zon amt 9 eae a8 © [7s t825 te10) Yamomon| tixomes ~ secant sae] 3 |75 [1625 41 7 smowon|ieasmon east Seaeae Figure 612. Newton quotient ay funtion of te magnitide of Ax (toler "Bape 05 ample: oreo Dsive by VBA (Pa 1, shea Nevtan Quo) Derivative of a Worksheet Formula Calculated hy Using the Finite-Differance Method ‘The spreadsheet shovin in Figure 6-13 (see folder ‘Chapter 06 Examples, workbook ‘Derivs by Sub Procedure) illustates the esleuetion of the frst derivative of a function y =x" ~ 3x" — 130x + 150 by evaluating the funtion at and atx + Ax. Here a value of ax of | 10" was used. For comparison, the first erivative, was calculated ftom the exact expression from differential calculus: PO) = 38 6r~ 130, The Excel formulas in cells 811, 11, Dit, E11, F11, Gt1 and Hit (columns C-F are hidden) ace BIT = teste we Fe) Ct =Att*(tedetta) tae Dit seers ctirrctt tw Feta) ENT =Att*éelia be Fit =Ditett ay on =FtvEn Ayla Hit sorarrarzuation

You might also like