PROFESSIONAL MINDWUnleash the Power of Excel Formulas Now revised to cover the new features of Excel 2002 and expanded with two all-newchapters on financial formulas, this one-of-a-kind
Trang 1PROFESSIONAL MINDW
Unleash the Power of Excel Formulas
Now revised to cover the new features of Excel 2002 and expanded with two all-newchapters on financial formulas, this one-of-a-kind reference delivers all the tips and techniques you need to maximize one of the most powerful spreadsheet tools:
formulas With clear explanations of operators, nesting, and functions plus hundreds
of practical, real-world examples, spreadsheet expert John Walkenbach shares provensolutions for typical (and not-so-typical) Excel challenges From working with dates toperforming table lookups to creating array formulas, this in-depth guide will help yousupercharge your spreadsheets — and make the most of Excel
Your Road Map to High-Performance Excel Formulas
• Get a concise overview of Excel’s many features, including cell formatting, analysistools, and protection options
• Master basic formula facts — including absolute vs relative references, operators,error values, naming techniques, and more
• Get practical tips on using Excel’s worksheet functions in your formulas
• Find expanded coverage of discounting, depreciation, and other financial formulas
• Perform magic with powerful array formulas
• Use your formulas to enhance charts and pivot tables
• Debug formulas and take advantage of Excel’s auditing tools
• Develop custom worksheet functions with VBA
Power Utility Pak trial
CD-ROM included
• A trial version of the author’s
award-winning Power Utility
Pentium PC with Windows 98 or greater;
32 MB RAM; Microsoft Excel 2002
See About the CD appendix for details
and complete system requirements.
BONUS CD-ROM INCLUDES
Excel 2002 Formulas
John Walkenbach
Author of Excel 2002 Power Programming with VBA
“Even if you already have a shelf full of Excel reference books,
be sure to squeeze in a couple of inches for this one.”
—Microsoft OfficePro magazine on the previous edition
John Walkenbachis a principal
of JWalk and Associates, Inc., a
consulting firm that specializes
in spreadsheet application
development, and is the author
of more than two dozen books,
including, most recently, Excel 2002
Bible and Excel 2002 Power
Programming with VBA He maintains
“The Spreadsheet Page,” a popular
Web resource at www.j-walk.com/ss.
,!7IA7G4-feiaaa!:p;N;t;T;t
ISBN 0-7645-4800-X
*85555-AGBGFb
w w w m a n d t b o o k s c o m
Trang 2Excel 2002 Formulas
Trang 4Excel 2002 Formulas
Trang 5LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED
TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES FULFILLMENT OF EACH COUPON OFFER
IS THE SOLE RESPONSIBILITY OF THE OFFEROR.
Trademarks: Professional Mindware is a trademark or registered trademark of Hungry Minds, Inc All other
trademarks are property of their respective owners Hungry Minds, Inc is not associated with any product or vendor mentioned in this book.
is a trademark of Hungry Minds, Inc.
www.hungryminds.com
Copyright © 2001 Hungry Minds, Inc All rights reserved.
No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher.
Library of Congress Control Number: 2001089348 ISBN: 0-7645-4800-X
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1 1B/RT/QZ/QR/IN Distributed in the United States by Hungry Minds, Inc.
Distributed by CDG Books Canada Inc for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty Ltd for Australia and New Zealand; by TransQuest Publishers Pte Ltd for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc.
for Taiwan; by ICG Muse, Inc for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by
LR International for Brazil; by Galileo Libros for Chile;
by Ediciones ZETA S.C.R Ltda for Peru;
by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc for Micronesia; by Chips Computadoras S.A de C.V for Mexico; by Editorial Norma de Panama S.A for Panama; by American Bookshops for Finland For general information on Hungry Minds’ products and services please contact our Customer Care department within the U.S at 800-762-2974, outside the U.S at 317-572-3993 or fax 317-572-4002.
For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign- language translations, please contact our Customer Care department at 800-434-3422, fax 317-572-4002 or write
to Hungry Minds, Inc., Attn: Customer Care Department,
10475 Crosspoint Boulevard, Indianapolis, IN 46256 For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care department
at 212-884-5000.
For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales department
at 800-434-2086 or fax 317-572-4005.
For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 317-572-3168 or fax 317-572-4168 For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, or fax 978-750-4470.
is a trademark of Hungry Minds, Inc.
Trang 7About the Author
John Walkenbach is a leading authority on spreadsheet software and principal of
JWalk and Associates Inc., a Southern California–based consulting firm that cializes in spreadsheet application development John is the author of about 30spreadsheet books, and has written more than 300 articles and reviews for a variety
spe-of publications, including PC World, InfoWorld, PC Magazine, Windows, and
PC/Computing He also maintains a popular Internet Web site (The Spreadsheet Page, www.j-walk.com/ss), and is the developer of the Power Utility Pak, anaward-winning add-in for Microsoft Excel John graduated from the University ofMissouri and earned a Masters and PhD from the University of Montana
Jennifer Mario, Rebekah Mancilla
SENIOR PERMISSIONS EDITOR
QUALITY CONTROL TECHNICIANS
Laura AlbertAndy HollandbeckCarl Pierce
MEDIA DEVELOPMENT SPECIALIST
Greg Stephens
MEDIA DEVELOPMENT COORDINATOR
Marisa Pearman
PROOFREADING AND INDEXING
TECHBOOKS Production Services
Trang 8Thanks for buying my book If you’re interested in developing killer formulas andtaking Excel to a new level, this book is as good as it gets I’m confident that you’llagree that your money was invested wisely
Why I Wrote This Book
I approached this project with one goal in mind: To write the ultimate Excel bookthat would appeal to a broad base of users That’s a fairly ambitious goal But based
on the feedback I received from the first edition, I think I’ve accomplished it.I’ve been using Excel for nearly a decade and I spend a lot of time participating
in the Excel newsgroups on the Internet As a result, I’m very familiar with thetypes of questions that come up time and time again Much of the material in thisbook was inspired by questions on the Excel newsgroups This book provides theanswers to those questions — along with answers to questions that probably neveroccurred to you!
As you probably know, most bookstores offer dozens of Excel books The vastmajority of these books are general-purpose user guides that explain how to use thefeatures available in Excel (often by simply rewording the text in the help files) Afew others focus on advanced issues such as macro programming or scientificapplications None (that’s right, none!) hones in on the one fundamental compo-nent of Excel that is critically important to every user: formulas Fact is, formulasare what make a spreadsheet a spreadsheet The more you know about formulas, thebetter your spreadsheets will be It’s that simple
Excel is the spreadsheet market leader, by a long shot This is the case not onlybecause of Microsoft’s enormous marketing clout but also because it is truly thebest spreadsheet available One area in which Excel’s superiority is most apparent isformulas Excel has some special tricks up its sleeve in the formulas department Asyou’ll see, Excel lets you do things with formulas that are impossible with otherspreadsheets
It’s a safe bet that only about ten percent of Excel users really understand how
to get the most out of worksheet formulas In this book, I attempt to nudge you intothat elite group Are you up to it?
What You Should Know
This is not a book for beginning Excel users If you have absolutely no experience
with Excel, this may not be the best book for you — unless you’re one of a rarebreed who can learn a new software product almost instantaneously
Trang 9To get the most out of this book, you should have some background using Excel.Specifically, I assume that you know how to
◆ Create workbooks, insert sheets, save files, and other basic tasks
◆ Navigate through a workbook
◆ Use Excel’s menus, toolbars, and dialog boxes
◆ Use basic Windows features, such as file management and copy and pastetechniques
If you’re an experienced spreadsheet user, but you are new to Excel, ter 1 presents a concise overview of what this product has to offer.
Chap-What You Should Have
To make the best use of this book, you need a copy of Microsoft Excel When Iwrote the current edition of the book, I was using Excel 2002 (which is part ofMicrosoft Office XP) With a few exceptions (noted in the text), the material in thisbook also applies to all earlier versions of Excel that are still in use
To use the examples on the companion CD-ROM, you’ll need a CD-ROM drive.Duh! The examples on the CD-ROM are discussed further in the “About theCompanion CD-ROM” section, later in this preface
I use Excel for Windows exclusively, and do not own a Macintosh Therefore,
I can’t guarantee that all of the examples will work with Excel for Macintosh Excel’s cross-platform compatibility is pretty good, but it’s definitely not perfect.
As far as hardware goes, the faster the better And, of course, the more memory
in your system, the happier you’ll be And, I strongly recommend using a resolution video mode: at least 1024 x 768
high-Conventions in This Book
Take a minute to skim this section and learn some of the typographic conventionsused throughout this book
Trang 10Keyboard Conventions
You need to use the keyboard to enter formulas In addition, you can work withmenus and dialog boxes directly from the keyboard — a method you may find eas-ier if your hands are already positioned over the keys
FORMULA LISTINGS
Formulas usually appear on a separate line in monospace font For example, I maylist the following formula:
=VLOOKUP(StockNumber,PriceList,2,False)
Excel supports a special type of formula known as an array formula When you
enter an array formula, press Ctrl+Shift+Enter (not just Enter) Excel encloses anarray formula in brackets in order to remind you that it’s an array formula When Ilist an array formula, I include the brackets to make it clear that it is, in fact, anarray formula For example:
{=SUM(LEN(A1:A10))}
Do not type the brackets for an array formula Excel will put them in automatically.
VBA CODE LISTINGS
This book also contains examples of VBA code Each listing appears in a space font; each line of code occupies a separate line To make the code easier toread, I usually use one or more tabs to create indentations Indentation is optional,but it does help to delineate statements that go together
mono-If a line of code doesn’t fit on a single line in this book, I use the standard VBAline continuation sequence: a space followed by an underscore character This indi-cates that the line of code extends to the next line For example, the following twolines comprise a single VBA statement:
If Right(cell.Value, 1) = “!” Then cell.Value _
= Left(cell.Value, Len(cell.Value) - 1)You can enter this code either exactly as shown on two lines, or on a single linewithout the trailing underscore character
ix
Trang 11KEY NAMES
Names of keys on the keyboard appear in normal type, for example Alt, Home,PgDn, and Ctrl When you should press two keys simultaneously, the keys are con-nected with a plus sign: “Press Ctrl+G to display the Go To dialog box.”
FUNCTIONS, PROCEDURES, AND NAMED RANGES
Excel’s worksheet functions appear in all uppercase, like so: “Use the SUM function
to add the values in column A.”
Macro and procedure names appear in normal type: “Execute the InsertTotalsprocedure.” I often use mixed upper- and lowercase to make these names easier to
read Named ranges appear in italic: “Select the InputArea range.”
Unless you’re dealing with text inside of quotation marks, Excel is not sensitive
to case In other words, both of the following formulas produce the same result:
=SUM(A1:A50)
=sum(a1:a50)Excel, however, will convert the characters in the second formula to uppercase
Mouse Conventions
The mouse terminology in this book is all standard fare: “pointing,” “clicking,”
“right-clicking,” “dragging,” and so on You know the drill
What the Icons Mean
Throughout the book, icons appear in the left margin to call your attention topoints that are particularly important
This icon indicates a feature new to Excel 2002.
I use Note icons to tell you that something is important — perhaps a cept that may help you master the task at hand or something fundamental for understanding subsequent material.
con-Tip icons indicate a more efficient way of doing something, or a technique that may not be obvious These will often impress your officemates.
Trang 12These icons indicate that an example file is on the companion CD-ROM.
(See the upcoming “About the Companion CD-ROM” section.)
I use Caution icons when the operation that I’m describing can cause lems if you’re not careful.
prob-I use the Cross Reference icon to refer you to other chapters that have more
to say on a particular topic.
How This Book Is Organized
There are hundreds of ways to organize this material, but I settled on a scheme thatdivides the book into five main parts In addition, I’ve included a few appendixesthat provide supplemental information that you may find helpful
Part I: Basic Information
This part is introductory in nature, and consists of Chapters 1 through 3 Chapter 1sets the stage with a quick and dirty overview of Excel This chapter is designed forreaders who are new to Excel, but who have used other spreadsheet products InChapter 2, I cover the basics of formulas This chapter is absolutely essential read-ing in order to get the most out of this book Chapter 3 deals with names If youthought names were just for cells and ranges, you’ll see that you’re missing out onquite a bit
Part II: Using Functions in Your Formulas
This part consists of Chapters 4 through 10 Chapter 4 covers the basics of usingworksheet functions in your formulas I get more specific in subsequent chapters
Chapter 5 deals with manipulating text, Chapter 6 covers dates and times, andChapter 7 explores various counting techniques In Chapter 8, I discuss various types
of lookup formulas Chapter 9 deals with databases and lists, and Chapter 10 covers
a variety of miscellaneous calculations such as unit conversions and rounding
Trang 13Part III: Financial Formulas
Part III consists of three chapters (Chapters 11 through 13) that deal with creatingfinancial formulas You’ll find lots of useful formulas that you can adapt to yourneeds
Most of the material in Chapters 11 through 13 was contributed by Norman Harker Norman is a Senior Lecturer in Real Estate at the University of Western Sydney (Australia).
Part IV: Array Formulas
This part consists of Chapters 14 and 15 The majority of Excel users know little ornothing about array formulas — a topic that happens to be dear to me Therefore Idevote an entire part to this little-used yet extremely powerful feature
Part V: Miscellaneous Formula Techniques
This part consists of Chapters 16 through 21 They cover a variety of topics — some
of which, on the surface, may appear to have nothing to do with formulas Chapter
16 demonstrates that a circular reference can be a good thing In Chapter 17, you’llsee why formulas can be important when you work with charts, and Chapter 18covers formulas as they relate to pivot tables Chapter 19 contains some very inter-esting (and useful) formulas that you can use in conjunction with Excel’s condi-tional formatting and data validation features Chapter 20 covers a topic that I call
“megaformulas.” A megaformula is a huge formula that takes the place of severalintermediary formulas And what do you do when your formulas don’t work cor-rectly? Consult Chapter 21 for some debugging techniques
Part VI: Developing Custom Worksheet Functions
This part consists of Chapters 22 through 25 This is the part that explores VisualBasic for Applications (VBA), the key to creating custom worksheet functions.Chapter 22 introduces VBA and the VB Editor, and Chapter 23 provides some nec-essary background on custom worksheet functions Chapter 24 covers program-ming concepts, and Chapter 25 provides a slew of worksheet function examplesthat you can use as-is or customize for your own needs
Appendixes
What’s a computer book without appendixes? This book has five appendixes In theappendixes, you’ll find secrets about importing 1-2-3 files, a quick reference guide
Trang 14to Excel’s worksheet functions, tips on using custom number formats, and a handyguide to Excel resources on the Internet The final appendix describes all the files
on the CD-ROM
How to Use This Book
You can use this book any way you please If you choose to read it cover to coverwhile lounging on a sunny beach in Maui, that’s fine with me More likely, you’llwant to keep it within arm’s reach while you toil away in your dimly lit cubicle
Due to the nature of the subject matter, the chapter order is often immaterial
Most readers will probably skip around, picking up useful tidbits here and there
The material contains many examples, designed to help you identify a relevant mula quickly If you’re faced with a challenging task, you may want to check theindex first to see whether the book specifically addresses your problem
for-About the Companion CD-ROM
The inside back cover of this book contains a CD-ROM that consists of three basicelements:
◆ Example workbooks that demonstrate concepts presented in the text
◆ A trial copy of my Power Utility Pak 2000 add-in
◆ A demo copy of my Sound-Proof 2000 add-in Sound-Proof is a handyauditing tool that uses Microsoft Agent technology to read the contents ofcells You may prefer this to Excel 2002’s text-to-speech feature
The example workbook files on the companion CD-ROM are not compressed, soyou can access them directly from the CD (installation not required) Power Utility
Pak and Sound-Proof, however, do require installation Refer to Appendix E for
details
All CD-ROM files are read-only.Therefore, if you open a file from the CD-ROM and make any changes to it, you’ll need to save it to your hard drive Also, if you copy a file from the CD-ROM to your hard drive, the file retains its read- only attribute.To change this attribute after copying a file, right-click the file- name or icon and select Properties from the shortcut menu In the Properties dialog box, click the General tab and remove the check mark from the Read-only check box.
Trang 15About the Power Utility Pak Offer
Toward the back of the book, you’ll find a coupon that you can redeem for a counted copy of my award-winning Power Utility Pak — a collection of useful Excelutilities, plus many new worksheet functions I developed this package using VBAexclusively
dis-You can also use this coupon to purchase the complete VBA source code for anominal fee Studying the code is an excellent way to pick up some useful pro-gramming techniques You can take the product for a test drive by installing theshareware version from the companion CD-ROM
Power Utility Pak requires Excel 97 for Windows or later.
You can always download the most current version of the Power Utility Pak from
to one of the Excel newsgroups is, by far, the best way to get such assistance SeeAppendix D for specifics
Also, when you’re out surfing the Web, don’t overlook my Web site (“TheSpreadsheet Page”):
http://www.j-walk.com/ss/
Now, without further ado, it’s time to turn the page and expand your horizons
Trang 16Thanks to everyone who purchased the first edition of this book I’m especiallygrateful to those who took the time to provide me with valuable feedback and sug-gestions I’ve incorporated many of the reader suggestions into this new edition
I am also grateful to Norman Harker, Senior Lecturer in Real Estate at theUniversity of Western Sydney (Australia) After reading the first edition, Normanpointed out that the single chapter on financial formulas was the weakest part ofthe book Consequently, the financial formulas portion of the book has been beefed
up significantly, and Norman provided the bulk of the contents of Chapters 11–13
I would also like to thank Bill Manville for his superb technical editing skills This
is my second project with Bill, and I’m convinced that he is among the best cal editors in the business He corrected many of my mistakes, made lots of usefulsuggestions, and re-wrote dozens of my formulas to make them perform better.Finally, I wish to thank the folks at Hungry Minds for publishing this book It iscertainly not your “typical” Excel book, and publishing it was a risky venture Therisk paid off, however, as evidenced by the fact that it was selected for a secondedition Special thanks to Susan Christophersen, my project editor She made myjob much easier
Trang 18techni-Contents at a Glance
Preface vii
Acknowledgments xv
Part I Basic Information Chapter 1 Excel in a Nutshell 3
Chapter 2 Basic Facts about Formulas 29
Chapter 3 Working with Names 57
Part II Using Functions in Your Formulas Chapter 4 Introducing Worksheet Functions 97
Chapter 5 Manipulating Text 113
Chapter 6 Working with Dates and Times 139
Chapter 7 Counting and Summing Techniques 179
Chapter 8 Lookups 211
Chapter 9 Databases and Lists 237
Chapter 10 Miscellaneous Calculations 269
Part III Financial Formulas Chapter 11 Introducing Financial Formulas 293
Chapter 12 Discounting and Depreciation Financial Functions 329
Chapter 13 Advanced Uses of Financial Functions and Formulas 351
Part IV Array Formulas Chapter 14 Introducing Arrays 375
Chapter 15 Performing Magic with Array Formulas 397
Part V Miscellaneous Formula Techniques Chapter 16 Intentional Circular References 425
Chapter 17 Charting Techniques 441
Chapter 18 Pivot Tables 489
Chapter 19 Conditional Formatting and Data Validation 513
Chapter 20 Creating Megaformulas 541
Chapter 21 Tools and Methods for Debugging Formulas 559
Trang 19Part VI Developing Custom Worksheet Functions
Chapter 22 Introducing VBA 587
Chapter 23 Function Procedure Basics 599
Chapter 24 VBA Programming Concepts 619
Chapter 25 VBA Custom Function Examples 653
Appendixes Appendix A Working with Imported 1-2-3 Files 699
Appendix B Excel Function Reference 717
Appendix C Using Custom Number Formats 733
Appendix D Additional Excel Resources 759
Appendix E What’s on the CD-ROM 765
Index 777
End-User License Agreement 825
CD-ROM Installation Instructions 828
Trang 20Preface vii
Acknowledgments xv
Part I Basic Information Chapter 1 Excel in a Nutshell 3
The History of Excel 4
It Started with VisiCalc 4
Then Came Lotus 4
Microsoft Enters the Picture 4
Excel Versions 5
The Object Model Concept 7
The Workings of Workbooks 7
Worksheets 9
Chart Sheets 10
XLM Macro Sheets 10
Dialog Sheets 10
Excel’s User Interface 11
Menus 11
Shortcut Menus 11
Smart Tags 12
Dialog Boxes 12
Toolbars 13
Drag-and-Drop 13
Keyboard Shortcuts 14
Customized On-screen Display 14
Data Entry 14
Object and Cell Selecting 14
Cell Formatting 16
Numeric Formatting 16
Stylistic Formatting 16
Worksheet Formulas and Functions 17
Objects on the Draw Layer 18
Shapes 18
Diagrams 18
Linked Picture Objects 19
Maps 19
Dialog Box Controls 19
Charts 20
Trang 21Customization in Excel 20
Macros 20
Toolbars 21
Add-in Programs 21
Analysis Tools 21
Database Access 22
Outlines 23
Scenario Management 23
Analysis ToolPak 24
Pivot Tables 24
Auditing Capabilities 24
Solver Add-in 24
Protection Options 25
Protecting Formulas from Being Overwritten 25
Protecting a Workbook’s Structure 26
Chapter 2 Basic Facts about Formulas 29
Entering and Editing Formulas 29
Formula Elements 29
Entering a Formula 30
Pasting Names 32
Spaces and Line Breaks 32
Formula Limits 32
Sample Formulas 33
Editing Formulas 34
Using Operators in Formulas 35
Reference Operators 36
Sample Formulas That Use Operators 36
Operator Precedence 38
Nested Parentheses 39
Calculating Formulas 40
Cell and Range References 42
Creating an Absolute Reference 42
Referencing Other Sheets or Workbooks 44
Making an Exact Copy of a Formula 45
Converting Formulas to Values 46
Hiding Formulas 48
Errors in Formulas 49
Dealing with Circular References 51
Goal Seeking 53
A Goal-Seeking Example 53
More about Goal Seeking 54
Chapter 3 Working with Names 57
What’s in a Name? 57
Methods for Creating Cell and Range Names 58
Creating Names Using the Define Name Dialog Box 58
Creating Names Using the Name Box 59
Trang 22Creating Names Automatically 61 Naming Entire Rows and Columns 63 Names Created by Excel 64
Creating Multisheet Names 65
A Name’s Scope 66
Creating Worksheet-Level Names 67 Combining Worksheet- and Workbook-Level Names 67 Referencing Names from Another Workbook 68
Working with Range and Cell Names 68
Creating a List of Names 68 Using Names in Formulas 69 Using the Intersection Operators with Names 70 Using the Range Operator with Names 72 Referencing a Single Cell in a Multicell Named Range 73 Applying Names to Existing Formulas 73 Applying Names Automatically when Creating a Formula 74 Unapplying Names 74 Deleting Names 75 Deleting Named Cells or Ranges 75 Redefining Names 76 Changing Names 76 Viewing Named Ranges 76 Using Names in Charts 77
How Excel Maintains Cell and Range Names 77
Inserting a Row or Column 77 Deleting a Row or Column 77 Cutting and Pasting 78
Potential Problems with Names 78
Name Problems When Copying Sheets 78 Name Problems when Deleting Sheets 79
The Secret to Understanding Names 80
Naming Constants 81 Naming Text Constants 82 Using Worksheet Functions in Named Formulas 83 Using Cell and Range References in Named Formulas 84 Using Named Formulas with Relative References 85
Advanced Techniques That Use Names 88
Using the INDIRECT Function with a Named Range 88 Using the INDIRECT Function to Create a Named Range
with a Fixed Address 89 Using Arrays in Named Formulas 90 Creating a Dynamic Named Formula 91
Trang 23Part II Using Functions in Your Formulas
Chapter 4 Introducing Worksheet Functions 97
What Is a Function? 97
Simplify Formulas 98 Perform Otherwise Impossible Calculations 98 Speed Up Editing Tasks 98 Provide Decision-Making Capability 99 More about Functions 99
Function Argument Types 99
Names as Arguments 100 Full-Column or Full-Row as Arguments 101 Literal Values as Arguments 102 Expressions as Arguments 102 Other Functions as Arguments 102 Arrays as Arguments 103
Ways to Enter a Function into a Formula 103
Entering a Function Manually 104 Using the Insert Function Dialog Box to Enter a Function 104 More Tips for Entering Functions 106
Function Categories 109
Financial Functions 109 Date & Time Functions 109 Math & Trig Functions 109 Statistical Functions 109 Lookup and Reference Functions 110 Database Functions 110 Text Functions 110 Logical Functions 110 Information Functions 110 Engineering Functions 110 User-Defined Functions 111 Other Function Categories 111 Analysis ToolPak Functions 112
Chapter 5 Manipulating Text 113
A Few Words about Text 113
How Many Characters in a Cell? 113 Numbers as Text 114
Text Functions 115
Determining Whether a Cell Contains Text 115 Working with Character Codes 117 Determining Whether Two Strings Are Identical 119 Joining Two or More Cells 120 Displaying Formatted Values as Text 121
Trang 24Displaying Formatted Currency Values as Text 122 Repeating a Character or String 123 Creating a Text Histogram 123 Padding a Number 124 Removing Excess Spaces and Nonprinting Characters 125 Counting Characters in a String 126 Changing the Case of Text 126 Extracting Characters from a String 127 Replacing Text with Other Text 127 Finding and Searching within a String 128 Searching and Replacing within a String 129
Advanced Text Formulas 130
Counting Specific Characters in a Cell 130 Counting the Occurrences of a Substring in a Cell 130 Expressing a Number as an Ordinal 131 Determining a Column Letter for a Column Number 132 Extracting a Filename from a Path Specification 132 Extracting the First Word of a String 133 Extracting the Last Word of a String 133 Extracting All but the First Word of a String 133 Extracting First Names, Middle Names, and Last Names 134 Removing Titles from Names 135 Counting the Number of Words in a Cell 135
Custom VBA Text Functions 136
Chapter 6 Working with Dates and Times 139
How Excel Handles Dates and Times 139
Understanding Date Serial Numbers 140 Entering Dates 141 Understanding Time Serial Numbers 142 Entering Times 144 Formatting Dates and Times 145 Problems with Dates 147
Date-Related Functions 149
Displaying the Current Date 150 Displaying Any Date 151 Generating a Series of Dates 152 Converting a Non-Date String to a Date 153 Calculating the Number of Days between Two Dates 153 Calculating the Number of Work Days between Two Dates 154 Offsetting a Date Using Only Work Days 156 Calculating the Number of Years between Two Dates 156 Calculating a Person’s Age 156 Determining the Day of the Year 157 Determining the Day of the Week 158 Determining the Date of the Most Recent Sunday 160
Trang 25Determining the First Day of the Week after a Date 160 Determining the nth Occurrence of a Day of the Week
in a Month 160 Counting the Occurrences of a Day of the Week 161 Expressing a Date as an Ordinal Number 162 Calculating Dates of Holidays 163 Determining the Last Day of a Month 165 Determining Whether a Year Is a Leap Year 165 Determining a Date’s Quarter 166 Converting a Year to Roman Numerals 166 Creating a Calendar in a Range 166
Time-Related Functions 167
Displaying the Current Time 168 Displaying Any Time 169 Summing Times That Exceed 24 Hours 170 Calculating the Difference between Two Times 172 Converting from Military Time 174 Converting Decimal Hours, Minutes, or Seconds to a Time 174 Adding Hours, Minutes, or Seconds to a Time 175 Converting between Time Zones 175 Rounding Time Values 176 Working with Non–Time-of-Day Values 177
Chapter 7 Counting and Summing Techniques 179
Counting and Summing Worksheet Cells 179 Counting or Summing Records in Databases
and Pivot Tables 181 Basic Counting Formulas 182
Counting the Total Number of Cells 183 Counting Blank Cells 183 Counting Nonblank Cells 184 Counting Numeric Cells 185 Counting Nontext Cells 185 Counting Text Cells 185 Counting Logical Values 185 Error Values in a Range 185
Advanced Counting Formulas 186
Counting Cells Using the COUNTIF Function 186 Counting Cells Using Multiple Criteria 188 Counting the Most Frequently Occurring Entry 191 Counting the Occurrences of Specific Text 192 Counting the Number of Unique Values 193 Creating a Frequency Distribution 195
Summing Formulas 201
Summing All Cells in a Range 201 Computing a Cumulative Sum 202 Summing the “Top n” Values 204
Trang 26Conditional Sums Using a Single Criterion 204
Summing Only Negative Values 206 Summing Values Based on a Different Range 206 Summing Values Based on a Text Comparison 207 Summing Values Based on a Date Comparison 207
Conditional Sums Using Multiple Criteria 208
Using And Criteria 208 Using Or Criteria 209 Using And and Or Criteria 209
Using VBA Functions to Count and Sum 210
Chapter 8 Lookups 211
What Is a Lookup Formula? 211 Functions Relevant to Lookups 212 Basic Lookup Formulas 213
The VLOOKUP Function 213 The HLOOKUP Function 215 The LOOKUP Function 216 Combining the MATCH and INDEX Functions 217
Specialized Lookup Formulas 219
Looking Up an Exact Value 220 Looking Up a Value to the Left 221 Performing a Case-Sensitive Lookup 222 Choosing among Multiple Lookup Tables 223 Determining Letter Grades for Test Scores 224 Calculating a Grade Point Average 225 Performing a Two-Way Lookup 226 Performing a Two-Column Lookup 228 Determining the Address of a Value within a Range 229 Looking Up a Value Using the Closest Match 230 Looking Up a Value Using Linear Interpolation 231
Chapter 9 Databases and Lists 237
Worksheet Lists or Databases 237 Using AutoFiltering 240
AutoFiltering Basics 240 Counting and Summing Filtered Data 242 Copying and Deleting Filtered Data 243
Using Advanced Filtering 244
Setting Up a Criteria Range 246 Filtering a List 247
Specifying Advanced Filter Criteria 248
Specifying a Single Criterion 249 Specifying Multiple Criteria 253 Specifying Computed Criteria 255
Using Database Functions with Lists 258 Summarizing a List with a Data Table 261 Creating Subtotals 264
Trang 27Chapter 10 Miscellaneous Calculations 269
Unit Conversions 269
Using the Unit Conversion Tables 269 Converting Metric Units 270 Distance Conversions 272 Weight Conversions 272 Liquid Measurement Conversions 272 Surface Conversions 272 Volume Conversions 272 Force Conversions 272 Energy Conversions 272 Time Conversions 272 Temperature Conversions 277
Solving Right Triangles 277 Area, Surface, Circumference,
and Volume Calculations 280
Calculating the Area and Perimeter of a Square 280 Calculating the Area and Perimeter of a Rectangle 281 Calculating the Area and Perimeter of a Circle 281 Calculating the Area of a Trapezoid 281 Calculating the Area of a Triangle 281 Calculating the Surface and Volume of a Sphere 282 Calculating the Surface and Volume of a Cube 282 Calculating the Surface and Volume of a Cone 282 Calculating the Volume of a Cylinder 282 Calculating the Volume of a Pyramid 283
Solving Simultaneous Equations 283 Rounding Numbers 285
Basic Rounding Formulas 286 Rounding to the Nearest Multiple 287 Rounding Dollar Values 287 Working with Fractional Dollars 288 Using the INT and TRUNC Functions 288 Rounding to an Even or Odd Integer 289 Rounding to n Significant Digits 290
Part III Financial Formulas
Chapter 11 Introducing Financial Formulas 293
Excel’s Basic Financial Functions 293 Signing of Money Flows Convention 295 Accumulation, Discounting, and
Amortization Functions 296
Simple Accumulation Problems 297 Complex Accumulation Problems 301 Simple Discounting Problems 303
Trang 28Complex Discounting Problems 307 Amortization Problems 308
Converting Interest Rates 313
Methods of Quoting Interest Rates 313 Converting Interest Rates Using
the Financial Functions Add-in 314
Effective Cost of Loans 317
Impact of Fees and Charges upon Effective Interest 317
“Flat” Rate Loans 319 Interest-Free Loans 319
“Annual Payments / 12” Loan Costs 320
Calculating the Interest and Principal Components 320
Using the IPMT and PPMT Functions 321 Using the CUMIPMT and CUMPRINC Functions 323
Matching Different Interest and Payment Frequencies 324 Limitations of Excel’s Financial Functions 325
Deferred Start to a Series of Regular Payments 326 Valuing a Series of Regular Payments 326
Chapter 12 Discounting and Depreciation
Financial Functions 329
Using the NPV Function 329
Definition of NPV 330 NPV Function Examples 330 Using the NPV Function to Calculate
Accumulated Amounts 337
Using the IRR Function 339 Multiple Rates of IRR and the MIRR Function 342 Using the FVSCHEDULE Function 346 Depreciation Calculations 347
Chapter 13 Advanced Uses of Financial Functions
and Formulas 351
Creating Dynamic Financial Schedules 351 Creating Amortization Schedules 352
A Simple Amortization Schedule 352
A Detailed Amortization Schedule 355
A Variable Loan Rate Amortization Schedule 356
Summarizing Loan Options Using a Data Table 358
Creating a One-Way Data Table 358 Creating a Two-Way Data Table 360
Accumulation Schedules 361 Discounted Cash Flow Schedules 363 Credit Card Calculations 365 XIRR and XNPV Functions 366 Variable Rate Analysis 369 Creating Indices 370
Trang 29Part IV Array Formulas
Chapter 14 Introducing Arrays 375
Introducing Array Formulas 375
A Multicell Array Formula 376
A Single-Cell Array Formula 377 Creation of an Array Constant 378 Array Constant Elements 379
Understanding the Dimensions of an Array 379
One-Dimensional Horizontal Arrays 379 One-Dimensional Vertical Arrays 380 Two-Dimensional Arrays 380
Naming Array Constants 381 Working with Array Formulas 383
Entering an Array Formula 383 Selecting an Array Formula Range 383 Editing an Array Formula 384 Expanding or Contracting a Multicell Array Formula 385
Using Multicell Array Formulas 386
Creating an Array from Values in a Range 386 Creating an Array Constant from Values in a Range 386 Performing Operations on an Array 387 Using Functions with an Array 388 Transposing an Array 388 Generating an Array of Consecutive Integers 389
Using Single-Cell Array Formulas 390
Counting Characters in a Range 391 Summing the Three Smallest Values in a Range 392 Counting Text Cells in a Range 392 Eliminating Intermediate Formulas 394 Using an Array in Lieu of a Range Reference 395
Chapter 15 Performing Magic with Array Formulas 397
Working with Single-Cell Array Formulas 397
Summing a Range That Contains Errors 398 Counting the Number of Error Values in a Range 398 Summing Based on a Condition 399 Summing the n Largest Values in a Range 402 Computing an Average That Excludes Zeros 402 Determining Whether a Particular Value
Appears in a Range 403 Counting the Number of Differences in Two Ranges 404 Returning the Location of the Maximum Value in a Range 404 Finding the Row of a Value’s nth Occurrence in a Range 405 Returning the Longest Text in a Range 405
Trang 30Determining Whether a Range Contains Valid Values 406 Summing the Digits of an Integer 406 Summing Rounded Values 408 Summing Every nth Value in a Range 409 Removing Non-Numeric Characters from a String 410 Determining the Closest Value in a Range 410 Returning the Last Value in a Column 410 Returning the Last Value in a Row 412 Ranking Data with an Array Formula 412 Creating a Dynamic Crosstab Table 413
Working with Multicell Array Formulas 414
Returning Only Positive Values from a Range 414 Returning Nonblank Cells from a Range 415 Reversing the Order of the Cells in a Range 415 Sorting a Range of Values Dynamically 416 Returning a List of Unique Items in a Range 416 Displaying a Calendar in a Range 417
Returning an Array from a Custom VBA Function 418
Part V Miscellaneous Formula Techniques
Chapter 16 Intentional Circular References 425
What Are Circular References? 425
Correcting an Accidental Circular Reference 426 Understanding Indirect Circular References 427
Intentional Circular References 428 How Excel Determines Calculation
and Iteration Settings 430 Circular Reference Examples 431
Time Stamping a Cell Entry 432 Calculating an All-Time-High Value 432 Generating Unique Random Integers 433 Solving a Recursive Equation 435 Solving Simultaneous Equations Using
a Circular Reference 436
Potential Problems with Intentional Circular References 438
Chapter 17 Charting Techniques 441
Representing Data in Charts 441
Understanding the SERIES Formula 441 Creating Links to Cells 445 Charting Progress toward a Goal 448 Creating a Gantt Chart 449 Creating a Comparative Histogram 451
Trang 31Creating a Box Plot 453 Plotting Every nth Data Point 455 Updating a Data Series Automatically 457 Plotting the Last n Data Points 458
Plotting Data Interactively 460
Plotting Based on the Active Row 460 Selecting Data from a Combo Box 461 Plotting Functions with One Variable 462 Plotting Functions with Two Variables 466
Creating Awesome Designs 468 Working with Trendlines 469
Linear Trendlines 470 Nonlinear Trendlines 474
Useful Chart Tricks 479
Storing Multiple Charts on a Chart Sheet 479 Viewing an Embedded Chart in a Window 480 Changing a Worksheet Value by Dragging a Data Point 480 Using Animated Charts 481 Creating a “Gauge” Chart 482 Creating a “Clock” Chart 483 Drawing with an XY Chart 486
Chapter 18 Pivot Tables 489
About Pivot Tables 489
A Pivot Table Example 490 Data Appropriate for a Pivot Table 493
Creating a Pivot Table 495
Step1: Specifying the Data Location 495 Step 2: Specifying the Data 496 Step 3: Completing the Pivot Table 497
Grouping Pivot Table Items 503 Creating a Calculated Field or Calculated Item 506
Creating a Calculated Field in a Pivot Table 507 Inserting a Calculated Item into a Pivot Table 509
Chapter 19 Conditional Formatting and Data Validation 513
Conditional Formatting 513
Specifying Conditional Formatting 514 Formatting Types You Can Apply 515 Specifying Conditions 516 Working with Conditional Formats 518 Conditional Formatting Formulas 521 Using Custom Functions in Conditional
Formatting Formulas 530
Trang 32Data Validation 533
Specifying Validation Criteria 534 Types of Validation Criteria You Can Apply 536 Using Formulas for Data Validation Rules 537 Using Data Validation Formulas to Accept Only
Specific Entries 538
Chapter 20 Creating Megaformulas 541
What Is a Megaformula? 541 Creating a Megaformula: A Simple Example 542 Megaformula Examples 544
Using a Megaformula to Remove Middle Names 544 Using a Megaformula to Return a String’s Last Space
Character Position 548 Using a Megaformula to Determine the Validity
of a Credit Card Number 552
The Pros and Cons of Megaformulas 557
Chapter 21 Tools and Methods for Debugging Formulas 559
Formula Debugging? 559 Formula Problems and Solutions 560
Mismatched Parentheses 561 Cells Are Filled with ########## 562 Blank Cells Are Not Blank 563 Formulas Returning an Error 563 Absolute/Relative Reference Problems 567 Operator Precedence Problems 568 Formulas Are Not Calculated 569 Actual versus Displayed Values 570 Floating Point Number Errors 571
“Phantom Link” Errors 572 Circular Reference Errors 572
Excel’s Auditing Tools 572
Identifying Cells of a Particular Type 573 Viewing Formulas 573 Tracing Cell Relationships 575 Tracing Error Values 577 Fixing Circular Reference Errors 577 Using Excel 2002’s Background Error Checking Feature 578 Using Excel 2002’s Formula Evaluator 580
Third-Party Auditing Tools 580
Power Utility Pak 581 Spreadsheet Detective 582 Excel Auditor 582
Trang 33Part VI Developing Custom Worksheet Functions
Chapter 22 Introducing VBA 587
About VBA 587 Introducing the Visual Basic Editor 588
Activating the VB Editor 588 The VB Editor Components 589 Using the Project Window 590 Using Code Windows 593 Entering VBA Code 595 Saving Your Project 598
Chapter 23 Function Procedure Basics 599
Why Create Custom Functions? 599
An Introductory VBA Function Example 600 About Function Procedures 602
Declaring a Function 602 Choosing a Name for Your Function 603 Using Functions in Formulas 604 Using Function Arguments 605
Using the Insert Function Dialog Box 605
Adding a Function Description 606 Specifying a Function Category 607
Testing and Debugging Your Functions 609
Using VBA’s MsgBox Statement 610 Using Debug.Print Statements in Your Code 612 Calling the Function from a Sub Procedure 613 Setting a Breakpoint in the Function 616
Creating Add-Ins 616
Chapter 24 VBA Programming Concepts 619
An Introductory Example Function Procedure 619 Using Comments in Your Code 622 Using Variables, Data Types, and Constants 622
Defining Data Types 623 Declaring Variables 624 Using Constants 626 Using Strings 627 Using Dates 627
Using Assignment Expressions 628 Using Arrays 629
Declaring an Array 630 Declaring Multidimensional Arrays 630
Using VBA’s Built-in Functions 631 Controlling Execution 633
The If-Then Construct 633 The Select Case Construct 635
Trang 34Looping Blocks of Instructions 636 The On Error Statement 641
Using Ranges 643
The For Each-Next Construct 643 Referencing a Range 644 Some Useful Properties of Ranges 646 The Set Keyword 649 The Intersect Function 650 The Union Function 651 The UsedRange Property 651
Chapter 25 VBA Custom Function Examples 653
Determining a Cell’s Data Type 659
A Multifunctional Function 660 Generating Random Numbers 662
Generating Random Numbers That Don’t Change 663 Selecting a Cell at Random 663
Calculating Sales Commissions 664
A Function for a Simple Commission Structure 665
A Function for a More Complex Commission Structure 666
Text Manipulation Functions 668
Reversing a String 668 Scrambling Text 669 Returning an Acronym 669 Does the Text Match a Pattern? 670 Does a Cell Contain Text? 671 Extracting the nth Element from a String 672 Spelling Out a Number 674
Counting and Summing Functions 674
Counting Cells Between Two Values 675 Counting Visible Cells in a Range 675 Summing Visible Cells in a Range 676
Date Functions 677
Calculating the Next Monday 677 Calculating the Next Day of the Week 678 Which Week of the Month? 678 Working with Dates Before 1900 679
Trang 35Returning the Last Nonempty Cell
Advanced Function Techniques 685
Returning an Error Value 685 Returning an Array from a Function 687 Returning an Array of Nonduplicated Random Integers 689 Randomizing a Range 691 Using Optional Arguments 693 Using an Indefinite Number of Arguments 694
Appendixes
Appendix A Working with Imported 1-2-3 Files 699
About 1-2-3 Files 699 Lotus 1-2-3 Formulas 700
Calculation Order 701 Text in Calculations 702 Logical Values 702 Date Problems 703 Database Criteria 703
Lotus 1-2-3 Function Compatibility 704
Function Equivalents 704 Converting Database Functions 714
Appendix B Excel Function Reference 717
Excel Functions by Category 717
Appendix C Using Custom Number Formats 733
About Number Formatting 733
Automatic Number Formatting 733 Formatting Numbers Using Toolbar Buttons 734 Using Shortcut Keys to Format Numbers 735 Using the Format Cells Dialog Box to Format Numbers 736
Creating a Custom Number Format 738
About Custom Number Formats 738 Parts of a Number Format String 739 Custom Number Format Codes 740
Custom Number Format Examples 742
Scaling Values 742 Hiding Zeros 746 Displaying Leading Zeros 747 Formatting Percentages 747
Trang 36Displaying Fractions 748 Displaying N/A for Text 749 Displaying Text in Quotes 749 Repeating Text 749 Displaying a Negative Sign on the Right 750 Conditional Number Formatting 750 Coloring Values 751 Formatting Dates and Times 752 Displaying Text with Numbers 753 Displaying a Zero with Dashes 753 Using Special Symbols 754 Suppressing Certain Types of Entries 755 Filling a Cell with a Repeating Character 756 Displaying Leading Dots 757
Appendix D Additional Excel Resources 759
Microsoft Technical Support 759
Support Options 759 Microsoft Knowledge Base 759 Microsoft Excel Home Page 760 Microsoft Office Tools on the Web 760
Internet Newsgroups 760
Spreadsheet Newsgroups 761 Microsoft Newsgroups 761 Searching Newsgroups 762
Internet Web sites 763
The Spreadsheet Page 763 Excel Web Source 764 Stephen Bullen’s Excel Page 764 Spreadsheet FAQ 764
Appendix E What’s on the CD-ROM 765
CD-ROM Overview 765 Chapter Examples 766
Chapter 5 766 Chapter 6 766 Chapter 7 767 Chapter 8 767 Chapter 9 768 Chapter 10 768 Chapter 11 768 Chapter 12 769 Chapter 13 769 Chapter 15 770 Chapter 16 770 Chapter 17 771 Chapter 18 772
Trang 37Chapter 19 772 Chapter 20 772 Chapter 25 773
Power Utility Pak 773
Registering Power Utility Pak 774 Installing the trial version 774 Uninstalling Power Utility Pak 774
End-User License Agreement 825
CD-ROM Installation Instructions 828
Trang 40Chapter 1
Excel in a Nutshell
IN THIS CHAPTER
◆ A brief history of Excel
◆ The object model concept in Excel
◆ The workings of workbooks
◆ The user interface
◆ The two types of cell formatting
◆ Worksheet formulas and functions
◆ Objects on the worksheet’s invisible drawer layer
◆ Macros, toolbars, and add-ins for Excel customization
◆ Analysis tools
◆ Protection options
M ICROSOFT E XCEL HAS BEEN REFERRED TOas “the best application ever written forWindows.” You may or may not agree with that statement, but you can’t deny that
Excel is one of the oldest Windows products and has undergone many
reincarna-tions and face-lifts over the years Cosmetically, the current version — Excel 2002 —barely even resembles the original version (which, by the way, was written for theMacintosh) However, many of Excel’s key elements have remained intact over theyears, with significant enhancements, of course
This chapter presents a concise overview of the features available in the morerecent versions of Excel, with specific emphasis on Excel 2002 It sets the stage forthe subsequent chapters and provides a transition for those who have used otherspreadsheet products and are moving up to Excel Hard-core Lotus 1-2-3 users, forexample, usually need some help to start thinking in Excel’s terms
If you’re an old hand at Excel, you may want to ignore this chapter or just skim through it quickly.
3