COMPUTERS/Spreadsheets
$49.99 US • $59.99 CAN
Follow Mr. Spreadsheet’s formula for Excel success
Excel 2010 Microsoft
® ®
CD-ROM INCLUDES: • Workbook files for all examples used in the book • The entire book in a searchable PDF file See Appendix D for complete system requirements.
• Master the new functionality in Excel 2010 • Understand and use various lookup formulas • Create financial formulas for borrowing or investing • Work with formulas for conditional formatting • Develop custom worksheet functions using VBA
®
Let Mr. Spreadsheet show you how to:
®
You’ll learn how to apply formulas to charts and pivot tables, troubleshoot your formulas, develop custom functions, and much more.
Microsoft
First, he shows you exactly what a formula is, how to create one, and what formulas can do. Then you’ll learn about using functions in your formulas. Finally you’ll explore specific types of formulas that can help you on multiple levels, such as financial and array formulas.
John Walkenbach, arguably the foremost authority on Excel, has written hundreds of articles and created the award-winning Power Utility Pak. His 50-plus books include Excel 2010 Power Programming with VBA, John Walkenbach's Favorite Excel 2010 Tips & Tricks, and the Excel 2010 Bible, all published by Wiley. Visit his popular Spreadsheet Page at spreadsheetpage.com.
CD-ROM INCLUDED
Excel 2010 Formulas
Experts estimate that barely 10 percent of Excel users understand how to make the most of worksheet formulas. If you already know your way around Excel basics, “Mr. Spreadsheet” John Walkenbach can help you master formulas to gain greater Excel functionality.
®
Formulas
John Walkenbach
Walkenbach
Visit Mr. Spreadsheet’s Web site at spreadsheetpage.com
BONUS CD-ROM! Includes all Excel workbook files used in the book, plus the complete book in a searchable PDF file
01_475362-ffirs.indd iii
4/14/10 9:13 PM
Excel® 2010 Formulas by John Walkenbach
01_475362-ffirs.indd i
4/14/10 9:13 PM
Excel® 2010 Formulas Published by Wiley Publishing, Inc. 111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 7486011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. Excel is a registered trademark of Microsoft Corporation in the United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. FULFILLMENT OF EACH COUPON OFFER IS THE SOLE RESPONSIBILITY OF THE OFFEROR.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit www.wiley.com/techsupport. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2010925706 ISBN: 978-0-470-47536-2 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1
01_475362-ffirs.indd ii
4/14/10 9:13 PM
About the Author John Walkenbach is a leading authority on spreadsheet software, and principal of J-Walk and Associates Inc., a one-person consulting firm based in southern Arizona. John has received a Microsoft MVP award every year since 2000. He’s the author of more than 50 spreadsheet books, and has written more than 300 articles and reviews for a variety of publications, including PC World, InfoWorld, PC Magazine, Windows, and PC/Computing. John also maintains a popular Web site (The Spreadsheet Page, http://spreadsheetpage.com), and is the developer of several Excel utilities, including the Power Utility Pak, an award-winning add-in for Excel. John graduated from the University of Missouri, and earned a Masters and PhD from the University of Montana.
01_475362-ffirs.indd iii
4/14/10 9:13 PM
Publisher’s Acknowledgments We’re proud of this book; please send us your comments at http://dummies.custhelp. com. For other comments, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media Development Project Editor: Susan B. Cohen Acquisitions Editor: Katie Mohr Copy Editor: Susan B. Cohen Technical Editor: Niek Otten Editorial Manager: Jodi Jensen
Composition Services Project Coordinator: Katherine Crocker Layout and Graphics: Beth Brooks, Jennifer Mayberry, Ronald G. Terry, Erin Zeltner Proofreaders: Laura Albert, Laura L. Bowman Indexer: Christine Karpeles
Media Development Assistant Project Manager: Jenny Swisher Media Development Associate Producer: Marilyn Hummel Editorial Assistant: Amanda Graham Sr. Editorial Assistant: Cherie Case
Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary Bednarek, Executive Acquisitions Director Mary C. Corder, Editorial Director
Publishing for Consumer Dummies Diane Graves Steele, Vice President and Publisher
Composition Services Debbie Stailey, Director of Composition Services
01_475362-ffirs.indd iv
4/14/10 9:13 PM
Contents at a Glance Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Part I: Basic Information Chapter 1: Excel in a Nutshell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Chapter 2: Basic Facts about Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Chapter 3: Working with Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Part II: Using Functions in Your Formulas Chapter 4: Introducing Worksheet Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Chapter 5: Manipulating Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Chapter 6: Working with Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143 Chapter 7: Counting and Summing Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Chapter 8: Using Lookup Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .213 Chapter 9: Tables and Worksheet Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Chapter 10: Miscellaneous Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Part III: Financial Formulas Chapter 11: Borrowing and Investing Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Chapter 12: Discounting and Depreciation Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .317 Chapter 13: Financial Schedules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .341
Part IV: Array Formulas Chapter 14: Introducing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Chapter 15: Performing Magic with Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391
Part V: Miscellaneous Formula Techniques Chapter 16: Intentional Circular References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .415 Chapter 17: Charting Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 Chapter 18: Pivot Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 Chapter 19: Conditional Formatting and Data Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .519 Chapter 20: Creating Megaformulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 Chapter 21: Tools and Methods for Debugging Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Part VI: Developing Custom Worksheet Functions Chapter 22: Introducing VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 Chapter 23: Function Procedure Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .613 Chapter 24: VBA Programming Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635 Chapter 25: VBA Custom Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
02_475362-ftoc.indd v
4/14/10 9:14 PM
vi
Part VII: Appendixes Appendix A: Excel Function Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .717 Appendix B: Using Custom Number Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733 Appendix C: Additional Excel Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753 Appendix D: What’s on the CD-ROM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
02_475362-ftoc.indd vi
4/14/10 9:14 PM
Table of Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What You Need to Know . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What You Need to Have . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Conventions in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Keyboard conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Mouse conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 What the icons mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 How This Book Is Organized. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Part I: Basic Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Part II: Using Functions in Your Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Part III: Financial Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Part IV: Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Part V: Miscellaneous Formula Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Part VI: Developing Custom Worksheet Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Part VII: Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 How to Use This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 About the Companion CD-ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 About the Power Utility Pak Offer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Reach Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Part I: Basic Information Chapter 1: Excel in a Nutshell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 The History of Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 It started with VisiCalc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 Then came Lotus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 Microsoft enters the picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 Excel versions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13 The Object Model Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 The Workings of Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Worksheets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Chart sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 Macro sheets and dialog sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 The Excel User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 A new UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 The Ribbon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 Backstage View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21 Shortcut menus and the Mini Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Customizing the UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Smart Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Task pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Drag and drop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
02_475362-ftoc.indd vii
4/14/10 9:14 PM
viii Keyboard shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Customized on-screen display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Data entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Object and cell selecting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 The Excel Help System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Cell Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Numeric formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Stylistic formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Worksheet Formulas and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Objects on the Drawing Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31 Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31 Illustrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31 Linked picture objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31 Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Sparkline graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Customizing Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Add-in programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Internet Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Analysis Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Database access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Outlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Scenario management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Pivot tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Auditing capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Solver add-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Protection Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Protecting formulas from being overwritten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Protecting a workbook’s structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Password-protecting a workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Chapter 2: Basic Facts about Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Entering and Editing Formulas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Formula elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Entering a formula. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Pasting names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41 Spaces and line breaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Formula limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Sample formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Editing formulas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Using Operators in Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Reference operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Sample formulas that use operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Operator precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Nested parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
02_475362-ftoc.indd viii
4/14/10 9:14 PM
ix Calculating Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Cell and Range References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51 Creating an absolute or a mixed reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Referencing other sheets or workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Making an Exact Copy of a Formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Converting Formulas to Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Hiding Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Errors in Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Dealing with Circular References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Goal Seeking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61 A goal seeking example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 More about goal seeking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Chapter 3: Working with Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 What’s in a Name? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 A Name’s Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Referencing names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Referencing names from another workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Conflicting names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 The Name Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Creating names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Editing names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Deleting names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Shortcuts for Creating Cell and Range Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 The New Name dialog box. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Creating names using the Name box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Creating names automatically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Naming entire rows and columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Names created by Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Creating Multisheet Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Working with Range and Cell Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Creating a list of names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Using names in formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Using the intersection operators with names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Using the range operator with names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81 Referencing a single cell in a multicell named range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81 Applying names to existing formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Applying names automatically when creating a formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Unapplying names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Names with errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Viewing named ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Using names in charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 How Excel Maintains Cell and Range Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Inserting a row or column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Deleting a row or column. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Cutting and pasting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
02_475362-ftoc.indd ix
4/14/10 9:14 PM
x Potential Problems with Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Name problems when copying sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Name problems when deleting sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 The Secret to Understanding Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Naming constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Naming text constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Using worksheet functions in named formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Using cell and range references in named formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91 Using named formulas with relative references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Advanced Techniques That Use Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Using the INDIRECT function with a named range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Using the INDIRECT function to create a named range with a fixed address. . . . . . . . . . . . 97 Using arrays in named formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Creating a dynamic named formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Part II: Using Functions in Your Formulas Chapter 4: Introducing Worksheet Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Simplify your formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Perform otherwise impossible calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Speed up editing tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Provide decision-making capability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 More about functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Function Argument Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Names as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Full-column or full-row as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Literal values as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Expressions as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Other functions as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Arrays as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Ways to Enter a Function into a Formula. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Entering a function manually. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Using the Function Library commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Using the Insert Function dialog box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 More tips for entering functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Function Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Financial functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Date and time functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Math and trig functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Statistical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Lookup and reference functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Database functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Text functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Logical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Information functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 User-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
02_475362-ftoc.indd x
4/14/10 9:14 PM
xi Engineering functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Cube functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Compatibility functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Other function categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Chapter 5: Manipulating Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 A Few Words about Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 How many characters in a cell?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Numbers as text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Text Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Determining whether a cell contains text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Working with character codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122 Determining whether two strings are identical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124 Joining two or more cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125 Displaying formatted values as text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126 Displaying formatted currency values as text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127 Removing excess spaces and nonprinting characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128 Counting characters in a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128 Repeating a character or string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129 Creating a text histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129 Padding a number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Changing the case of text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Extracting characters from a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132 Replacing text with other text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133 Finding and searching within a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .134 Searching and replacing within a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .134 Advanced Text Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135 Counting specific characters in a cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135 Counting the occurrences of a substring in a cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135 Removing trailing minus signs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136 Expressing a number as an ordinal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136 Determining a column letter for a column number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137 Extracting a filename from a path specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Extracting the first word of a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Extracting the last word of a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Extracting all but the first word of a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139 Extracting first names, middle names, and last names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139 Removing titles from names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Counting the number of words in a cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142
Chapter 6: Working with Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143 How Excel Handles Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143 Understanding date serial numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 Entering dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145 Understanding time serial numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Entering times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .147 Formatting dates and times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Problems with dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
02_475362-ftoc.indd xi
4/14/10 9:14 PM
xii Date-Related Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152 Displaying the current date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152 Displaying any date. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153 Generating a series of dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .154 Converting a non-date string to a date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155 Calculating the number of days between two dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156 Calculating the number of work days between two dates . . . . . . . . . . . . . . . . . . . . . . . . . . .157 Offsetting a date using only work days . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158 Calculating the number of years between two dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158 Calculating a person’s age . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Determining the day of the year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Determining the day of the week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Determining the date of the most recent Sunday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Determining the first day of the week after a date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162 Determining the nth occurrence of a day of the week in a month . . . . . . . . . . . . . . . . . . . . .162 Counting the occurrences of a day of the week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .163 Expressing a date as an ordinal number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Calculating dates of holidays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Determining the last day of a month . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .168 Determining whether a year is a leap year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .168 Determining a date’s quarter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .168 Converting a year to roman numerals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Time-Related Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Displaying the current time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Displaying any time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Summing times that exceed 24 hours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Calculating the difference between two times. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .173 Converting from military time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 Converting decimal hours, minutes, or seconds to a time . . . . . . . . . . . . . . . . . . . . . . . . . . . .175 Adding hours, minutes, or seconds to a time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .175 Converting between time zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 Rounding time values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Working with non–time-of-day values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178
Chapter 7: Counting and Summing Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Counting and Summing Worksheet Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Counting or Summing Records in Databases and Pivot Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .183 Basic Counting Formulas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 Counting the total number of cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185 Counting blank cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185 Counting nonblank cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186 Counting numeric cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186 Counting nontext cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186 Counting text cells. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186 Counting logical values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187 Counting error values in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187
02_475362-ftoc.indd xii
4/14/10 9:14 PM
xiii Advanced Counting Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187 Counting cells with the COUNTIF function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .188 Counting cells that meet multiple criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189 Counting the most frequently occurring entry. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .192 Counting the occurrences of specific text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193 Counting the number of unique values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195 Creating a frequency distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 Summing Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Summing all cells in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 Computing a cumulative sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 Summing the “top n” values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Conditional Sums Using a Single Criterion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Summing only negative values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Summing values based on a different range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Summing values based on a text comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Summing values based on a date comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Conditional Sums Using Multiple Criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 Using And criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Using Or criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Using And and Or criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Chapter 8: Using Lookup Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .213 What Is a Lookup Formula? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .213 Functions Relevant to Lookups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .214 Basic Lookup Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .214 The VLOOKUP function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .215 The HLOOKUP function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .216 The LOOKUP function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .217 Combining the MATCH and INDEX functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .218 Specialized Lookup Formulas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 Looking up an exact value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 Looking up a value to the left . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 Performing a case-sensitive lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 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. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 Determining the address of a value within a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 Looking up a value by using the closest match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Looking up a value using linear interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Chapter 9: Tables and Worksheet Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Tables and Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 A worksheet database example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 A table example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Uses for worksheet databases and tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
02_475362-ftoc.indd xiii
4/14/10 9:14 PM
xiv Working with Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Creating a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 Changing the look of a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 Navigating and selecting in a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .241 Adding new rows or columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Deleting rows or columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Moving a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 Setting table style options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 Removing duplicate rows from a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Sorting and filtering a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Working with the Total row . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Using formulas within a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 Referencing data in a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Converting a table to a worksheet database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Using Advanced Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 Setting up a criteria range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Applying an advanced filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 Clearing an advanced filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Specifying Advanced Filter Criteria. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Specifying a single criterion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Specifying multiple criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 Specifying computed criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 Using Database Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 Inserting Subtotals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Chapter 10: Miscellaneous Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Unit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Calculating the area and perimeter of a circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Calculating the area of a trapezoid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .281 Calculating the area of a triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .281 Calculating the surface and volume of a sphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .281 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 Basic rounding formulas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Rounding to the nearest multiple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 Rounding currency values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 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
02_475362-ftoc.indd xiv
4/14/10 9:14 PM
xv
Part III: Financial Formulas Chapter 11: Borrowing and Investing Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Financial Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Time value of money . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 Cash in and cash out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 Matching time periods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Timing of the first payment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 The Basic Excel Financial Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Calculating present value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Calculating future value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Calculating payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Calculating rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Calculating periods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 Calculating the Interest and Principal Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Using the IPMT and PPMT functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 Using the CUMIPMT and CUMPRINC functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 Converting Interest Rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Methods of quoting interest rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Conversion formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 Limitations of Excel’s Financial Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .312 Deferred start to a series of regular payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .312 Valuing a series of variable payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .313 Bond Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .314 Pricing bonds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .314 Calculating yield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .316
Chapter 12: Discounting and Depreciation Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Using the NPV Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .317 Definition of NPV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .318 NPV function examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .319 Using the NPV function to calculate accumulated amounts . . . . . . . . . . . . . . . . . . . . . . . . . 325 Using the IRR Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 Rate of return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Geometric growth rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 Checking results. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Multiple Rates of IRR and the MIRR Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .331 Multiple IRRs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .331 Separating flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 Using balances instead of flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Irregular Cash Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 Net present value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 Internal rate of return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Using the FVSCHEDULE Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 Calculating an annual return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 Depreciation Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
02_475362-ftoc.indd xv
4/14/10 9:14 PM
xvi Chapter 13: Financial Schedules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .341 Creating Financial Schedules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .341 Creating Amortization Schedules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 A simple amortization schedule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 A dynamic amortization schedule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 Using payment and interest tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 Credit card calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 Summarizing Loan Options Using a Data Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .351 Creating a one-way data table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .351 Creating a two-way data table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Financial Statements and Ratios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Basic financial statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Ratio analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Creating Indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Part IV: Array Formulas Chapter 14: Introducing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Introducing Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 A multicell array formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 A single-cell array formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Creating an array constant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Array constant elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .371 Understanding the Dimensions of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 One-dimensional horizontal arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 One-dimensional vertical arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 Two-dimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 Naming Array Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 Working with Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Entering an array formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Selecting an array formula range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Editing an array formula. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Expanding or contracting a multicell array formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 Using Multicell Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 Creating an array from values in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 Creating an array constant from values in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 Performing operations on an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 Using functions with an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .381 Transposing an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .381 Generating an array of consecutive integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 Using Single-Cell Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 Counting characters in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 Summing the three smallest values in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 Counting text cells in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 Eliminating intermediate formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 Using an array in lieu of a range reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
02_475362-ftoc.indd xvi
4/14/10 9:14 PM
xvii Chapter 15: Performing Magic with Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391 Working with Single-Cell Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391 Summing a range that contains errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391 Counting the number of error values in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 Summing the n largest values in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 Computing an average that excludes zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 Determining whether a particular value appears in a range . . . . . . . . . . . . . . . . . . . . . . . . . 395 Counting the number of differences in two ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 Returning the location of the maximum value in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Finding the row of a value’s nth occurrence in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Returning the longest text in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 Determining whether a range contains valid values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 Summing the digits of an integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 Summing rounded values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .400 Summing every nth value in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 Removing nonnumeric characters from a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Determining the closest value in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Returning the last value in a column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Returning the last value in a row . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Ranking data with an array formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Working with Multicell Array Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Returning only positive values from a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 Returning nonblank cells from a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Reversing the order of cells in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Sorting a range of values dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 Returning a list of unique items in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 Displaying a calendar in a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Part V: Miscellaneous Formula Techniques Chapter 16: Intentional Circular References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .415 What Are Circular References? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .415 Correcting an accidental circular reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Understanding indirect circular references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .417 Intentional Circular References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .417 How Excel Determines Calculation and Iteration Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Circular Reference Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .421 Generating unique random integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .421 Solving a recursive equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 Solving simultaneous equations using a circular reference . . . . . . . . . . . . . . . . . . . . . . . . . . 424 Animating a chart using iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 Potential Problems with Intentional Circular References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Chapter 17: Charting Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 Understanding the SERIES Formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 Using names in a SERIES formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .431 Unlinking a chart series from its data range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
02_475362-ftoc.indd xvii
4/14/10 9:14 PM
xviii Creating Links to Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 Adding a chart title link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 Adding axis title links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 Adding links to data labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 Adding text links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 Adding a linked picture to a chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 Chart Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 Charting progress toward a goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 Creating a gauge chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438 Displaying conditional colors in a column chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 Creating a comparative histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 Creating a Gantt chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 Creating a box plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Plotting every nth data point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 Plotting the last n data points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 Selecting a series from a combo box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 Plotting mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450 Plotting a circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 Creating a clock chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 Creating awesome designs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 Working with Trendlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 Linear trendlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 Working with nonlinear trendlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
Chapter 18: Pivot Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 About Pivot Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 A Pivot Table Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474 Data Appropriate for a Pivot Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 Creating a Pivot Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 Specifying the Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 Specifying the location for the pivot table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 Laying out the pivot table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 Formatting the pivot table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484 Modifying the pivot table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 More Pivot Table Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 Question 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 Question 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 Question 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 Question 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 Question 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 Question 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 Question 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492 Grouping Pivot Table Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 A manual grouping example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 Viewing grouped data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 Automatic grouping examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 Creating a Frequency Distribution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
02_475362-ftoc.indd xviii
4/14/10 9:14 PM
xix Creating a Calculated Field or Calculated Item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 Creating a calculated field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504 Inserting a calculated item. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 Filtering Pivot Tables with Slicers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509 Referencing Cells within a Pivot Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510 Another Pivot Table Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .512 Producing a Report with a Pivot Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .515
Chapter 19: Conditional Formatting and Data Validation . . . . . . . . . . . . . . . . . . . . . . . . .519 Conditional Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .519 Specifying conditional formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520 Conditional formats that use graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524 Working with conditional formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532 Creating formula-based rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534 Data Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 Specifying validation criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 Types of validation criteria you can apply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 Creating a drop-down list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548 Using formulas for data validation rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549 Creating a dependent list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Chapter 20: Creating Megaformulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 What Is a Megaformula? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 Creating a Megaformula: A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556 Megaformula Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 Using a megaformula to remove middle names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558 Using a megaformula to return a string’s last space character position . . . . . . . . . . . . . . . 562 Using a megaformula to determine the validity of a credit card number . . . . . . . . . . . . . . 566 Generating random names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570 The Pros and Cons of Megaformulas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
Chapter 21: Tools and Methods for Debugging Formulas . . . . . . . . . . . . . . . . . . . . . . . . 573 Formula Debugging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 Formula Problems and Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 Mismatched parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 Cells are filled with hash marks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 Blank cells are not blank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 Extra space characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577 Formulas returning an error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578 Absolute/relative reference problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582 Operator precedence problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582 Formulas are not calculated . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 Actual versus displayed values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 Floating-point number errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585 Phantom link errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586 Logical value errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 Circular reference errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
02_475362-ftoc.indd xix
4/14/10 9:14 PM
xx Excel’s Auditing Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 Identifying cells of a particular type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 Viewing formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590 Tracing cell relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .591 Tracing error values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 Fixing circular reference errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 Using background error checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593 Using Excel’s Formula Evaluator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Part VI: Developing Custom Worksheet Functions Chapter 22: Introducing VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 About VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 Displaying the Developer Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600 About Macro Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600 Saving Workbooks That Contain Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 Introducing the Visual Basic Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603 Activating the VB Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603 The VB Editor components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604 Using the Project window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605 Using code windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 Entering VBA code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609 Saving your project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .612
Chapter 23: Function Procedure Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .613 Why Create Custom Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .613 An Introductory VBA Function Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614 About Function Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616 Declaring a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616 Choosing a name for your function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .617 Using functions in formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .618 Using function arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 Using the Insert Function Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 Adding a function description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 Specifying a function category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .621 Adding argument descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 Testing and Debugging Your Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624 Using the VBA MsgBox statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625 Using Debug.Print statements in your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627 Calling the function from a Sub procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628 Setting a breakpoint in the function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .631 Creating Add-Ins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
Chapter 24: VBA Programming Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635 An Introductory Example Function Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636 Using Comments in Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
02_475362-ftoc.indd xx
4/14/10 9:14 PM
xxi Using Variables, Data Types, and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638 Defining data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639 Declaring variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640 Using constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 Using strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 Using dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 Using Assignment Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644 Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645 Declaring an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645 Declaring multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646 Using Built-In VBA Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 Controlling Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648 The If-Then construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649 The Select Case construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .651 Looping blocks of instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652 The On Error statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656 Using Ranges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658 The For Each-Next construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658 Referencing a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659 Some useful properties of ranges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662 The Set keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 The Intersect function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 The Union function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 The UsedRange property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Chapter 25: VBA Custom Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669 Simple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 Does a cell contain a formula? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 Returning a cell’s formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 Is the cell hidden? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .671 Returning a worksheet name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .671 Returning a workbook name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672 Returning the application’s name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672 Returning Excel’s version number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673 Returning cell formatting information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673 Determining a Cell’s Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675 A Multifunctional Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679 Generating random numbers that don’t change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 Selecting a cell at random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 Calculating Sales Commissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682 A function for a simple commission structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683 A function for a more complex commission structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684 Text Manipulation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685 Reversing a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685 Scrambling text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685 Returning an acronym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
02_475362-ftoc.indd xxi
4/14/10 9:14 PM
xxii Does the text match a pattern? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 Does a cell contain a particular word. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688 Does a cell contain text? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 Extracting the nth Element from a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690 Spelling out a number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691 Counting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691 Counting pattern-matched cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 Counting sheets in a workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 Counting words in a range. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 Counting colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 Date Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694 Calculating the next Monday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694 Calculating the next day of the week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695 Which week of the month? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695 Working with dates before 1900 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696 Returning the Last Nonempty Cell in a Column or Row . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697 The LASTINCOLUMN function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697 The LASTINROW function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698 Multisheet Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699 Returning the maximum value across all worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699 The SHEETOFFSET function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700 Advanced Function Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701 Returning an error value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701 Returning an array from a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 Returning an array of nonduplicated random integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705 Randomizing a range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706 Using optional arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708 Using an indefinite number of arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
Part VII: Appendixes Appendix A: Excel Function Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 Appendix B: Using Custom Number Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733 About Number Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733 Automatic number formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734 Formatting numbers by using the Ribbon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734 Using shortcut keys to format numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 Using the Format Cells dialog box to format numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 Creating a Custom Number Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737 Parts of a number format string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738 Custom number format codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739 Custom Number Format Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .741 Scaling values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .741 Hiding zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744 Displaying leading zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745 Displaying fractions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
02_475362-ftoc.indd xxii
4/14/10 9:14 PM
xxiii Displaying N/A for text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746 Displaying text in quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746 Repeating a cell entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746 Displaying a negative sign on the right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747 Conditional number formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747 Coloring values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748 Formatting dates and times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749 Displaying text with numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749 Displaying a zero with dashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750 Using special symbols. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .751 Suppressing certain types of entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .751 Filling a cell with a repeating character. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .751 Displaying leading dots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
Appendix C: Additional Excel Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753 The Excel Help System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753 Microsoft Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753 Support options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 Microsoft Knowledge Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 Microsoft Excel home page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 Microsoft Office home page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 Internet Newsgroups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755 Accessing newsgroups by using a newsreader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755 Accessing newsgroups by using a Web browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755 Searching newsgroups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756 Internet Web sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 The Spreadsheet Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 Daily Dose of Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 Jon Peltier’s Excel page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 Pearson Software consulting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 Contextures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 David McRitchie’s Excel pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 Pointy Haired Dilbert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 Mr. Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
Appendix D: What’s on the CD-ROM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759 Using the CD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759 Files and Software on the CD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760 eBook version of Excel 2010 Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760 Examples files for Excel 2010 Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
02_475362-ftoc.indd xxiii
4/14/10 9:14 PM
02_475362-ftoc.indd xxiv
4/14/10 9:14 PM
INTRODUCTION
Welcome to Excel 2010 Formulas. I approached this project with one goal in mind: To write the ultimate book about Excel 2010 formulas that would appeal to a broad base of users. That’s a fairly ambitious goal. But based on the feedback I received from the first four editions, I think I’ve accomplished it. Excel is the spreadsheet market leader, by a long shot. This is the case not only because of Microsoft’s enormous marketing clout, but because it is truly the best spreadsheet available. One area in which Excel’s superiority is most apparent is formulas. Excel has some special tricks up its sleeve in the formulas department. As you’ll see, Excel lets you do things with formulas that are impossible with other spreadsheets. It’s a safe bet that only about 10 percent of Excel users really understand how to get the most out of worksheet formulas. In this book, I attempt to nudge you into that elite group. Are you up to it?
What You Need to Know This is not a book for beginning Excel users. If you have absolutely no experience with Excel, this is probably not the best book for you — unless you’re one of a rare breed who can learn a new software product almost instantaneously. To get the most out of this book, you should have some background using Excel. Specifically, I assume that you know how to h Create workbooks, insert sheets, save files, and complete other basic tasks h Navigate through a workbook h Use the Excel 2010 Ribbon and dialog boxes h Use basic Windows features, such as file management and copy and paste techniques
1
03_475362-intro.indd 1
4/14/10 9:15 PM
2
Introduction
What You Need to Have I wrote this book for Excel 2010, but most of the material also applies to Excel 2007. If you’re using a version prior to Excel 2007, I suggest that you put down this book immediately and pick up a previous edition. The changes introduced in Excel 2007 are so extensive that you might be hopelessly confused if you try to follow along using an earlier version of Excel. To use the examples on the companion CD-ROM, you’ll need a CD-ROM drive. The examples on the CD-ROM are discussed further in the “About the Companion CD-ROM” section, later in this Introduction. I use Excel for Windows exclusively, and I do not own a Macintosh. Therefore, I can’t guarantee that all of the examples will work with Excel for Macintosh. Excel’s crossplatform 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 high-resolution video mode. Better yet, try a dual-monitor system.
Conventions in This Book Take a minute to skim this section and learn some of the typographic conventions used throughout this book.
Keyboard conventions You need to use the keyboard to enter formulas. In addition, you can work with menus and dialog boxes directly from the keyboard — a method you may find easier if your hands are already positioned over the keys.
Formula listings Formulas usually appear on a separate line in monospace font. For example, I may list 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 an array formula in brackets in order to remind you that it’s an array formula. When I list an array formula, I include the brackets to make it clear that it is, in fact, an array formula. For example: {=SUM(LEN(A1:A10))}
03_475362-intro.indd 2
4/14/10 9:15 PM
Introduction
3
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 monospace font; each line of code occupies a separate line. To make the code easier to read, I usually use one or more tabs to create indentations. Indentation is optional, but it does help to delineate statements that go together. If a line of code doesn’t fit on a single line in this book, I use the standard VBA line continuation sequence: a space followed by an underscore character. This indicates that the line of code extends to the next line. For example, the following two lines 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 line without the trailing underscore character.
Key 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 connected 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 InsertTotals procedure.” 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.
03_475362-intro.indd 3
4/14/10 9:15 PM
4
Introduction
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 to call your attention to points that are particularly important. This icon indicates a feature new to Excel 2010.
I use Note icons to tell you that something is important — perhaps a concept that may help you master the task at hand or something fundamental for understanding subsequent material.
Tip icons indicate a more efficient way of doing something or a technique that may not be obvious. These will often impress your officemates.
These 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 problems if you’re not careful.
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 dozens of ways to organize this material, but I settled on a scheme that divides the book into six main parts. In addition, I’ve included a few appendixes that provide supplemental information that you may find helpful.
Part I: Basic Information This part is introductory in nature; it consists of Chapters 1 through 3. Chapter 1 sets the stage with a quick and dirty overview of Excel. This chapter is designed for readers who are new to Excel but who have used other spreadsheet products. In Chapter 2, I cover the basics of formulas.
03_475362-intro.indd 4
4/14/10 9:15 PM
Introduction
5
This chapter is absolutely essential reading in order to get the most out of this book. Chapter 3 deals with names. If you thought names were just for cells and ranges, you’ll see that you’re missing out on quite a bit.
Part II: Using Functions in Your Formulas This part consists of Chapters 4 through 10. Chapter 4 covers the basics of using worksheet functions in your formulas. I get more specific in subsequent chapters. Chapter 5 deals with manipulating text, Chapter 6 covers dates and times, and Chapter 7 explores various counting techniques. In Chapter 8, I discuss various types of lookup formulas. Chapter 9 deals with tables and worksheet databases, and Chapter 10 covers a variety of miscellaneous calculations such as unit conversions and rounding.
Part III: Financial Formulas Part III consists of three chapters (Chapters 11 through 13) that deal with creating financial formulas. You’ll find lots of useful formulas that you can adapt to your needs.
Part IV: Array Formulas This part consists of Chapters 14 and 15. The majority of Excel users know little or nothing about array formulas — a topic that happens to be dear to me. Therefore I devote 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’ll see why formulas can be important when you work with charts, and Chapter 18 covers formulas as they relate to pivot tables. Chapter 19 contains some very interesting (and useful) formulas that you can use in conjunction with Excel’s conditional 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 several intermediary formulas. And what do you do when your formulas don’t work correctly? 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 Visual Basic for Applications (VBA), the key to creating custom worksheet functions. Chapter 22 introduces VBA and the VB Editor, and Chapter 23 provides some necessary background on custom worksheet functions. Chapter 24 covers programming concepts, and Chapter 25 provides a slew of worksheet function examples that you can use as-is, or customize for your own needs.
03_475362-intro.indd 5
4/14/10 9:15 PM
6
Introduction
Part VII: Appendixes What’s a computer book without appendixes? This book has four appendixes. In the appendixes, you’ll find a quick reference guide to Excel’s worksheet functions, tips on using custom number formats, and a handy guide 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 cover while lounging on a sunny beach in Kauai, that’s fine with me. More likely, you’ll want 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 formula quickly. If you’re faced with a challenging task, you may want to check the index first to see whether the book specifically addresses your problem.
About the Companion CD-ROM This book contains many examples, and the workbooks for those examples are available on the companion CD-ROM, arranged in directories that correspond to the chapters. The example workbook files on the companion CD-ROM are not compressed, so you can access them directly from the CD (installation not required). These files are all Excel 2007/2010 files. Files that have an *.xlsm extension contain VBA macros. In order to use the macros, you must enable the macros. In addition, the CD-ROM contains an electronic version of this book. It’s a searchable PDF file that’s a perfect companion for your notebook computer when you take your next cross-country flight. Refer to Appendix D for more information about the example files on the CD-ROM.
About the Power Utility Pak Offer Toward the back of the book, you’ll find a coupon that you can redeem for a discounted copy of my award-winning Power Utility Pak — a collection of useful Excel utilities, plus many new worksheet functions. I developed this package using VBA exclusively.
03_475362-intro.indd 6
4/14/10 9:15 PM
Introduction
7
You can also use this coupon to purchase the complete VBA source code for a nominal fee. Studying the code is an excellent way to pick up some useful programming techniques. You can take the product for a test drive by installing the shareware version from the companion CD-ROM. You can download a 30-day trial version of the most recent version of the Power Utility Pak from my Web site: http://spreadsheetpage.com
If you find it useful, use the coupon to purchase a licensed copy at a discount.
Reach Out I’m always interested in getting feedback on my books. The best way to provide this feedback is via e-mail. Send your comments and suggestions to
[email protected] Unfortunately, I’m not able to reply to specific questions. Posting your question to one of the Excel newsgroups is, by far, the best way to get such assistance. See Appendix C for more information about the newsgroups. Also, when you’re out surfing the Web, don’t overlook my Web site (“The Spreadsheet Page”). You’ll find lots of useful Excel information, including tips and downloads. The URL is http://spreadsheetpage.com
Now, without further ado, it’s time to turn the page and expand your horizons.
03_475362-intro.indd 7
4/14/10 9:15 PM
8
03_475362-intro.indd 8
Introduction
4/14/10 9:15 PM
PART
I
Basic Information Chapter 1 Excel in a Nutshell
Chapter 2 Basic Facts about Formulas
Chapter 3 Working with Names
04_475362-pp01.indd 9
4/14/10 9:16 PM
04_475362-pp01.indd 10
4/14/10 9:16 PM
1 Excel in a Nutshell In This Chapter ●
A brief history of Excel
●
What’s new in Excel 2010
●
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 drawing layer
●
Macros, toolbars, and add-ins for Excel customization
●
Internet features
●
Analysis tools
●
Protection options
Microsoft Excel has been referred to as “the best application ever written for Windows.” 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 reincarnations and face-lifts over the years. Cosmetically, the current version — Excel 2010 — barely even resembles the original version. However, many of Excel’s key elements have remained intact over the years, with significant enhancements, of course. This chapter presents a concise overview of the features available in the more recent versions of Excel, with specific emphasis on Excel 2010. It sets the stage for the subsequent chapters and provides an overview for those who may have let their Excel skills get rusty.
11
05_475362-ch01.indd 11
4/14/10 9:25 PM
12
Part I: Basic Information
The History of Excel You probably weren’t expecting a history lesson when you bought this book, but you may find this information interesting. At the very least, this section provides fodder for the next office trivia match. Spreadsheets comprise a huge business, but most of us tend to take this software for granted. In the pre-spreadsheet days, people relied on clumsy mainframes or calculators and spent hours doing what now takes minutes.
It started with VisiCalc Dan Bricklin and Bob Frankston conjured up VisiCalc, the world’s first electronic spreadsheet, back in the late 1970s when personal computers were unheard of in the office environment. They wrote VisiCalc for the Apple II computer, an interesting machine that seems like a toy by today’s standards. VisiCalc caught on quickly, and many forward-looking companies purchased the Apple II for the sole purpose of developing their budgets with VisiCalc. Consequently, VisiCalc is often credited for much of Apple II’s initial success.
Then came Lotus When the IBM PC arrived on the scene in 1982, thus legitimizing personal computers, VisiCorp wasted no time porting VisiCalc to this new hardware environment. Envious of VisiCalc’s success, a small group of computer enthusiasts at a start-up company in Cambridge, Massachusetts, refined the spreadsheet concept. Headed by Mitch Kapor and Jonathan Sachs, the company designed a new product and launched the software industry’s first full-fledged marketing blitz. Released in January 1983, Lotus Development Corporation’s 1-2-3 proved an instant success. Despite its $495 price tag (yes, people really paid that much for a single program), it quickly outsold VisiCalc and rocketed to the top of the sales charts, where it remained for many years.
Microsoft enters the picture Most people don’t realize that Microsoft’s experience with spreadsheets extends back to the early 1980s. In 1982, Microsoft released its first spreadsheet — MultiPlan. Designed for computers running the CP/M operating system, the product was subsequently ported to several other platforms, including Apple II, Apple III, XENIX, and MS-DOS. MultiPlan essentially ignored existing software UI standards. Difficult to learn and use, it never earned much of a following in the United States. Not surprisingly, Lotus 1-2-3 pretty much left MultiPlan in the dust. Excel partly evolved from MultiPlan, and first surfaced in 1985 on the Macintosh. Like all Mac applications, Excel was a graphics-based program (unlike the character-based MultiPlan). In November 1987, Microsoft released the first version of Excel for Windows (labeled Excel 2 to correspond with the Macintosh version). Excel didn’t catch on right away, but as Windows gained popularity, so did Excel. Lotus eventually released a Windows version of Lotus 1-2-3, and Excel
05_475362-ch01.indd 12
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
13
had additional competition from Quattro Pro — originally a DOS program developed by Borland International, then sold to Novell, and then sold again to Corel (its current owner).
Excel versions Excel 2010 is actually Excel 14 in disguise. You may think that this name represents the 14th version of Excel. Think again. Microsoft may be a successful company, but its version-naming techniques can prove quite confusing. As you’ll see, Excel 2010 actually represents the 11th Windows version of Excel. In the following sections, I briefly describe the major Windows versions of Excel.
Excel 2 The original version of Excel for Windows, Excel 2 first appeared in late 1987. It was labeled Version 2 to correspond to the Macintosh version (the original Excel). Because Windows wasn’t in widespread use at the time, this version included a runtime version of Windows — a special version with just enough features to run Excel and nothing else. This version appears quite crude by today’s standards, as shown in Figure 1-1.
Figure 1-1: The original Excel 2 for Windows. Excel has come a long way since its original version. (Photo courtesy of Microsoft Corporation)
Excel 3 At the end of 1990, Microsoft released Excel 3 for Windows. This version offered a significant improvement in both appearance and features. It included toolbars, drawing capabilities, worksheet outlining, add-in support, 3-D charts, workgroup editing, and lots more.
05_475362-ch01.indd 13
4/14/10 9:25 PM
14
Part I: Basic Information
Excel 4 Excel 4 hit the streets in the spring of 1992. This version made quite an impact on the marketplace as Windows increased in popularity. It boasted lots of new features and usability enhancements that made it easier for beginners to get up to speed quickly.
Excel 5 In early 1994, Excel 5 appeared on the scene. This version introduced tons of new features, including multisheet workbooks and the new Visual Basic for Applications (VBA) macro language. Like its predecessor, Excel 5 took top honors in just about every spreadsheet comparison published in the trade magazines.
Excel 95 Excel 95 (also known as Excel 7) shipped in the summer of 1995. On the surface, it resembled Excel 5 (this version included only a few major new features). However, Excel 95 proved to be significant because it presented the first version to use more advanced 32-bit code. Excel 95 and Excel 5 use the same file format.
Excel 97 Excel 97 (also known as Excel 8) probably offered the most significant upgrade ever. The toolbars and menus took on a great new look, online help moved a dramatic step forward, and the number of rows available in a worksheet quadrupled. And if you’re a macro developer, you may have noticed that Excel’s programming environment (VBA) moved up several notches on the scale. Excel 97 also introduced a new file format.
Excel 2000 Excel 2000 (also known as Excel 9) was released in June of 1999. Excel 2000 offered several minor enhancements, but the most significant advancement was the ability to use HTML as an alternative file format. Excel 2000 still supported the standard binary file format, of course, which is compatible with Excel 97.
Excel 2002 Excel 2002 (also known as Excel 10 or Excel XP) was released in June of 2001 and is part of Microsoft Office XP. This version offered several new features, most of which are fairly minor and were designed to appeal to novice users. Perhaps the most significant new feature was the capability to save your work when Excel crashes and also recover corrupt workbook files that you may have abandoned long ago. Excel 2002 also added background formula error checking and a new formula-debugging tool.
Excel 2003 Excel 2003 (also known as Excel 11) was released in the fall of 2003. This version had very few new features. Perhaps the most significant new feature was the ability to import and export XML
05_475362-ch01.indd 14
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
15
files and map the data to specific cells in a worksheet. It also introduced the concept of the List, a specially designated range of cells. Both of these features would prove to be precursors to future enhancements.
Excel 2007 Excel 2007 (also known as Excel 12) was released in early 2007. Its official name is Microsoft Office Excel 2007. This release represented the most significant change since Excel 97, including a change to Excel’s default file format. The new format was XML based although a binary format is still available. Another major change was the Ribbon, a new type of UI that replaced the Excel menu and toolbar system. In addition to these two major changes, Microsoft enhanced the List concept introduced in Excel 2003 (a List is now known as a Table), improved the look of charts, significantly increased the number of rows and columns, and added some new worksheet functions. XML (Extensible Markup Language) stores data in a structured text format. The new file formats are actually compressed folders that contain several different XML files. The default format’s file extension is .xlsx. There’s also a macro-enabled format with the extension .xlsm, a new binary format with the extension .xlsb, and all the legacy formats that you’re used to.
Excel 2010 The current version, Excel 2010, was released in early 2010 and is also known as Excel 14. If you think you’ve spotted a typo in the previous sentence, you’re wrong. Yes, even big companies can be superstitious; Microsoft skipped Version 13 of Office and went from Version 12 to Version 14. Excel 2010 builds on the improvements introduced in Excel 2007, and it offers several new enhancements. See the sidebar, “What’s new in Excel 2010?”
The Object Model Concept If you’ve dealt with computers for any length of time, you’ve undoubtedly heard the term objectoriented programming. An object essentially represents a software element that a programmer can manipulate. When using Excel, you may find it useful to think in terms of objects, even if you have no intention of becoming a programmer. An object-oriented approach can often help you keep the various elements in perspective. Excel objects include the following: h Excel itself h An Excel workbook h A worksheet in a workbook h A range in a worksheet h A button on a worksheet
05_475362-ch01.indd 15
4/14/10 9:25 PM
16
Part I: Basic Information
h A ListBox control on a UserForm (a custom dialog box) h A chart sheet h A chart on a chart sheet h A chart series in a chart
New Feature
What’s new in Excel 2010? Here’s a quick summary of what’s new, relative to Excel 2007: ●
64-bit version: If your hardware supports it, you can install the 64-bit version, which lets you create much larger workbooks.
●
Sparkline charts: Create small, in-cell charts to summarize a range of data graphically.
●
Pivot table Slicers: A new way to filter and display data in pivot tables.
●
Pivot table formatting options: You have more control over the appearance of pivot table reports.
●
File tab: The File tab replaces the Office button, which is located to the left of the other tabs. Clicking it displays Backstage View, a screen that lets you perform various operations on your workbook. This view essentially replaces the traditional File and Print menus — plus quite a bit more.
●
Draft mode for charts: If you use many highly formatted charts, you can choose to display them in draft mode for improved performance.
●
Conditional formatting enhancements: Data bar conditional formatting can display in a solid color, and the bars provide a more accurate display.
●
Function enhancements: Many of Excel’s statistical functions have been improved in terms of numeric accuracy. The old versions of these functions are still available and have been relegated to a new function category called Compatibility.
●
Image editing enhancements: You have much more control over the appearance of graphic images inserted into a workbook.
●
Paste preview: When you copy a range, the Paste command displays various options (with preview).
●
Ribbon customization: End users can customize the Ribbon by adding new tabs and groups.
●
Equation editor: Create and display (noncalculating) mathematical equations.
●
Faster processing: Microsoft made some improvements to the calculation engine, and files load a bit faster.
●
New security features: Workbooks downloaded from the Internet or from e-mail attachments are opened in Protected View mode. Workbooks can be designated as “trusted,” and they don’t need to reside in special trusted folders.
●
Updated Solver: Excel 2010 includes a new version of the Solver add-in.
●
Enhancements to VBA: Many operations that used to require old XLM macros can now be performed directly using VBA macro commands.
05_475362-ch01.indd 16
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
17
Notice the existence of an object hierarchy: The Excel object contains workbook objects, which contain worksheet objects, which contain range objects. This hierarchy is called Excel’s object model. Other Microsoft Office products have their own object model. The object model concept proves to be vitally important when developing VBA macros. Even if you don’t create macros, you may find it helpful to think in terms of objects.
The Workings of Workbooks The core document of Excel is a workbook. Everything that you do in Excel takes place in a workbook. Beginning with Excel 2007, workbook “files” are actually compressed folders. You may be familiar with compressed folders if you’ve ever used a file with a .zip extension. Inside the compressed folders are a number of files that hold all the information about your workbook, including charts, macros, formatting, and the data in its cells. An Excel workbook can hold any number of sheets (limited only by memory). The four types of sheets are h Worksheets h Chart sheets h MS Excel 4.0 macro sheets (obsolete, but still supported) h MS Excel 5.0 dialog sheets (obsolete, but still supported) You can open or create as many workbooks as you want (each in its own window), but only one workbook is the active workbook at any given time. Similarly, only one sheet in a workbook is the active sheet. To activate a different sheet, click its corresponding tab at the bottom of the window, or press Ctrl+PgUp (for the previous sheet) or Ctrl+PgDn (for the next sheet). To change a sheet’s name, double-click its Sheet tab and type the new text for the name. Right-clicking a tab brings up a shortcut menu with some additional sheet-manipulation options. You can also hide the window that contains a workbook by using the View➜Window➜Hide command. A hidden workbook window remains open but not visible. Use the View➜Window➜Unhide command to make the window visible again. A single workbook can display in multiple windows (choose View➜Window➜New Window). Each window can display a different sheet or a different area of the same sheet.
Worksheets The most common type of sheet is a worksheet — which you normally think of when you think of a spreadsheet. Excel 2010 worksheets have 16,384 columns and 1,048,576 rows. Versions prior to Excel 2007 support only 256 columns and 65,536 rows. If you open such a file, Excel 2010 enters compatibility mode to work with the smaller worksheet grid. In order to work with the larger grid, you must save the file in one of the Excel 2010 formats. Then close the workbook and reopen it.
05_475362-ch01.indd 17
4/14/10 9:25 PM
18
Part I: Basic Information
How big is a worksheet? It’s interesting to stop and think about the actual size of a worksheet. Do the arithmetic (16,384 × 1,048,576), and you’ll see that a worksheet has 17,179,869,184 cells. Remember that this is in just one worksheet. A single workbook can hold more than one worksheet. If you’re using a 1600 x 1200 video mode with the default row heights and column widths, you can see 24 columns and 49 rows (or 1,176 cells) at a time — which is about .0000068 percent of the entire worksheet. In other words, more than 14.6 million screens of information reside within a single worksheet. If you entered a single digit into each cell at the relatively rapid clip of one cell per second, it would take you over 500 years, nonstop, to fill up a worksheet. To print the results of your efforts would require more than 36 million sheets of paper — a stack about 12,000 feet high (that’s ten Empire State Buildings stacked on top of each other).
Having access to more cells isn’t the real value of using multiple worksheets in a workbook. Rather, multiple worksheets are valuable because they enable you to organize your work better. Back in the old days, when a spreadsheet file consisted of a single worksheet, developers wasted a lot of time trying to organize the worksheet to hold their information efficiently. Now, you can store information on any number of worksheets and still access it instantly. You have complete control over the column widths and row heights, and you can even hide rows and columns (as well as entire worksheets). You can display the contents of a cell vertically (or at an angle) and even wrap around to occupy multiple lines. In addition, you can merge cells together to form a larger cell. By default, every new workbook starts out with three worksheets. You can easily add a new sheet when necessary, so you really don’t need to start with three sheets. You may want to change this default to a single sheet. To change this option, choose the File➜Options command, click the General tab, and change the setting for the option labeled Include This Many Sheets.
Chart sheets A chart sheet holds a single chart. Many users ignore chart sheets, preferring to use embedded charts, which are stored on the worksheet’s drawing layer. Using chart sheets is optional, but they make it a bit easier to locate a particular chart, and they prove especially useful for presentations. I discuss embedded charts (or floating charts on a worksheet) later in this chapter.
Macro sheets and dialog sheets This section discusses two obsolete Excel features that continue to be supported.
05_475362-ch01.indd 18
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
19
An Excel 4.0 macro sheet is a worksheet that has some different defaults. Its purpose is to hold XLM macros. XLM is the macro system used in Excel version 4.0 and earlier. This macro system was replaced by VBA in Excel 5.0 and is not discussed in this book. An Excel 5.0 dialog sheet is a drawing grid that can hold text and controls. In Excel 5.0 and Excel 95, dialog sheets were used to make custom dialog boxes. UserForms were introduced in Excel 97 to replace these sheets.
The Excel User Interface A UI is the means by which an end user communicates with a computer program. A UI includes elements such as menus, dialog boxes, toolbars, and keystroke combinations, as well as features such as drag and drop.
A new UI Almost every Windows program you use employs the menu and toolbar approach. That is, at the top of the screen is a menu bar that contains virtually every command that’s available in the application, and below that is one or more toolbars, which provide shortcuts to some of the more frequently used commands. With the release of Office 2007, the days of menus and toolbars are over. The new UI for Excel consists of components like the Ribbon, Backstage View, the Mini Toolbar, and the Quick Access toolbar.
The Ribbon The Ribbon is the primary UI component in Excel. It replaces the menu and most of the toolbars that were common in previous versions, and it is a very significant departure from the interfaces of most Windows-based applications.
One-stop shopping Microsoft felt that the commands contained in the old menu and toolbar system were becoming so numerous that a new paradigm was necessary. One of the main goals for developing the Ribbon was to provide the user with a single place to look for a particular feature. Every commonly used command available in Excel would be contained in the Ribbon (or in a dialog box accessed via the Ribbon). Although Microsoft succeeded in putting most of the available commands on the Ribbon, it’s still a pretty big place. The Ribbon in Office 2007 received mixed reviews. Some people hated it, and others loved it. For some, the hatred was so severe that they sought Excel 2007 add-ins that restored the old menus. Others set up online petitions, asking Microsoft to restore the old menus for Office. Fact is, the Ribbon is here to stay. Once you get used to the Ribbon, it really is easier to use than the convoluted menu system that it replaced.
05_475362-ch01.indd 19
4/14/10 9:25 PM
20
Part I: Basic Information
A few commands failed to make the cut and do not appear in the Ribbon. But they are still available if you know where to look for them. Right-click the Quick Access toolbar and choose Customize Quick Access Toolbar. Excel displays a dialog box with a list of commands that you can add to your Quick Access toolbar. Some of these commands aren’t available elsewhere in the UI. In Excel 2010, you can also add new commands to the Ribbon: Right-click the Ribbon and select Customize The Ribbon.
Tabs, groups, and tools The Ribbon is a band of tools that stretches across the top of the Excel window. About the vertical size of three of the old-style toolbars, the Ribbon sports a number of tabs including Home, Insert, Page Layout, and others. On each tab are groups that contain related tools. On the Home tab, for example, you find the Clipboard group, the Font group, the Alignment group, and others. Within the groups are the tools, which are similar to the tools that existed on the old-style toolbars with one major difference: their different sizes. Tools that you use most often are larger than less-frequently used tools. For example, nearly half of the Clipboard group is consumed by the large Paste tool; the Cut, Copy, and Format Painter tools are much smaller. Microsoft determined that the Paste tool is the most used tool and thus sized it accordingly. The Ribbon and all its components resize dynamically as you resize the Excel window horizontally. Smaller Excel windows collapse the tools on compressed tabs and groups, and maximized Excel windows on large monitors show everything that’s available. Even in a small window, all Ribbon commands remain available. You just may need to click a few extra times to access them. Figure 1-2 shows three sizes of the Ribbon when the Home tab is displayed using an increasingly smaller horizontal window size.
Figure 1-2: The Ribbon sizes dynamically, depending on the horizontal size of Excel’s window.
Navigation Using the Ribbon is fairly easy with a mouse. You click a tab and then click a tool. If you prefer to use the keyboard, Microsoft has added a feature just for you. Pressing Alt displays tiny squares with shortcut letters in them that hover over their respective tab or tool. Each shortcut letter that you press either executes its command or drills down to another level of shortcut letters. Pressing Esc cancels the letters or moves up to the previous level.
05_475362-ch01.indd 20
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
21
For example, a keystroke sequence of Alt+HBB adds a double border to the bottom of the selection. The Alt key activates the shortcut letters, the H shortcut activates the Home tab, the B shortcut activates the Borders tool menu, and the second B shortcut executes the Bottom Double Border command. Note that it’s not necessary to keep the Alt key depressed while you press the other keys.
Contextual tabs The Ribbon contains tabs that are visible only when they are needed. Generally, when a previously hidden tab appears, it’s because you selected an object or a range with special characteristics (like a chart or a pivot table). A typical example is the Drawing Tools contextual tab. When you select a shape or WordArt object, the Drawing Tools tab is made visible and active. It contains many tools that are only applicable to shapes, such as shape-formatting tools.
ScreenTips and dialog box launchers Hovering over a tool on the Ribbon displays a ScreenTip that explains the command the tool will execute. ScreenTips are larger and, in most cases, wordier than the ToolTips from previous versions. At the bottom of many of the groups is a small box icon (a dialog box launcher) that opens a dialog box related to that group. Users of previous versions of Excel will recognize these dialog boxes, many of which are unchanged. Some of the icons open the same dialog boxes but to different areas. For instance, the Font group icon opens the Format Cells dialog box with the Font tab activated. The Alignment group opens the same dialog box but activates the Alignment tab. The Ribbon makes using dialog boxes a far less-frequent activity than in the past because most of the commonly used operations can be done directly on the Ribbon.
Galleries and Live Preview A gallery is a large collection of tools that look like the choice they represent. If you’ve used previous versions of Excel, you may have noticed that the font names in the drop-down list box on the Formatting toolbar were in their own font. Galleries are an extension of that feature. The Styles gallery, for example, does not just list the name of the style, but lists it in the same formatting that will be applied to the cell. Although galleries help to give you an idea of what your object will look like when an option is selected, Live Preview takes it to the next level. Live Preview displays your object or data as it will look right on the worksheet when you hover over the gallery tool. By hovering over the various tools in the Format Table gallery, you can see exactly what your table will look like before you commit to a format.
Backstage View The big round Office Button in Excel 2007 has been replaced by a File tab that takes you to the Backstage View (see Figure 1-3). This is where you perform most of the document-related activities: creating new workbooks, opening files, saving files, printing, and so on.
05_475362-ch01.indd 21
4/14/10 9:25 PM
22
Part I: Basic Information
Figure 1-3: Clicking the File tab takes you to the Backstage View.
Backstage View also contains the list of recent documents (up to 50), with a pushpin icon next to each entry that you can use to keep that document at the top of the list regardless of how many files you open and close. Plus, Backstage View gives you access to the Excel Options dialog box, which contains dozens of settings for customizing Excel.
Shortcut menus and the Mini Toolbar Excel also features dozens of shortcut menus. These menus appear when you right-click after selecting one or more objects. The shortcut menus are context sensitive. In other words, the menu that appears depends on the location of the mouse pointer when you right-click. You can right-click just about anything — a cell, a row or column border, a workbook title bar, and so on. Right-clicking many items displays the shortcut menu as well as a Mini Toolbar. The Mini Toolbar is a floating toolbar that contains a dozen or so of the most popular formatting commands. Figure 1-4 shows the shortcut menu and Mini Toolbar when a range is selected.
05_475362-ch01.indd 22
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
23
Figure 1-4: The shortcut menu and Mini Toolbar appear when you right-click a range.
Customizing the UI The Quick Access toolbar is a set of tools that the user can customize. By default, the Quick Access toolbar contains three tools: Save, Undo, and Redo. If you find that you use a particular Ribbon command frequently, right-click the command and select Add to Quick Access Toolbar. You can make other changes to the Quick Access toolbar from the Quick Access Toolbar tab of the Excel Options dialog box. To access this dialog box, right-click the Quick Access toolbar and select Customize Quick Access Toolbar. A new feature in Excel 2010 lets you customize the Ribbon; this is done in the Customize Ribbon tab of the Excel Options dialog box. You can customize the Ribbon in these ways: h Add a new tab h Add a new group to a tab h Add commands to a group h Remove groups from a tab h Remove commands from custom groups h Change the order of the tabs
05_475362-ch01.indd 23
4/14/10 9:25 PM
24
Part I: Basic Information
h Change the order of the groups within a tab h Change the name of a tab h Change the name of a group h Move a group to a different tab h Reset the Ribbon to remove all customizations That’s a fairly comprehensive list of customization options, but there are some actions that you cannot do: h You cannot remove built-in tabs — but you can hide them. h You cannot remove commands from built-in groups. h You cannot change the order of commands in a built-in group.
Smart Tags A Smart Tag is a small icon that appears automatically in your worksheet after you complete certain actions. Clicking a Smart Tag (or pressing Ctrl) reveals several options. For example, if you copy and paste a range of cells, Excel generates a Smart Tag that appears below the pasted range (see Figure 1-5). Excel features several other Smart Tags, and additional Smart Tags can be provided by third-party providers.
Figure 1-5: This Smart Tag appears when you paste a copied range.
05_475362-ch01.indd 24
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
25
Task pane Excel 2002 introduced the task pane. This is a multipurpose UI element that is normally docked on a side of Excel’s window (but you can drag it anywhere you like). You can use the task pane for a variety of purposes, including displaying the Office Clipboard, providing research assistance, displaying pivot table fields, and mapping XML data. Figure 1-6 shows the task pane that appears when you insert clip art.
Figure 1-6: The Clip Art task pane allows you to search for and insert an image.
Drag and drop Excel’s drag-and-drop UI feature enables you to freely drag objects that reside on the drawing layer to change their position. Pressing Ctrl while dragging duplicates the selected objects. These objects include shapes, embedded charts, and SmartArt. Excel also permits drag-and-drop actions on cells and ranges. You can easily drag the contents of a cell or range to a different position. And pressing Ctrl while dragging copies the selected range. You can disable the ability to drag and drop the contents of cells. To change this setting, choose File➜Options to display the Excel Options dialog box. Click the Advanced tab and clear the Enable Fill Handle and Cell Drag-and-Drop check box (located in the Editing Options section).
Keyboard shortcuts In addition to the keyboard shortcuts for navigating the Ribbon, Excel has many other keyboard shortcuts that execute commands directly. For example, you can press Ctrl+C to copy a selection. If you’re a newcomer to Excel or if you just want to improve your efficiency, do yourself a favor
05_475362-ch01.indd 25
4/14/10 9:25 PM
26
Part I: Basic Information
and check out the shortcuts listed in Excel’s Help system. (Search for keyboard shortcuts using the Search box or locate the topic under the Accessibility chapter of Help’s Table of Contents.) The Help system contains tables that summarize useful keyboard commands and shortcuts. To ease the transition from previous versions, Microsoft includes the Office 2003 Access Key feature. Many Excel users are accustomed to navigating the old menu system with their keyboard, and they would become much more inefficient if they had to rely on the new Ribbon. If you type an Alt+letter sequence that isn’t a part of the Ribbon but that did exist in Excel 2003, you get a ScreenTip near the top of the Excel window, like the one shown in Figure 1-7.
Figure 1-7: Using a keyboard sequence like Alt+I+R (for Insert➜Row) can still be used to insert a row and will display this ScreenTip during the process.
Customized on-screen display Excel offers some flexibility regarding on-screen display (status bar, Formula bar, the Ribbon, and so on). For example, by choosing View➜Workbook Views➜Full Screen, you can get rid of everything except the title bar, thereby maximizing the amount of visible information. To get out of full-screen mode, right-click and select Exit Fullscreen from the shortcut menu (or press Esc). A little less drastic is pressing the Ctrl+F1 shortcut key to hide (and restore) the Ribbon. The status bar at the bottom of the screen can be customized. Right-click the status bar, and you see lots of options that allow you to control what information is displayed in the status bar. Many other customizations can be made by choosing File➜Options and clicking the Advanced tab. On this tab are several sections that deal with what displays on-screen.
Data entry Data entry in Excel is quite straightforward. Excel interprets each cell entry as one of the following: h A value (including a date or a time) h Text h A Boolean value (TRUE or FALSE) h A formula
Formulas always begin with an equal sign (=).
05_475362-ch01.indd 26
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
27
Data-entry tips The following list of data-entry tips can help those moving up to Excel from another spreadsheet: ●
To enter data without pressing the arrow keys, enable the After Pressing Enter, Move Selection option on the Advanced tab of the Excel Options dialog box (which you access from the Office➜Excel Options command). You can also choose the direction that you want to go.
●
You may find it helpful to select a range of cells before entering data. If you do so, you can use the Tab key or Enter key to move only within the selected cells.
●
To enter the same data in all cells within a range, select the range, enter the information into the active cell, and then press Ctrl+Enter.
●
To copy the contents of the active cell to all other cells in a selected range, press F2 and then press Ctrl+Enter.
●
To fill a range with increments of a single value, press Ctrl while you drag the fill handle at the lower-right corner of the cell.
●
To create a custom AutoFill list, select the Edit Custom Lists button on the Popular tab of the Excel Options dialog box.
●
To copy a cell without incrementing, drag the fill handle at the lower-right corner of the selection; or, press Ctrl+D to copy down or Ctrl+R to copy to the right.
●
To make text easier to read, you can enter line breaks in a cell. To enter a line break, press Alt+Enter. Line breaks cause a cell’s contents to wrap within the cell.
●
To enter a fraction, type 0, a space, and then the fraction (using a slash). Excel formats the cell using the Fraction number format.
●
To automatically format a cell with the currency format, type your currency symbol before the value.
●
To enter a value in percent format, type a percent sign after the value. You can also include your local thousand separator symbol to separate thousands (for example, 123,434).
●
To insert the current date, press Ctrl+; (semicolon). To enter the current time into a cell, press Ctrl+Shift+;.
●
To set up a cell or range so that it accepts entries only of a certain type (or within a certain value range), choose the Data➜Data Tools➜Data Validation command.
Object and cell selecting Generally, selecting objects in Excel conforms to standard Windows practices. You can select a range of cells by using the keyboard (by pressing the Shift key, along with the arrow keys) or by clicking and dragging the mouse. To select a large range, click a cell at any corner of the range, scroll to the opposite corner of the range, and press Shift while you click the opposite corner cell.
05_475362-ch01.indd 27
4/14/10 9:25 PM
28
Part I: Basic Information
You can use Ctrl+* (asterisk) to select an entire table. And when a large range is selected, you can use Ctrl+. (period) to move among the four corners of the range. If you’re working in a table (created with the Insert➜Tables➜Table command), you’ll find that (beginning with Excel 2007) Ctrl+A works in a new way. Press it once to select the table cells only. Press Ctrl+A a second time, and it selects the entire table (including the header and totals row). Press it a third time, and it selects all cells on the worksheet. Clicking an object placed on the drawing layer selects the object. An exception occurs if the object has a macro assigned to it. In such a case, clicking the object executes the macro. To select multiple objects or noncontiguous cells, press Ctrl while you select the objects or cells.
The Excel Help System One of Excel’s most important features is its Help system. The Help icon, a blue circle with a question mark in it, is located near the upper-right corner of the Excel window. Clicking the Help icon or pressing the F1 function key displays the Help system window, as shown in Figure 1-8.
Figure 1-8: The Excel Help system window.
The two primary methods for navigating Help are the Search box and the Table of Contents. Typing keywords into the Search box and clicking the Search button displays a list of relevant Help articles in the main window. The Table of Contents lists many related Help articles organized by chapters. The Table of Contents window can be hidden when not in use. Note that the Search button is actually a drop-down control. Click the small arrow, and you can choose the general type
05_475362-ch01.indd 28
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
29
of Help you need. By default, the content shown is downloaded from the Microsoft Office Web site: http://office.microsoft.com. If you do not have Internet access or you prefer to limit Help to articles on your computer, click the Connection status bar in the lower-right corner of the Help window. A small menu appears that allows you to specify which Help system to use.
Cell Formatting Excel provides two types of cell formatting — numeric formatting and stylistic formatting.
Numeric formatting Numeric formatting refers to how a value appears in the cell. In addition to choosing from an extensive list of predefined formats, you can create your own custom number formats in the Number tab of the Format Cells dialog box. (Choose the dialog box launcher at the bottom of the Home➜Number group.) Excel applies some numeric formatting automatically, based on the entry. For example, if you precede a value with your local currency symbol (such as a dollar sign), Excel applies Currency number formatting. If you append a percent symbol, Excel applies Percent formatting. Refer to Appendix B for additional information about creating custom number formats.
The number format doesn’t affect the actual value stored in the cell. For example, suppose that a cell contains the value 3.14159. If you apply a format to display two decimal places, the number appears as 3.14. When you use the cell in a formula, however, the actual value (3.14159) — not the displayed value — is used.
Stylistic formatting Stylistic formatting refers to the cosmetic formatting (colors, shading, fonts, borders, and so on) that you apply in order to make your work look good. The Home➜Font and Home➜Styles groups contain commands to format your cells and ranges. A formatting concept introduced in Excel 2007 is document themes. Basically, themes allow you to set many formatting options at once, such as font, colors, and cell styles. The formatting options contained in a theme are designed to work well together. If you’re not feeling particularly artistic, you can apply a theme and know the colors won’t clash. All the commands for themes are in the Themes group of the Page Layout tab. Don’t overlook Excel’s conditional formatting feature. This handy tool enables you to specify formatting that appears only when certain conditions are met. For example, you can make the cell’s interior red if the cell contains a negative number. Excel 2007 introduced many new conditional formatting options, and Excel 2010 refined them.
05_475362-ch01.indd 29
4/14/10 9:25 PM
30
Part I: Basic Information
See Chapter 19 for more information on conditional formatting.
Tables A table is a specially designated range in a worksheet. Converting a range into a table makes it easier to perform many operations on that data. The data in a table is related in a specific way. The rows represent related objects, and the columns represent specific pieces of information about each of those objects. If, for instance, you have a table of library books, each row would hold the information for one book. Columns might include title, author, publisher, date, and so on. In database terminology, the rows are records, and the columns are fields. If your data is arranged in this fashion, you can designate it as a table by selecting the range and then choosing Insert➜Tables➜Table. Excel inserts generic column headings if none exist; the column heading includes drop-down controls. These drop-down controls, as well as the Table Tools context tab on the Ribbon, provide quick access to many table-related features like sorting, filtering, and formatting. In addition, using formulas within a table offers some clear advantages. See Chapter 9 for more information about the table feature.
Worksheet Formulas and Functions Formulas, of course, make a spreadsheet a spreadsheet. Excel’s formula-building capability is as good as it gets. You will discover this as you explore subsequent chapters in this book. Worksheet functions allow you to perform calculations or operations that would otherwise be impossible. Excel provides a huge number of built-in functions, including dozens of new functions introduced in Excel 2010. See Chapter 4 for more information about worksheet functions.
Most spreadsheets allow you to define names for cells and ranges, but Excel handles names in some unique ways. A name represents an identifier that enables you to refer to a cell, range, value, or formula. Using names makes your formulas easier to create and read. I devote Chapter 3 entirely to names.
05_475362-ch01.indd 30
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
31
Objects on the Drawing Layer As I mention earlier in this chapter, each worksheet has an invisible drawing layer, which holds shapes, SmartArt, charts, pictures, and controls (such as buttons and list boxes). I discuss some of these items in the following sections.
Shapes You can insert a wide variety of shapes from Insert➜Shapes. After you place a shape on your worksheet, you can modify the shape by selecting it and dragging its handles. In addition, you can apply built-in shape styles, fill effects, or 3-D effects to the shape. Also, you can group multiple shapes into a single drawing object, which you’ll find easier to size or position.
Illustrations Pictures, clip art, and SmartArt can be inserted from the Insert➜Illustrations group. Figure 1-9 shows some objects on the drawing layer of a worksheet.
Figure 1-9: Objects on a worksheet drawing layer. Excel makes a great doodle pad.
Linked picture objects A linked picture is a shape object that shows a range. When the range is changed, the shape object changes along with it. To use this object, select a range and press Ctrl+C to copy it. Then choose Home➜Clipboard➜Paste➜Linked Picture. This command is useful if you want to print a noncontiguous selection of ranges. You can “take pictures” of the ranges and then paste the pictures together in a single area, which you can then print.
05_475362-ch01.indd 31
4/14/10 9:25 PM
32
Part I: Basic Information
Controls You can insert a number of different controls on a worksheet. These controls come in two flavors — Form controls and ActiveX controls. Using controls on a worksheet can greatly enhance the worksheet’s usability — often, without using macros. To insert a control, choose Developer➜Controls➜ Insert. Figure 1-10 shows a worksheet with various controls added to the drawing layer: a check box, two sets of option buttons, and a scroll bar. The Ribbon’s Developer tab is not visible by default. To show the Developer tab, rightclick the Ribbon and select Customize The Ribbon to display the Excel Options dialog box. In the list box on the right, place a check mark next to Developer.
If you’d like to see how these controls work, the workbook shown in Figure 1-10 is available on the companion CD-ROM. The file is named worksheet controls.xlsx.
Figure 1-10: Excel enables you to add many controls directly to the drawing layer of a worksheet.
Charts Excel, of course, has excellent charting capabilities. As I mention earlier in this chapter, you can store charts on a chart sheet or you can float them on a worksheet. Excel offers extensive chart customization options. Selecting a chart displays the Chart Tools contextual tab, which contains basic tools to customize your chart. For more control, press Ctrl+1 to display the Format dialog box for the selected elements. In addition, right-clicking a chart element displays a shortcut menu. You can easily create a free-floating chart by selecting the data to be charted and selecting one of the chart types from the Insert➜Charts group. Chapter 17 contains additional information about charts.
05_475362-ch01.indd 32
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
33
Sparkline graphics A new feature in Excel 2010 is Sparkline graphics. A Sparkline is a chart that occupies a single cell. Sparklines are usually used in groups to provide a quick overview of trends in your data. Figure 1-11 shows a worksheet with Sparklines.
Figure 1-11: Sparkline graphics shows trends in your data.
Customizing Excel This section describes two features that enable you to customize Excel — macros and add-ins.
Macros Excel’s VBA programming language is a powerful tool that can make Excel perform otherwise impossible feats. You can classify the procedures that you create with VBA into two general types: h Macros that automate various aspects of Excel h Macros that serve as custom functions that you can use in worksheet formulas Part VI of this book describes how to use and create custom worksheet functions using VBA.
05_475362-ch01.indd 33
4/14/10 9:25 PM
34
Part I: Basic Information
Add-in programs An add-in is a program attached to Excel that gives it additional functionality. For example, you can store custom worksheet functions in an add-in. To attach an add-in, use the Add-Ins tab in the Excel Options dialog box. Excel ships with quite a few add-ins, and you can purchase or download many third-party addins from online services. My Power Utility Pak is an example of an add-in (use the coupon in the back of the book to order a copy at a discounted price). Chapter 23 describes how to create your own add-ins that contain custom worksheet functions.
Internet Features Excel includes a number of features that relate to the Internet. For example, you can save a worksheet or an entire workbook in HTML format, accessible in a Web browser. In addition, you can insert clickable hyperlinks (including e-mail addresses) directly into cells. You can also create Web queries to bring in data stored in a corporate intranet or on the Internet.
Analysis Tools Excel is certainly no slouch when it comes to analysis. After all, most people use a spreadsheet for analysis. Many analytical tasks can be handled with formulas, but Excel offers many other options, which I discuss in the following sections.
Database access Over the years, most spreadsheets have enabled users to work with simple flat database tables. Excel’s database features fall into two main categories: h Worksheet databases: The entire database is stored in a worksheet. In theory, an Excel worksheet database can have no more than 1,048,575 records (because the top row holds the field names) and 16,384 fields (one per column). In practice, such a large database is not possible. h External databases: The data is stored outside Excel, such as in an Access file or in SQL Server. Generally, when the cell pointer resides within a worksheet database, Excel recognizes it and displays the field names whenever possible. For example, if you move the cell pointer within a worksheet database and choose the Data➜Sort & Filter➜Sort command, Excel allows you to select the sort keys by choosing field names from a drop-down list.
05_475362-ch01.indd 34
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
35
A particularly useful feature, filtering, enables you to display only the records that you want to see. When Filter mode is on, you can filter the data by selecting values from pull-down menus (which appear below the field names when you choose the Data➜Sort & Filter➜Filter command). Rows that don’t meet the filter criteria are hidden. See Figure 1-12 for an example. If you convert a worksheet database into a table (by using Insert➜Tables➜Table), filtering is turned on automatically.
Figure 1-12: Excel’s Filter feature makes it easy to view only the database records that meet your criteria.
If you prefer, you can use the traditional spreadsheet database techniques that involve criteria ranges. To do so, choose the Data➜Sort & Filter➜Advanced command. Chapter 9 provides additional details regarding worksheet lists and databases.
Excel can automatically insert (or remove) subtotal formulas in a table that is set up as a database. It also creates an outline from the data so that you can view only the subtotals or any level of detail that you desire.
Outlines A worksheet outline is often useful when working with hierarchical data, such as budgets. Excel can create an outline automatically by examining the formulas in your worksheet (use the Data➜Outline➜Subtotal command). After you’ve created an outline, you can collapse or expand the outline to display various levels of details. Figure 1-13 shows an example of a worksheet outline.
05_475362-ch01.indd 35
4/14/10 9:25 PM
36
Part I: Basic Information
Figure 1-13: Excel can automatically insert subtotal formulas and create outlines.
Scenario management Scenario management is storing input values that drive a model. For example, if you have a sales forecast, you may create scenarios such as best case, worst case, and most likely case. Excel’s Scenario Manager can handle only simple scenario-management tasks, but most users find it adequate. However, it is definitely easier than trying to keep track of different scenarios manually.
Pivot tables One of Excel’s most powerful tools is the pivot table, which enables you to display summarized data in just about any way possible. Data for a pivot table comes from a worksheet database (or table) or an external database, and it is stored in a special cache, which enables Excel to recalculate data rapidly after a pivot table is altered. Chapter 18 contains additional information about pivot tables.
As a companion to a pivot table, Excel also supports the pivot chart feature. Pivot charts enable you to link a chart to a pivot table.
Auditing capabilities Excel also offers useful auditing capabilities that help you identify errors or track the logic in an unfamiliar spreadsheet. To access this feature, choose commands in the Formulas➜Formula Auditing group. Refer to Chapter 21 for more information about Excel’s auditing features.
05_475362-ch01.indd 36
4/14/10 9:25 PM
Chapter 1: Excel in a Nutshell
37
Solver add-in For specialized linear and nonlinear problems, Excel’s Solver add-in calculates solutions to whatif scenarios based on adjustable cells, constraint cells, and, optionally, cells that must be maximized or minimized. Excel 2010 comes with a new version of Solver.
Protection Options Excel offers a number of different protection options. For example, you can protect formulas from being overwritten or modified, protect a workbook’s structure, and protect your VBA code.
Protecting formulas from being overwritten In many cases, you may want to protect your formulas from being overwritten or modified. To do so, you must unlock the cells that you will allow to be overwritten and then protect the sheet. First select the cells that may be overwritten and choose Home➜Cells➜Format➜Lock to unlock those cells. (The command toggles the Locked status.) Next, choose Home➜Cells➜Format➜ Protect Sheet to show the Protect Sheet dialog box. Here you can specify a password if desired. By default, all cells are locked. Locking and unlocking cells has no effect, however, unless you have a protected worksheet.
When you protect a worksheet, the Protect Sheet dialog box (see Figure 1-14) lets you select which elements won’t be protected. For example, you can allow users to sort data or use AutoFiltering on a protected sheet.
Figure 1-14: Select which elements to protect in the Protect Sheet dialog box.
You can also hide your formulas so they won’t appear in the Excel Formula bar when the cell is activated. To do so, select the formula cells and press Ctrl+1 to display the Format Cells dialog box. Click the Protection tab and make sure that the Hidden check box is selected.
05_475362-ch01.indd 37
4/14/10 9:25 PM
38
Part I: Basic Information
Protecting a workbook’s structure When you protect a workbook’s structure, you can’t add or delete sheets. Use the Review➜ Changes➜Protect Workbook command to display the Protect Structure and Windows dialog box, as shown in Figure 1-15. Make sure that you enable the Structure check box. If you also mark the Windows check box, the window can’t be moved or resized.
Figure 1-15: To protect your workbook’s structure, select the Structure check box.
Keep in mind that Excel is not really a secure application. The protection features, even when used with a password, are intended to prevent casual users from accessing various components of your workbook. Anyone who really wants to defeat your protection can probably do so by using readily available password-cracking utilities.
Password-protecting a workbook In addition to protecting individual sheets and the structure of the workbook, you can require a password to open the workbook. To set a password, choose File➜Info➜Protect Workbook➜ Encrypt With Password to display the Encrypt Document dialog box (see Figure 1-16). In this dialog box, you can specify a password to open the workbook.
Figure 1-16: Use the Encrypt Document dialog box to specify a password for a workbook.
05_475362-ch01.indd 38
4/14/10 9:25 PM
2 Basic Facts about Formulas In This Chapter ●
How to enter, edit, and paste names into formulas
●
The various operators used in formulas
●
How Excel calculates formulas
●
Cell and range references used in formulas
●
How to make an exact copy of a formula
●
How to convert formulas to values
●
How to prevent formulas from being viewed
●
The types of formula errors
●
Circular reference messages and correction techniques
●
Excel’s goal seeking feature
This chapter serves as a basic introduction to using formulas in Excel. Although I direct its focus on newcomers to Excel, even veteran Excel users may find some new information here.
Entering and Editing Formulas This section describes the basic elements of a formula. It also explains various ways of entering and editing your formulas.
Formula elements A formula entered into a cell can consist of five elements: h Operators: These include symbols such as + (for addition) and * (for multiplication). h Cell references: These include named cells and ranges that can refer to cells in the current worksheet, cells in another worksheet in the same workbook, or even cells in a worksheet in another workbook.
39
06_475362-ch02.indd 39
4/14/10 9:18 PM
40
Part I: Basic Information
h Values or text strings: Examples include 7.5 (a value) and “Year-End Results” (a string, enclosed in quotes). h Worksheet functions and their arguments: These include functions such as SUM or AVERAGE and their arguments. Function arguments appear in parentheses, and provide input for the function’s calculations. h Parentheses: These control the order in which expressions within a formula are evaluated.
Entering a formula When you type an equal sign into an empty cell, Excel assumes that you are entering a formula because a formula always begins with an equal sign. Excel’s accommodating nature also permits you to begin your formula with a minus sign or a plus sign. However, Excel always inserts the leading equal sign after you enter the formula. As a concession to former Lotus 1-2-3 users, Excel also allows you to use an “at” symbol (@) to begin a formula that starts with a function. For example, Excel accepts either of the following formulas: =SUM(A1:A200) @SUM(A1:A200)
However, after you enter the second formula, Excel replaces the @ symbol with an equal sign. You can enter a formula into a cell in one of two ways: Enter it manually, or enter it by pointing to cells that are used in the formula. I discuss each of these methods in the following sections.
Entering a Formula Manually Entering a formula manually involves, well, entering a formula manually. You simply activate a cell and type an equal sign (=) followed by the formula. As you type, the characters appear in the cell as well as in the Formula bar. You can, of course, use all the normal editing keys when typing a formula. After you insert the formula, press Enter. When you type an array formula, you must press Ctrl+Shift+Enter rather than just Enter. An array formula is a special type of formula, which I discuss in Part IV.
After you press Enter, the cell displays the result of the formula. The formula itself appears in the Formula bar when the cell is activated.
06_475362-ch02.indd 40
4/14/10 9:18 PM
Chapter 2: Basic Facts about Formulas
41
Entering a formula by pointing The other method of entering a formula still involves some manual typing, but you can simply point to the cell references instead of typing them manually. For example, to enter the formula =A1+A2 into cell A3, follow these steps: 1. Move the cell pointer to cell A3. 2. Type an equal sign (=) to begin the formula. Notice that Excel displays Enter in the left side of the status bar. 3. Press ↑ twice. As you press this key, notice that Excel displays a moving border around the cell and that the cell reference (A1) appears in cell A3 and in the Formula bar. Also notice that Excel displays Point in the status bar. If you prefer, you can use your mouse and click cell A1. 4. Type a plus sign (+). The moving border becomes a solid blue border around A1, and Enter reappears in the status bar. The cell cursor also returns to the original cell (A3). 5. Press ↑ one more time. A2 adds to the formula. If you prefer, you can use your mouse and click cell A2. 6. Press Enter to end the formula. Like with typing the formula manually, the cell displays the result of the formula, and the formula appears in the Formula bar when the cell is activated. If you prefer, you can use your mouse and click the check mark icon next to the Formula bar. This method might sound a bit tedious, but it’s actually very efficient once you get the hang of it. Pointing to cell addresses rather than entering them manually is almost always faster and more accurate.
Pasting names As I discuss in Chapter 3, you can assign a name to a cell or range. If your formula uses named cells or ranges, you can type the name in place of the address or choose the name from a list and have Excel insert the name for you automatically.
06_475362-ch02.indd 41
4/14/10 9:18 PM
42
Part I: Basic Information
To insert a name into a formula, position your cursor in the formula where you want the name entered and use one of these two methods: h Press F3 to display the Paste Name dialog box. Select the name and click OK. h Take advantage of the Formula AutoComplete feature. When you type a letter while constructing a formula, Excel displays a list of matching options. These options include functions and names. Use the down-arrow key (↓) to select the name and then press Tab to insert the name in your formula.
Spaces and line breaks Normally, you enter a formula without using any spaces. However, you can use spaces (and even line breaks) within your formulas. Doing so has no effect on the formula’s result but can make the formula easier to read. To enter a line break in a formula, press Alt+Enter. Figure 2-1 shows a formula that contains spaces and line breaks. To make the Formula bar display more than one line, drag the border below the Formula bar downward.
Figure 2-1: This formula contains spaces and line breaks.
Formula limits A formula can consist of up to about 8,000 characters. In the unlikely event that you need to create a formula that exceeds this limit, you must break the formula up into multiple formulas. You also can opt to create a custom function by using Visual Basic for Applications (VBA). Part VI focuses on creating custom functions.
06_475362-ch02.indd 42
4/14/10 9:18 PM
Chapter 2: Basic Facts about Formulas
43
Sample formulas If you follow the above instructions for entering formulas, you can create a variety of formulas. This section provides a look at some sample formulas. h The following formula multiplies 150 × .01, returning 1.5. This formula uses only literal values, so it doesn’t seem very useful. However, it may be useful to show your work when you review your spreadsheet later. =150*.01
h This formula adds the values in cells A1 and A2: =A1+A2
h The next formula subtracts the value in the cell named Expenses from the value in the cell named Income: =Income–Expenses
h The following formula uses the SUM function to add the values in the range A1:A12. =SUM(A1:A12)
h The next formula compares cell A1 with cell C12 by using the = operator. If the values in the two cells are identical, the formula returns TRUE; otherwise, it returns FALSE. =A1=C12
h This final formula subtracts the value in cell B3 from the value in cell B2 and then multiplies the result by the value in cell B4: =(B2–B3)*B4
Editing formulas If you make changes to your worksheet, you may need to edit formulas. Or if a formula returns one of the error values described later in this chapter, you might need to edit the formula to correct the error. You can edit your formulas just as you edit any other cell. Here are several ways to get into cell edit mode: h Double-click the cell. This enables you to edit the cell contents directly in the cell. This technique works only if the Double-click Allows Editing Directly in Cell check box is selected on the Advanced tab in the Excel Options dialog box.
06_475362-ch02.indd 43
4/14/10 9:18 PM
44
Part I: Basic Information
h Press F2. This enables you to edit the cell contents directly in the cell. If the Double-click Allows Editing Directly in Cell check box is not selected, the editing will occur in the Formula bar. h Select the formula cell that you want to edit and then click in the Formula bar. This enables you to edit the cell contents in the Formula bar. When you edit a formula, you can select multiple characters by dragging the mouse over them or by holding down Shift while you use the arrow keys. You can also press Home or End to select from the cursor position to the beginning or end of the current line of the formula. Suppose you have a lengthy formula that contains an error, and Excel won’t let you enter it because of the error. In this case, you can convert the formula to text and tackle it again later. To convert a formula to text, just remove the initial equal sign (=). When you’re ready to return to editing the formula, insert the initial equal sign to convert the cell contents back to a formula.
Using the Formula bar as a calculator If you simply need to perform a calculation, you can use the Formula bar as a calculator. For example, enter the following formula into any cell: =(145*1.05)/12
Because this formula always returns the same result, you may prefer to store the formula’s result rather than the formula. To do so, press F2 to edit the cell. Then press F9, followed by Enter. Excel stores the formula’s result (12.6875), rather than the formula. This technique also works if the formula uses cell references. This technique is most useful when you use worksheet functions. For example, to enter the square root of 221 into a cell, type =SQRT(221), press F9, and then press Enter. Excel enters the result: 14.8660687473185. You also can use this technique to evaluate just part of a formula. Consider this formula: =(145*1.05)/A1
If you want to convert just the expression within the parentheses to a value, get into cell edit mode and select the part that you want to evaluate. In this example, select 145*1.05. Then press F9 followed by Enter. Excel converts the formula to the following: =(152.25)/A1
06_475362-ch02.indd 44
4/14/10 9:18 PM
Chapter 2: Basic Facts about Formulas
45
Using Operators in Formulas As previously discussed, an operator is the basic element of a formula. An operator is a symbol that represents an operation. Table 2-1 shows the Excel-supported operators.
Table 2-1: Excel-Supported Operators Symbol
Operator
+
Addition
–
Subtraction
/
Division
*
Multiplication
%
Percent*
&
Text concatenation
^
Exponentiation
=
Logical comparison (equal to)
>
Logical comparison (greater than)
=
Logical comparison (greater than or equal to)
100”,Amount,”100”)-COUNTIF(Amount,”>200”)
This formula counts the number of values that are greater than 100 and then subtracts the number of values that are greater than 200. The result is the number of cells that contain a value greater than 100 and less than or equal to 200. Creating this type of formula can be confusing because the formula refers to a condition “>200” even though the goal is to count values that are less than or equal to 200. An alternate technique is to use an array formula, such as the one that follows. You may find creating this type of formula easier. {=SUM((Amount>100)*(Amount1000”)
An alternative formula, which works with versions prior to Excel 2007, uses the SUMPRODUCT function. The following formula returns the same result as the previous formula: =SUMPRODUCT((Month=”January”)*(SalesRep=”Brooks”)*(Amount>1000))
12_475362-ch07.indd 190
4/14/10 9:46 PM
Chapter 7: Counting and Summing Techniques
191
Yet another way to perform this count is to use an array formula: {=SUM((Month=”January”)*(SalesRep=”Brooks”)*(Amount>1000))}
Using Or criteria To count cells by using an Or criterion, you can sometimes use multiple COUNTIF functions. The following formula, for example, counts the number of sales made in January or February: =COUNTIF(Month,”January”)+COUNTIF(Month,”February”)
You can also use the COUNTIF function in an array formula. The following array formula, for example, returns the same result as the previous formula: {=SUM(COUNTIF(Month,{“January”,”February”}))}
But if you base your Or criteria on cells other than the cells being counted, the COUNTIF function won’t work. (Refer to Figure 7-2.) Suppose that you want to count the number of sales that meet the following criteria: h Month is January, or h SalesRep is Brooks, or h Amount is greater than 1,000 If you attempt to create a formula that uses COUNTIF, some double counting will occur. The solution is to use an array formula like this: {=SUM(IF((Month=”January”)+(SalesRep=”Brooks”)+(Amount>1000),1))}
Combining And and Or criteria In some cases, you may need to combine And and Or criteria when counting. For example, perhaps you want to count sales that meet the following criteria: h Month is January, and h SalesRep is Brooks, or SalesRep is Cook You can add two COUNTIFS functions to get the desired result: =COUNTIFS(Month,”January”,SalesRep,”Brooks”)+ COUNTIFS(Month,”January”,SalesRep,”Cook”)
12_475362-ch07.indd 191
4/14/10 9:46 PM
192
Part II: Using Functions in Your Formulas
Because you have to repeat the And portion of the criteria in each function’s arguments, using COUNTIFS can produce long formulas with more criteria. When you have a lot of criteria, it makes sense to use an array formula, like this one that produces the same result: {=SUM((Month=”January”)*((SalesRep=”Brooks”)+(SalesRep=”Cook”)))}
Counting the most frequently occurring entry Excel’s MODE function returns the most frequently occurring value in a range. Figure 7-3 shows a worksheet with values in range A1:A10 (named Data). The formula that follows returns 10 because that value appears most frequently in the Data range: =MODE(Data)
The formula returns an #N/A error if the Data range contains no duplicated values.
Figure 7-3: The MODE function returns the most frequently occurring value in a range.
To count the number of times the most frequently occurring value appears in the range (in other words, the frequency of the mode), use the following formula: =COUNTIF(Data,MODE(Data))
This formula returns 5 because the modal value (10) appears five times in the Data range. The MODE function works only for numeric values, and it ignores cells that contain text. To find the most frequently occurring text entry in a range, you need to use an array formula. To count the number of times the most frequently occurring item (text or values) appears in a range named Data, use the following array formula: {=MAX(COUNTIF(Data,Data))}
12_475362-ch07.indd 192
4/14/10 9:46 PM
Chapter 7: Counting and Summing Techniques
193
This next array formula operates like the MODE function except that it works with both text and values: {=INDEX(Data,MATCH(MAX(COUNTIF(Data,Data)),COUNTIF(Data,Data),0))}
If there is more than one most frequent value, the preceding formula returns only the first in the list.
Counting the occurrences of specific text The examples in this section demonstrate various ways to count the occurrences of a character or text string in a range of cells. Figure 7-4 shows a worksheet that demonstrates these examples. Various text appears in the range A1:A10 (named Data); cell B1 is named Text.
Figure 7-4: This worksheet demonstrates various ways to count characters in a range.
The companion CD-ROM contains a workbook named counting text in a range. xlsx that demonstrates the formulas in this section.
Entire cell contents To count the number of cells containing the contents of the Text cell (and nothing else), you can use the COUNTIF function. The following formula demonstrates: =COUNTIF(Data,Text)
For example, if the Text cell contains the string Alpha, the formula returns 2 because two cells in the Data range contain this text. This formula is not case sensitive, so it counts both Alpha (cell A2) and alpha (cell A10). Note, however, that it does not count the cell that contains Alpha Beta (cell A8). The following array formula is similar to the preceding formula, but this one is case sensitive: {=SUM(IF(EXACT(Data,Text),1))}
12_475362-ch07.indd 193
4/14/10 9:46 PM
194
Part II: Using Functions in Your Formulas
Partial cell contents To count the number of cells that contain a string that includes the contents of the Text cell, use this formula: =COUNTIF(Data,”*”&Text&”*”)
For example, if the Text cell contains the text Alpha, the formula returns 3 because three cells in the Data range contain the text alpha (cells A2, A8, and A10). Note that the comparison is not case sensitive. An alternative is a longer array formula that uses the SEARCH function: {=SUM(IF(NOT(ISERROR(SEARCH(text,data))),1))}
The SEARCH function returns an error if Text is not found in Data. The preceding formula counts one for every cell where SEARCH does not find an error. Because SEARCH is not case sensitive, neither is this formula. If you need a case-sensitive count, you can use the following array formula: {=SUM(IF(LEN(Data)-LEN(SUBSTITUTE(Data,Text,””))>0,1))}
If the Text cells contain the text Alpha, the preceding formula returns 2 because the string appears in two cells (A2 and A8). Like the SEARCH function, the FIND function returns an error if Text is not found in Data, as in this alternative array formula: {=SUM(IF(NOT(ISERROR(FIND(text,data))),1))}
Unlike SEARCH, the FIND function is case sensitive.
Total occurrences in a range To count the total number of occurrences of a string within a range of cells, use the following array formula: {=(SUM(LEN(Data))-SUM(LEN(SUBSTITUTE(Data,Text,””))))/ LEN(Text)}
If the Text cell contains the character B, the formula returns 7 because the range contains seven instances of the string. This formula is case sensitive.
12_475362-ch07.indd 194
4/14/10 9:46 PM
Chapter 7: Counting and Summing Techniques
195
The following array formula is a modified version that is not case sensitive: {=(SUM(LEN(Data))-SUM(LEN(SUBSTITUTE(UPPER(Data), UPPER(Text),””))))/LEN(Text)}
Counting the number of unique values The following array formula returns the number of unique values in a range named Data: {=SUM(1/COUNTIF(Data,Data))}
To understand how this formula works, you need a basic understanding of array formulas. (See Chapter 14 for an introduction to this topic.) In Figure 7-5, range A1:A12 is named Data. Range C1:C12 contains the following multicell array formula. A single formula was entered into all 12 cells in the range. {=COUNTIF(Data,Data)}
Figure 7-5: Using an array formula to count the number of unique values in a range.
You can access the workbook count unique.xlsx shown in Figure 7-5 on the companion CD-ROM.
The array in range C1:C12 consists of the count of each value in Data. For example, the number 100 appears three times, so each array element that corresponds to a value of 100 in the Data range has a value of 3.
12_475362-ch07.indd 195
4/14/10 9:46 PM
196
Part II: Using Functions in Your Formulas
Range D1:D12 contains the following array formula: {=1/C1:C12}
This array consists of each value in the array in range C1:C12, divided into 1. For example, each cell in the original Data range that contains a 200 has a value of 0.5 in the corresponding cell in D1:D12. Summing the range D1:D12 gives the number of unique items in Data. The array formula presented at the beginning of this section essentially creates the array that occupies D1:D12 and sums the values. This formula has a serious limitation: If the range contains any blank cells, it returns an error. The following array formula solves this problem: {=SUM(IF(COUNTIF(Data,Data)=0,””,1/COUNTIF(Data,Data)))}
To create an array formula that returns a list of unique items in a range, refer to Chapter 15.
Creating a frequency distribution A frequency distribution basically comprises a summary table that shows the frequency of each value in a range. For example, an instructor may create a frequency distribution of test scores. The table would show the count of As, Bs, Cs, and so on. Excel provides a number of ways to create frequency distributions. You can h Use the FREQUENCY function. h Create your own formulas. h Use the Analysis ToolPak add-in. h Use a pivot table. The frequency distribution.xlsx workbook that demonstrates these four techniques appears on the companion CD-ROM.
The FREQUENCY function The first method that I discuss uses Excel’s FREQUENCY function. This function always returns an array, so you must use it in an array formula entered into a multicell range.
12_475362-ch07.indd 196
4/14/10 9:46 PM
Chapter 7: Counting and Summing Techniques
197
Figure 7-6 shows some data in range A1:E25 (named Data). These values range from 1 to 500. The range G2:G11 contains the bins used for the frequency distribution. Each cell in this bin range contains the upper limit for the bin. In this case, the bins consist of =D2)*(Grades= 75 Then Discount = 0.25 End Function
Notice that each If-Then statement in this procedure is always executed, and the value for Discount can change as the function executes. The final value, however, is the desired value. The preceding examples all used a single statement for the Then clause of the If-Then construct. However, you often need to execute multiple statements if a condition is TRUE. You can still use the If-Then construct, but you need to use an End If statement to signal the end of the statements that make up the Then clause. Here’s an example that executes two statements if the If clause is TRUE: If x > 0 Then y = 2 z = 3 End If
You can also use multiple statements for an If-Then-Else construct. Here’s an example that executes two statements if the If clause is TRUE, and two other statements if the If clause is not TRUE: If x > 0 Then y = 2 z = 3 Else y = –2 z = –3 End If
33_475362-ch24.indd 650
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
651
The Select Case construct The Select Case construct is useful for choosing among three or more options. this construct also works with two options and is a good alternative to using If-Then-Else. The syntax for Select Case is as follows: Select Case testexpression [Case expressionlist–n [instructions–n]] [Case Else [default_instructions]] End Select
The following example of a Select Case construct shows another way to code the GreetMe examples presented in the preceding section: Function GreetMe() Select Case Time Case Is < 0.5 GreetMe = “Good Morning” Case 0.5 To 0.75 GreetMe = “Good Afternoon” Case Else GreetMe = “Good Evening” End Select End Function
And here’s a rewritten version of the Discount function from the previous section, this time using a Select Case construct: Function Discount2(quantity) Select Case quantity Case Is = 75 Discount2 = 0.25 End Select End Function
Any number of instructions can be written below each Case statement; they all execute if that case evaluates to TRUE.
33_475362-ch24.indd 651
4/14/10 10:30 PM
652
Part VI: Developing Custom Worksheet Functions
Looping blocks of instructions Looping is the process of repeating a block of VBA instructions within a procedure. You may know the number of times to loop, or it may be determined by the values of variables in your program. VBA offers a number of looping constructs: h For-Next loops h Do While loops h Do Until loops
For-Next loops The following is the syntax for a For-Next loop: For counter = start To end [Step stepval] [instructions] [Exit For] [instructions] Next [counter]
The following listing is an example of a For-Next loop that does not use the optional Step value or the optional Exit For statement. This function accepts two arguments and returns the sum of all integers between (and including) the arguments: Function SumIntegers(first, last) total = 0 For num = first To last total = total + num Next num SumIntegers = total End Function
The following formula, for example, returns 55 — the sum of all integers from 1 to 10: =SumIntegers(1,10)
In this example, num (the loop counter variable) starts out with the same value as the first variable, and increases by 1 each time the loop repeats. The loop ends when num is equal to the last variable. The total variable simply accumulates the various values of num as it changes during the looping.
33_475362-ch24.indd 652
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
653
When you use For-Next loops, you should understand that the loop counter is a normal variable — it is not a special type of variable. As a result, you can change the value of the loop counter within the block of code executed between the For and Next statements. this is, however, a very bad practice and can cause problems. In fact, you should take special precautions to ensure that your code does not change the loop counter.
You also can use a Step value to skip some values in the loop. Here’s the same function rewritten to sum every other integer between the first and last arguments: Function SumIntegers2(first, last) total = 0 For num = first To last Step 2 total = total + num Next num SumIntegers2 = Total End Function
The following formula returns 25, which is the sum of 1, 3, 5, 7, and 9: =SumIntegers2(1,10)
For-Next loops can also include one or more Exit For statements within the loop. When this statement is encountered, the loop terminates immediately, as the following example demonstrates: Function RowOfLargest(c) NumRows = Rows.Count MaxVal = WorksheetFunction.Max(Columns(c)) For r = 1 To NumRows If Cells(r, c) = MaxVal Then RowOfLargest = r Exit For End If Next r End Function
The RowOfLargest function accepts a column number (1–16,384) for its argument and returns the row number of the largest value in that column. It starts by getting a count of the number of rows in the worksheet. (This varies, depending on the version of Excel.) This number is assigned to the NumRows variable. The maximum value in the column is calculated by using the Excel MAX function, and this value is assigned to the MaxVal variable.
33_475362-ch24.indd 653
4/14/10 10:30 PM
654
Part VI: Developing Custom Worksheet Functions
The For-Next loop checks each cell in the column. When the cell equal to MaxVal is found, the row number (variable r, the loop counter) is assigned to the function’s name, and the Exit For statement ends the procedure. Without the Exit For statement, the loop continues to check all cells in the column — which can take quite a long time! The previous examples use relatively simple loops. But you can have any number of statements in the loop, and you can even nest For-Next loops inside other For-Next loops. The following is VBA code that uses nested For-Next loops to initialize a 10 x 10 x 10 array with the value –1. When the three loops finish executing, each of the 1,000 elements in MyArray contains –1. Dim MyArray(1 to 10, 1 to 10, 1 to 10) For i = 1 To 10 For j = 1 To 10 For k = 1 To 10 MyArray(i, j, k) = –1 Next k Next j Next i
Do While loops A Do While loop is another type of looping structure available in VBA. Unlike a For-Next loop, a Do While loop executes while a specified condition is met. A Do While loop can have one of two syntaxes: Do [While condition] [instructions] [Exit Do] [instructions] Loop
or Do [instructions] [Exit Do] [instructions] Loop [While condition]
As you can see, VBA enables you to put the While condition at the beginning or the end of the loop. The difference between these two syntaxes involves the point in time when the condition is evaluated. In the first syntax, the contents of the loop may never be executed: That is, if the condition is met as soon as the Do statement is executed. In the second syntax, the contents of the loop are always executed at least one time.
33_475362-ch24.indd 654
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
655
The following example is the RowOfLargest function presented in the previous section, rewritten to use a Do While loop (using the first syntax): Function RowOfLargest2(c) NumRows = Rows.Count MaxVal = Application.Max(Columns(c)) r = 1 Do While Cells(r, c) MaxVal r = r + 1 Loop RowOfLargest2 = r End Function
The variable r starts out with a value of 1 and increments within the Do While loop. The looping continues as long as the cell being evaluated is not equal to MaxVal. When the cell is equal to MaxVal, the loop ends, and the function is assigned the value of r. Notice that if the maximum value is in row 1, the looping does not occur. The following procedure uses the second Do While loop syntax. The loop always executes at least once. Function RowOfLargest(c) MaxVal = Application.Max(Columns(c)) r = 0 Do r = r + 1 Loop While Cells(r, c) MaxVal RowOfLargest = r End Function
Do While loops can also contain one or more Exit Do statements. When an Exit Do statement is encountered, the loop ends immediately.
Do Until loops The Do Until loop structure closely resembles the Do While structure. The difference is evident only when the condition is tested. In a Do While loop, the loop executes while the condition is true. In a Do Until loop, the loop executes until the condition is true. Do Until also has two syntaxes: Do [Until condition] [instructions] [Exit Do] [instructions] Loop
33_475362-ch24.indd 655
4/14/10 10:30 PM
656
Part VI: Developing Custom Worksheet Functions
or Do [instructions] [Exit Do] [instructions] Loop [Until condition]
The following example demonstrates the first syntax of the Do Until loop. This example makes the code a bit clearer because it avoids the negative comparison required in the Do While example. Function RowOfLargest4(c) NumRows = Rows.Count MaxVal = Application.Max(Columns(c)) r = 1 Do Until Cells(r, c) = MaxVal r = r + 1 Loop RowOfLargest4 = r End Function
Finally, the following function is the same procedure but is rewritten to use the second syntax of the Do Until loop: Function RowOfLargest5(c) NumRows = Rows.Count MaxVal = Application.Max(Columns(c)) r = 0 Do r = r + 1 Loop Until Cells(r, c) = MaxVal RowOfLargest5 = r End Function
The On Error statement Undoubtedly, you’ve used one of Excel’s worksheet functions in a formula and discovered that the formula returns an error value (for example, #VALUE!). A formula can return an error value in a number of situations, including these: h You omitted one or more required argument(s). h An argument was not the correct data type (for example, text instead of a value). h An argument is outside of a valid numeric range (division by zero, for example).
33_475362-ch24.indd 656
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
657
In many cases, you can ignore error handling within your functions. If the user does not provide the proper number of arguments, the function simply returns an error value. It’s up to the user to figure out the problem. In fact, this is how Excel’s worksheet functions handle errors. In other cases, you want your code to know if errors occurred and then do something about them. Excel’s On Error statement enables you to identify and handle errors. To simply ignore an error, use the following statement: On Error Resume Next
If you use this statement, you can determine whether an error occurs by checking the Number property of the Err object. If this property is equal to zero, an error did not occur. If Err. Number is equal to anything else, an error did occur. The following example is a function that returns the name of a cell or range. If the cell or range does not have a name, an error occurs, and the formula that uses the function returns a #VALUE! error. Function RANGENAME(rng) RANGENAME = rng.Name.Name End Function
The following list shows an improved version of the function. The On Error Resume Next statement causes VBA to ignore the error. The If Err statement checks whether an error occurs. If so, the function returns an empty string. Function RANGENAME(rng) On Error Resume Next RANGENAME = rng.Name.Name If Err.Number 0 Then RANGENAME = “” End Function
The following statement instructs VBA to watch for errors; if an error occurs, it continues executing at a different named location — in this case, a statement labeled ErrHandler: On Error GoTo ErrHandler
The following Function procedure demonstrates this statement. The DIVIDETWO function accepts two arguments (num1 and num2) and returns the result of num1 divided by num2.
33_475362-ch24.indd 657
4/14/10 10:30 PM
658
Part VI: Developing Custom Worksheet Functions
Function DIVIDETWO(num1, num2) On Error GoTo ErrHandler DIVIDETWO = num1 / num2 Exit Function ErrHandler: DIVIDETWO = “ERROR” End Function
The On Error GoTo statement instructs VBA to jump to the statement labeled ErrHandler if an error occurs. As a result, the function returns a string (ERROR) if any type of error occurs while the function is executing. Note the use of the Exit Function statement. Without this statement, the code continues executing, and the error handling code always executes. In other words, the function always returns ERROR. It’s important to understand that the DIVIDETWO function is nonstandard in its approach. Returning an error message string when an error occurs (ERROR) is not how Excel functions work. Excel functions return an actual error value. Chapter 25 contains an example that demonstrates how to return an actual error value from a function.
Using Ranges Many of the custom functions that you develop will work with the data contained in a cell or in a range of cells. Recognize that a range can be a single cell or a group of cells. This section describes some key concepts to make this task easier. The information in this section is intended to be practical, rather than comprehensive. If you want more details, consult Excel’s online help. Chapter 25 contains many practical examples of functions that use ranges. Studying those examples helps to clarify the information in this section.
The For Each-Next construct Your Function procedures often need to loop through a range of cells. For example, you may write a function that accepts a range as an argument. Your code needs to examine each cell in the range and do something. The For Each-Next construct is very useful for this sort of thing. The syntax of the For Each-Next construct is For Each element In group [instructions] [Exit For] [instructions] Next [element]
33_475362-ch24.indd 658
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
659
The following Function procedure accepts a range argument and returns the sum of the squared values in the range: Function SUMOFSQUARES(rng as Range) Dim total as Double Dim cell as Range total = 0 For Each cell In rng total = total + cell ^ 2 Next cell SUMOFSQUARES = total End Function
The following is a worksheet formula that uses the SumOfSquares function: =SumOfSquares(A1:C100)
In this case, the function’s argument is a range that consists of 300 cells. In the preceding example, cell and rng are both variable names. There’s nothing special about either name; you can replace them with any valid variable name.
Referencing a range VBA code can reference a range in a number of different ways: h Using the Range property h Using the Cells property h Using the Offset property
The Range property You can use the Range property to refer to a range directly by using a cell address or name. The following example assigns the value in cell A1 to a variable named Init. In this case, the statement accesses the range’s Value property. Init = Range(“A1”).Value
In addition to the Value property, VBA enables you to access a number of other properties of a range. For example, the following statement counts the number of cells in a range and assigns the value to the Cnt variable:
33_475362-ch24.indd 659
4/14/10 10:30 PM
660
Part VI: Developing Custom Worksheet Functions
Cnt = Range(“A1:C300”).Count
The Range property is also useful for referencing a single cell in a multicell range. For example, you may create a function that is supposed to accept a single-cell argument. If the user specifies a multicell range as the argument, you can use the Range property to extract the upper-left cell in the range. The following example uses the Range property (with an argument of “A1”) to return the value in the upper-left cell of the range represented by the cell argument. Function Square(cell as Range) CellValue = cell.Range(“A1”).Value Square = CellValue ^ 2 End Function
Assume that the user enters the following formula: =Square(C5:C12)
The Square function works with the upper-left cell in C5:C12 (which is C5) and returns the value squared. Many Excel worksheet functions work in this way. For example, if you specify a multicell range as the first argument for the LEFT function, Excel uses the upper-left cell in the range. However, Excel is not consistent. If you specify a multicell range as the argument for the SQRT function, Excel returns an error.
The Cells property Another way to reference a range is to use the Cells property. The Cells property accepts two arguments (a row number and a column number), and returns a single cell. The following statement assigns the value in cell A1 to a variable named FirstCell: FirstCell = Cells(1, 1).Value
The following statement returns the upper-left cell in the range C5:C12: UpperLeft = Range(“C5:C12”).Cells(1,1)
If you use the Cells property without an argument, it returns a range that consists of all cells on the worksheet. In the following example, the TotalCells variable contains the total number of cells in the worksheet: TotalCells = Cells.Count
33_475362-ch24.indd 660
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
661
The following statement uses the Excel COUNTA function to determine the number of nonempty cells in the worksheet: NonEmpty =WorksheetFunction.COUNTA(Cells)
The Offset property The Offset property (like the Range and Cells properties) also returns a Range object. The Offset property is used in conjunction with a range. It takes two arguments that correspond to the relative position from the upper-left cell of the specified Range object. The arguments can be positive (down or right), negative (up or left), or zero. The following example returns the value one cell below cell A1 (that is, cell A2) and assigns it to a variable named NextCell: NextCell = Range(“A1”).Offset(1,0).Value
The following Function procedure accepts a single-cell argument and returns the sum of the eight cells that surround it: Function SumSurroundingCells(cell) Dim Total As Double Dim r As Long, c As Long Total = 0 For r = –1 To 1 For c = –1 To 1 Total = Total + cell.Offset(r, c) Next c Next r SumSurroundingCells = Total – cell End Function
This function uses a nested For-Next loop. So, when the r loop counter is –1, the c loop counter goes from –1 to 1. Nine cells are summed, including the argument cell, which is Offset(0, 0). The final statement subtracts the value of the argument cell from the total. The function returns an error if the argument does not have eight surrounding cells (for example, if it’s in row 1 or column 1). To better understand how the nested loop works, following are nine statements that perform exactly the same calculation: Total Total Total Total Total
33_475362-ch24.indd 661
= = = = =
Total Total Total Total Total
+ + + + +
cell.Offset(–1, –1) ‘ upper left cell.Offset(–1, 0) ‘left cell.Offset(–1, 1) ‘upper right cell.Offset(0, –1) ‘above cell.Offset(0, 0) ‘the cell itself
4/14/10 10:30 PM
662
Total Total Total Total
Part VI: Developing Custom Worksheet Functions
= = = =
Total Total Total Total
+ + + +
cell.Offset(0, cell.Offset(1, cell.Offset(1, cell.Offset(1,
1) ‘right –1) ‘lower left 0) ‘below 1) ‘lower right
Some useful properties of ranges Previous sections in this chapter give you examples that used the Value property for a range. VBA gives you access to many additional range properties. Some of the more useful properties for function writers are briefly described in the following sections. For complete information on a particular property, refer to Excel’s online help.
The Formula property The Formula property returns the formula (as a string) contained in a cell. If you try to access the Formula property for a range that consists of more than one cell, you get an error. If the cell does not have a formula, this property returns a string, which is the cell’s value as it appears in the Formula bar. The following function simply displays the formula for the upper-left cell in a range: Function CELLFORMULA(cell) CELLFORMULA = cell.Range(“A1”).Formula End Function
You can use the HasFormula property to determine whether a cell has a formula.
The Address Property The Address property returns the address of a range as a string. By default, it returns the address as an absolute reference (for example, $A$1:$C$12). The following function, which is not all that useful, returns the address of a range: Function RANGEADDRESS(rng) RANGEADDRESS = rng.Address End Function
For example, the following formula returns the string $A$1:$C$3: =RANGEADDRESS(A1:C3)
The formula below returns the address of a range named MyRange: =RANGEADDRESS(MyRange)
33_475362-ch24.indd 662
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
663
The Count property The Count property returns the number of cells in a range. The following function uses the Count property: Function CELLCOUNT(rng) CELLCOUNT = rng.Count End Function
The following formula returns 9: =CELLCOUNT(A1:C3)
The Count property of a Range object is not the same as the COUNT worksheet function. The Count property returns the number of cells in the range, including empty cells and cells with any kind of data. The COUNT worksheet function returns the number of cells in the range that contain numeric data.
Excel 2007 and later worksheets contain over 17 billion cells compared with a mere 17 million in previous versions. Because of this dramatic increase, the Count property — which returns a Long — may return an error if there are more than 2,147,483,647 cells to be counted. You can use the CountLarge property instead of Count to be safe, but beware that CountLarge does not work in older versions of Excel. In the CELLCOUNT function, the following statement will handle any size range (including all cells on a worksheet): CELLCOUNT = rng.CountLarge
The Parent property The Parent property returns an object that corresponds to an object’s container object. For a Range object, the Parent property returns a Worksheet object (the worksheet that contains the range). The following function uses the Parent property and returns the name of the worksheet of the range passed as an argument: Function SHEETNAME(rng) SHEETNAME = rng.Parent.Name End Function
33_475362-ch24.indd 663
4/14/10 10:30 PM
664
Part VI: Developing Custom Worksheet Functions
The following formula, for example, returns the string Sheet1: =SHEETNAME(Sheet1!A16)
The Name property The Name property returns a Name object for a cell or range. To get the actual cell or range name, you need to access the Name property of the Name object. If the cell or range does not have a name, the Name property returns an error. The following Function procedure displays the name of a range or cell passed as its argument. If the range or cell does not have a name, the function returns an empty string. Note the use of On Error Resume Next. This handles situations in which the range does not have a name. Function RANGENAME(rng) On Error Resume Next RANGENAME = rng.Name.Name If Err.Number 0 Then RANGENAME = “” End Function
The NumberFormat property The NumberFormat property returns the number format (as a string) assigned to a cell or range. The following function simply displays the number format for the upper-left cell in a range: Function NUMBERFORMAT(cell) NUMBERFORMAT = cell.Range(“A1”).NumberFormat End Function
The Font property The Font property returns a Font object for a range or cell. To actually do anything with this Font object, you need to access its properties. For example, a Font object has properties such as Bold, Italic, Name, Color, and so on. The following function returns TRUE if the upper-left cell of its argument is formatted as bold: Function ISBOLD(cell) ISBOLD = cell.Range(“A1”).Font.Bold End Function
33_475362-ch24.indd 664
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
665
A cell’s background color is not part of the Font object; it’s stored in the Interior object. This function returns True if the upper-left cell of its argument is colored red (vbRed is a built-in constant): Function ISREDBKGRD(cell) ISREDBKGRD = cell.Range(“A1”).Interior.Color = vbRed End Function
The Columns and Rows properties The Columns and Rows properties work with columns or rows in a range. For example, the following function returns the number of columns in a range by accessing the Count property: Function COLUMNCOUNT(rng) COLUMNCOUNT = rng.Columns.Count End Function
The EntireRow and EntireColumn properties The EntireRow and EntireColumn properties enable you to work with an entire row or column for a particular cell. The following function accepts a single cell argument and then uses the EntireColumn property to get a range consisting of the cell’s entire column. It then uses the Excel COUNTA function to return the number of nonempty cells in the column. Function NONEMPTYCELLSINCOLUMN(cell) NONEMPTYCELLSINCOLUMN = WorksheetFunction.CountA(cell.EntireColumn) End Function
You cannot use this function in a formula that’s in the same column as the cell argument. Doing so will generate a circular reference.
The Hidden property The Hidden property is used with rows or columns. It returns TRUE if the row or column is hidden. If you try to access this property for a range that does not consist of an entire row or column, you get an error. The following function accepts a single cell argument and returns TRUE if either the cell’s row or the cell’s column is hidden: Function CELLISHIDDEN(cell) If cell.EntireRow.Hidden Or cell.EntireColumn.Hidden Then CELLISHIDDEN = True Else CELLISHIDDEN = False End If End Function
33_475362-ch24.indd 665
4/14/10 10:30 PM
666
Part VI: Developing Custom Worksheet Functions
You can also write this function without using an If-Then-Else construct. In the following function, the expression to the right of the equal sign returns either TRUE or FALSE — and this value is returned by the function: Function CELLISHIDDEN(cell) CELLISHIDDEN = cell.EntireRow.Hidden Or _ cell.EntireColumn.Hidden End Function
The Set keyword An important concept in VBA is the ability to create a new Range object and assign it to a variable — more specifically, an object variable. You do so by using the Set keyword. The following statement creates an object variable named MyRange: Set MyRange = Range(“A1:A10”)
After the statement executes, you can use the MyRange variable in your code in place of the actual range reference. Examples in subsequent sections help to clarify this concept. Creating a Range object is not the same as creating a named range. In other words, you can’t use the name of a Range object in your worksheet formulas.
The Intersect function The Intersect function returns a range that consists of the intersection of two other ranges. For example, consider the two ranges selected in Figure 24-2. These ranges, D3:D10 and B5:F5, contain one cell in common (D5). In other words, D5 is the intersection of D3:D10 and B5:F5. The following Function procedure accepts two range arguments and returns the count of the number of cells that the ranges have in common: Function CELLSINCOMMON(rng1, rng2) Dim CommonCells As Range On Error Resume Next Set CommonCells = Intersect(rng1, rng2) If Err.Number = 0 Then CELLSINCOMMON = CommonCells.CountLarge Else CELLSINCOMMON = 0 End If End Function
33_475362-ch24.indd 666
4/14/10 10:30 PM
Chapter 24: VBA Programming Concepts
667
Figure 24-2: Use the Intersect function to work with the intersection of two ranges.
The CELLSINCOMMON function uses the Intersect function to create a range object named CommonCells. Note the use of On Error Resume Next. This statement is necessary because the Intersect function returns an error if the ranges have no cells in common. If the error occurs, it is ignored. The final statement checks the Number property of the Err object. If it is 0, no error occurs, and the function returns the value of the CountLarge property for the CommonCells object. If an error does occur, Err.Number has a value other than 0, and the function returns 0.
The Union function The Union function combines two or more ranges into a single range. The following statement uses the Union function to create a range object that consists of the first and third columns of a worksheet: Set TwoCols = Union(Range(“A:A”), Range(“C:C”))
The Union function takes between 2 and 30 arguments.
The UsedRange property The UsedRange property returns a Range object that represents the used range of the worksheet. Press Ctrl+End to activate the lower-right cell of the used range. The UsedRange property can be very useful in making your functions more efficient.
33_475362-ch24.indd 667
4/14/10 10:30 PM
668
Part VI: Developing Custom Worksheet Functions
Consider the following Function procedure. This function accepts a range argument and returns the number of formula cells in the range: Function FORMULACOUNT(rng) cnt = 0 For Each cell In rng If cell.HasFormula Then cnt = cnt + 1 Next cell FORMULACOUNT = cnt End Function
In many cases, the preceding function works just fine. But what if the user enters a formula like this one? =FORMULACOUNT(A:C)
The three-column argument consists of 3,145,728 cells. With an argument that consists of one or more entire columns, the function does not work well because it loops through every cell in the range, even those that are well beyond the area of the sheet that’s actually used. The following function is rewritten to make it more efficient: Function FORMULACOUNT(rng) cnt = 0 Set WorkRange = Intersect(rng, rng.Parent.UsedRange) If WorkRange Is Nothing Then FORMULACOUNT = 0 Exit Function End If For Each cell In WorkRange If cell.HasFormula Then cnt = cnt + 1 Next cell FORMULACOUNT = cnt End Function
This function creates a Range object variable named WorkRange that consists of the intersection of the range passed as an argument and the used range of the worksheet. In other words, WorkRange consists of a subset of the range argument that only includes cells in the used range of the worksheet. Note the If-Then construct that checks if the WorkRange is Nothing. That will be the case if the argument for the function is outside of the used range. In such a case, the function returns 0, and execution ends.
33_475362-ch24.indd 668
4/14/10 10:30 PM
25 VBA Custom Function Examples In This Chapter ●
Simple custom function examples
●
A custom function to determine a cell’s data type
●
A custom function to make a single worksheet function act like multiple functions
●
A custom function for generating random numbers and selecting cells at random
●
Custom functions for calculating sales commissions
●
Custom functions for manipulating text
●
Custom functions for counting and summing cells
●
Custom functions that deal with dates
●
A custom function example for returning the last nonempty cell in a column or row
●
Custom functions that work with multiple worksheets
●
Advanced custom function techniques
This chapter is jam-packed with a wide variety of useful (or potentially useful) VBA custom worksheet functions. You can use many of the functions as they are written. You may need to modify other functions to meet your particular needs. For maximum speed and efficiency, these Function procedures declare all variables that are used.
669
34_475362-ch25.indd 669
4/14/10 10:31 PM
670
Part VI: Developing Custom Worksheet Functions
Simple Functions The functions in this section are relatively simple, but they can be very useful. Most of them are based on the fact that VBA can obtain useful information that’s not normally available for use in a formula. For example, your VBA code can access a cell’s HasFormula property to determine whether a cell contains a formula. Oddly, Excel does not have a built-in worksheet function that tells you this. The companion CD-ROM contains the workbook simple functions.xlsm that includes all the functions in this section.
Does a cell contain a formula? The following CELLHASFORMULA function accepts a single-cell argument and returns TRUE if the cell has a formula: Function CELLHASFORMULA(cell As Range) As Boolean ‘ Returns TRUE if cell has a formula CELLHASFORMULA = cell.Range(“A1”).HasFormula End Function
If a multicell range argument is passed to the function, the function works with the upper-left cell in the range.
Returning a cell’s formula The following CELLFORMULA function returns the formula for a cell as a string. If the cell does not have a formula, it returns an empty string. Function CELLFORMULA(cell As Range) As String ‘ Returns the formula in cell, or an ‘ empty string if cell has no formula Dim UpperLeft As Range Set UpperLeft = cell.Range(“A1”) If UpperLeft.HasFormula Then CELLFORMULA = UpperLeft.Formula Else CELLFORMULA = “” End If End Function
This function creates a Range object variable named UpperLeft. This variable represents the upper-left cell in the argument that is passed to the function.
34_475362-ch25.indd 670
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
671
On the CD
Using the functions in this chapter If you see a function listed in this chapter that you find useful, you can use it in your own workbook. All the Function procedures in this chapter are available on the companion CD-ROM. Just open the appropriate workbook (see Appendix D for a description of the files), activate the VB Editor, and copy and paste the function listing to a VBA module in your workbook. If you prefer, you can collect a number of functions and create an add-in (see Chapter 23 for details). It’s impossible to anticipate every function that you’ll ever need. However, the examples in this chapter cover a wide variety of topics, so it’s likely that you can locate an appropriate function and adapt the code for your own use.
Is the cell hidden? The following CELLISHIDDEN function accepts a single cell argument and returns TRUE if the cell is hidden. It is considered a hidden cell if either its row or its column is hidden. Function CELLISHIDDEN(cell As Range) As Boolean ‘ Returns TRUE if cell is hidden Dim UpperLeft As Range Set UpperLeft = cell.Range(“A1”) CELLISHIDDEN = UpperLeft.EntireRow.Hidden Or _ UpperLeft.EntireColumn.Hidden End Function
Returning a worksheet name The following SHEETNAME function accepts a single argument (a range) and returns the name of the worksheet that contains the range. It uses the Parent property of the Range object. The Parent property returns an object — the worksheet object that contains the Range object. Function SHEETNAME(rng As Range) As String ‘ Returns the sheet name for rng SHEETNAME = rng.Parent.Name End Function
The following function is a variation on this theme. It does not use an argument; rather, it relies on the fact that a function can determine the cell from which it was called by using Application.Caller.
34_475362-ch25.indd 671
4/14/10 10:31 PM
672
Part VI: Developing Custom Worksheet Functions
Function SHEETNAME2() As String ‘ Returns the sheet name of the cell that ‘ contains the function SHEETNAME2 = Application.Caller.Parent.Name End Function
In this function, the Caller property of the Application object returns a Range object that corresponds to the cell that contains the function. For example, suppose that you have the following formula in cell A1: =SHEETNAME2()
When the SHEETNAME2 function is executed, the Application.Caller property returns a Range object corresponding to the cell that contains the function. The Parent property returns the Worksheet object, and the Name property returns the name of the worksheet.
Returning a workbook name The next function, WORKBOOKNAME, returns the name of the workbook. Notice that it uses the Parent property twice. The first Parent property returns a Worksheet object, the second Parent property returns a Workbook object, and the Name property returns the name of the workbook. Function WORKBOOKNAME() As String ‘ Returns the workbook name of the cell ‘ that contains the function WORKBOOKNAME = Application.Caller.Parent.Parent.Name End Function
Returning the application’s name The following function, although not very useful, carries this discussion of object parents to the next logical level by accessing the Parent property three times. This function returns the name of the Application object, which is always the string Microsoft Excel. Function APPNAME() As String ‘ Returns the application name of the cell ‘ that contains the function APPNAME = Application.Caller.Parent.Parent.Parent.Name End Function
34_475362-ch25.indd 672
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
673
Understanding object parents Objects in Excel are arranged in a hierarchy. At the top of the hierarchy is the Application object (Excel itself). Excel contains other objects; these objects contain other objects, and so on. The following hierarchy depicts how a Range object fits into this scheme: Application object (Excel) Workbook object Worksheet object Range object In the lingo of object-oriented programming (OOP), a Range object’s parent is the Worksheet object that contains it. A Worksheet object’s parent is the workbook that contains the worksheet. And a Workbook object’s parent is the Application object. Armed with this knowledge, you can make use of the Parent property to create a few useful functions.
Returning Excel’s version number The following function returns Excel’s version number. For example, if you use Excel 2010, it returns the text string 14.0. Function EXCELVERSION() as String ‘ Returns Excel’s version number EXCELVERSION = Application.Version End Function
Note that the EXCELVERSION function returns a string, not a value. The following function returns TRUE if the application is Excel 2007 or later (Excel 2007 is version 12). This function uses the VBA Val function to convert the text string to a value: Function EXCEL2007ORLATER() As Boolean EXCEL2007ORLATER = Val(Application.Version) >= 12 End Function
Returning cell formatting information This section contains a number of custom functions that return information about a cell’s formatting. These functions are useful if you need to sort data based on formatting (for example, sorting all bold cells together).
34_475362-ch25.indd 673
4/14/10 10:31 PM
674
Part VI: Developing Custom Worksheet Functions
The functions in this section use the following statement: Application.Volatile True
This statement causes the function to be reevaluated when the workbook is calculated. You’ll find, however, that these functions don’t always return the correct value. This is because changing cell formatting, for example, does not trigger Excel’s recalculation engine. To force a global recalculation (and update all the custom functions), press Ctrl+Alt +F9.
The following function returns TRUE if its single-cell argument has bold formatting: Function ISBOLD(cell As Range) As Boolean ‘ Returns TRUE if cell is bold Application.Volatile True ISBOLD = cell.Range(“A1”).Font.Bold End Function
The following function returns TRUE if its single-cell argument has italic formatting: Function ISITALIC(cell As Range) As Boolean ‘ Returns TRUE if cell is italic Application.Volatile True ISITALIC = cell.Range(“A1”).Font.Italic End Function
Both of the preceding functions have a slight flaw: They return an error (#VALUE!) if the cell has mixed formatting. For example, it’s possible that only some characters in the cell are bold. The following function returns TRUE only if all the characters in the cell are bold. If the Bold property of the Font object returns Null (indicating mixed formatting), the If statement generates an error, and the function name is never set to TRUE. The function name was previously set to FALSE, so that’s the value returned by the function. Function ALLBOLD(cell As Range) As Boolean ‘ Returns TRUE if all characters in cell are bold Dim UpperLeft As Range Application.Volatile True Set UpperLeft = cell.Range(“A1”) ALLBOLD = False If UpperLeft.Font.Bold Then ALLBOLD = True End Function
34_475362-ch25.indd 674
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
675
The following FILLCOLOR function returns an integer that corresponds to the color index of the cell’s interior (the cell’s fill color). If the cell’s interior is not filled, the function returns –4142. The ColorIndex property ranges from 0 to 56. Function FILLCOLOR(cell As Range) As Long ‘ Returns a value corresponding to ‘ cell’s interior color Application.Volatile True FILLCOLOR = cell.Range(“A1”).Interior.ColorIndex End Function
If a cell is part of a table that uses a style, the FILLCOLOR function does not return the correct color. Similarly, a fill color that results from conditional formatting is not returned by this function.
The following function returns the number format string for a cell: Function NUMBERFORMAT(cell As Range) As String ‘ Returns a string that represents ‘ the cell’s number format Application.Volatile True NUMBERFORMAT = cell.Range(“A1”).NumberFormat End Function
If the cell uses the default number format, the function returns the string General.
Determining a Cell’s Data Type Excel provides a number of built-in functions that can help determine the type of data contained in a cell. These include ISTEXT, ISLOGICAL, and ISERROR. In addition, VBA includes functions such as ISEMPTY, ISDATE, and ISNUMERIC. The following function accepts a range argument and returns a string (Blank, Text, Logical, Error, Date, Time, or Value) that describes the data type of the upper-left cell in the range: Function CELLTYPE(cell As Range) As String ‘ Returns the cell type of the upper-left ‘ cell in a range Dim UpperLeft As Range Application.Volatile True Set UpperLeft = cell.Range(“A1”) Select Case True
34_475362-ch25.indd 675
4/14/10 10:31 PM
676
Part VI: Developing Custom Worksheet Functions
Case UpperLeft.NumberFormat = “@” CELLTYPE = “Text” Case IsEmpty(UpperLeft.Value) CELLTYPE = “Blank” Case WorksheetFunction.IsText(UpperLeft) CELLTYPE = “Text” Case WorksheetFunction.IsLogical(UpperLeft.Value) CELLTYPE = “Logical” Case WorksheetFunction.IsErr(UpperLeft.Value) CELLTYPE = “Error” Case IsDate(UpperLeft.Value) CELLTYPE = “Date” Case InStr(1, UpperLeft.Text, “:”) 0 CELLTYPE = “Time” Case IsNumeric(UpperLeft.Value) CELLTYPE = “Value” End Select End Function
Figure 25-1 shows the CELLTYPE function in use. Column B contains formulas that use the CELLTYPE function with an argument from column A. For example, cell B1 contains the following formula: =CELLTYPE(A1)
Figure 25-1: The CELLTYPE function returns a string that describes the contents of a cell.
The workbook celltype function.xlsm that demonstrates the CELLTYPE function is available on the companion CD-ROM.
34_475362-ch25.indd 676
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
677
A Multifunctional Function This section demonstrates a technique that may be helpful in some situations — the technique of making a single worksheet function act like multiple functions. The following VBA custom function, named STATFUNCTION, takes two arguments — the range (rng) and the operation (op). Depending on the value of op, the function returns a value computed by using any of the following worksheet functions: AVERAGE, COUNT, MAX, MEDIAN, MIN, MODE, STDEV, SUM, or VAR. For example, you can use this function in your worksheet: =STATFUNCTION(B1:B24,A24)
The result of the formula depends on the contents of cell A24, which should be a string, such as Average, Count, Max, and so on. You can adapt this technique for other types of functions. Function STATFUNCTION(rng As Variant, op As String) As Variant Select Case UCase(op) Case “SUM” STATFUNCTION = Application.Sum(rng) Case “AVERAGE” STATFUNCTION = Application.Average(rng) Case “MEDIAN” STATFUNCTION = Application.Median(rng) Case “MODE” STATFUNCTION = Application.Mode(rng) Case “COUNT” STATFUNCTION = Application.Count(rng) Case “MAX” STATFUNCTION = Application.Max(rng) Case “MIN” STATFUNCTION = Application.Min(rng) Case “VAR” STATFUNCTION = Application.Var(rng) Case “STDEV” STATFUNCTION = Application.StDev(rng) Case Else STATFUNCTION = CVErr(xlErrNA) End Select End Function
Figure 25-2 shows the STATFUNCTION function that is used in conjunction with a drop-down list generated by Excel’s Data➜Data Tools➜Data Validation command. The formula in cell C14 is as follows: =STATFUNCTION(C1:C12,B14)
34_475362-ch25.indd 677
4/14/10 10:31 PM
678
Part VI: Developing Custom Worksheet Functions
Figure 25-2: Selecting an operation from the list displays the result in cell C14.
The workbook, statfunction function.xlsm, shown in Figure 25-2, is available on the companion CD-ROM.
The following STATFUNCTION2 function is a much simpler approach that works exactly like the STATFUNCTION function. It uses the Evaluate method to evaluate an expression. Function STATFUNCTION2(rng As Range, op As String) As Double STATFUNCTION2 = Evaluate(Op & “(“ & _ rng.Address(external:=True) & “)”) End Function
For example, assume that the rng argument is C1:C12 and also that the op argument is the string SUM. The expression that is used as an argument for the Evaluate method is SUM(C1:C12)
The Evaluate method evaluates its argument and returns the result. In addition to being much shorter, a benefit of this version of STATFUNCTION is that it’s not necessary to list all the possible functions.
34_475362-ch25.indd 678
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
679
Worksheet function data types You may have noticed some differences in the data types used for functions and arguments so far. For instance, in STATFUNCTION, the variable rng was declared as a Variant, while the same variable was declared as a Range in STATFUNCTION2. Also, the former’s return value was declared as a Variant, while the latter’s is a Double data type. Data types are two-edged swords. They can be used to limit the type of data that can be passed to, or returned from, a function, but they can also reduce the flexibility of the function. Using Variant data types maximizes flexibility but slows execution speed. One of the possible return values of STATFUNCTION is an error, in the Case Else section of the Select Case statement. That means that the function can return a Double data type or an Error. The most restrictive data type that can hold both an Error and a Double is a Variant (which can hold anything), so the function is typed as a Variant. On the other hand, STATFUNCTION2 does not have any provision for returning an error, so it’s typed as the more restrictive Double data type. Numeric data in cells is treated as a Double even if it looks like an Integer. The rng arguments are also typed differently. In STATFUNCTION2, the Address property of the Range object is used. Because of this, you must pass a Range to the function, or it will return an error. However, there is nothing in STATFUNCTION that forces rng to be a Range. By declaring rng as a Variant, the user has the flexibility to provide inputs in other ways. Excel will happily try to convert whatever it’s given into something it can use. If it can’t convert it, the result will surely be an error. A user can enter the following formula: =STATFUNCTION({123.45,643,893.22},”Min”)
Neither argument is a cell reference, but Excel doesn’t mind. It can find the minimum of an array constant as easily as a range of values. It works the other way too, as in the case of the second argument. If a cell reference is supplied, Excel will try to convert it to a String and will have no problem doing so. In general, you should use the most restrictive data types possible for your situation while providing for the most user flexibility.
Generating Random Numbers This section presents functions that deal with random numbers. One generates random numbers that don’t change. The other selects a cell at random from a range. The functions in this section are available on the companion CD-ROM. The filename is random functions.xlsm.
34_475362-ch25.indd 679
4/14/10 10:31 PM
680
Part VI: Developing Custom Worksheet Functions
Generating random numbers that don’t change You can use the Excel RAND function to quickly fill a range of cells with random values. But, as you may have discovered, the RAND function generates a new random number whenever the worksheet is recalculated. If you prefer to generate random numbers that don’t change with each recalculation, use the following STATICRAND Function procedure: Function STATICRAND() As Double ‘ Returns a random number that doesn’t ‘ change when recalculated STATICRAND = Rnd End Function
The STATICRAND function uses the VBA Rnd function, which, like Excel’s RAND function, returns a random number between 0 and 1. When you use STATICRAND, however, the random numbers don’t change when the sheet is calculated. Pressing F9 does not generate new values from the STATICRAND function, but pressing Ctrl+Alt+F9 (Excel’s “global recalc” key combination) does.
Following is another version of the function that returns a random integer within a specified range of values: Function STATICRANDBETWEEN(lo As Long, hi As Long) As Long ‘ Returns a random integer that doesn’t ‘ change when recalculated STATICRANDBETWEEN = Int((hi – lo + 1) * Rnd + lo) End Function
For example, if you want to generate a random integer between 1 and 1000, you can use a formula such as =STATICRANDBETWEEN(1,1000)
Selecting a cell at random The following function, named DRAWONE, randomly chooses one cell from an input range and returns the cell’s contents: Function DRAWONE(rng As Variant) As Double ‘ Chooses one cell at random from a range DRAWONE = rng(Int((rng.Count) * Rnd + 1)) End Function
34_475362-ch25.indd 680
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
681
Controlling function recalculation When you use a custom function in a worksheet formula, when is it recalculated? Custom functions behave like Excel’s built-in worksheet functions. Normally, a custom function is recalculated only when it needs to be recalculated — that is, when you modify any of a function’s arguments — but you can force functions to recalculate more frequently. Adding the following statement to a Function procedure makes the function recalculate whenever the workbook is recalculated: Application.Volatile True
The Volatile method of the Application object has one argument (either True or False). Marking a Function procedure as “volatile” forces the function to be calculated whenever calculation occurs in any cell in the worksheet. For example, the custom STATICRAND function presented in this chapter can be changed to emulate the Excel RAND() function by using the Volatile method, as follows: Function NONSTATICRAND() ‘ Returns a random number that ‘ changes when the sheet is recalculated Application.Volatile True NONSTATICRAND = Rnd End Function
Using the False argument of the Volatile method causes the function to be recalculated only when one or more of its arguments change (if a function has no arguments, this method has no effect). By default, all functions work as if they include an Application.Volatile False statement.
If you use this function, you’ll find that it is not recalculated when the worksheet is calculated. In other words, the function is not a volatile function. (For more information about controlling recalculation, see the nearby sidebar, “Controlling function recalculation.” You can make the function volatile by adding the following statement: Application.Volatile True
After doing so, the DRAWONE function displays a new random cell value whenever the sheet is calculated.
34_475362-ch25.indd 681
4/14/10 10:31 PM
682
Part VI: Developing Custom Worksheet Functions
A more general function, one that accepts array constants as well as ranges, is shown here: Function DRAWONE2(rng As Variant) As Variant ‘ Chooses one value at random from an array Dim ArrayLen As Long If TypeName(rng) = “Range” Then DRAWONE2 = rng(Int((rng.Count) * Rnd + 1)).Value Else ArrayLen = UBound(rng) – LBound(rng) + 1 DRAWONE2 = rng(Int(ArrayLen * Rnd + 1)) End If End Function
This function uses the VBA built-in TypeName function to determine whether the argument passed is a Range. If not, it’s assumed to be an array. Following is a formula that uses the DRAWONE2 function. This formula returns a text string that corresponds to a suit in a deck of cards: =DRAWONE2({“Clubs”,”Hearts”,”Diamonds”,”Spades”})
Following is a formula that has the same result, written using Excel’s built-in functions: =CHOOSE(RANDBETWEEN(1,3),”Clubs”,”Hearts”,”Diamonds”,”Spades”)
I present two additional functions that deal with randomization later in this chapter (see the “Advanced Function Techniques” section).
Calculating Sales Commissions Sales managers often need to calculate the commissions earned by their sales forces. The calculations in the function example presented here are based on a sliding scale: Employees who sell more earn a higher commission rate (see Table 25-1). For example, a salesperson with sales between $10,000 and $19,999 qualifies for a commission rate of 10.5 percent.
Table 25-1: Commission Rates for Monthly Sales Monthly Sales
Commission Rate
Less than $10,000
8.0%
$10,000 to $19,999
10.5%
$20,000 to $39,999
12.0%
$40,000 or more
14.0%
34_475362-ch25.indd 682
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
683
You can calculate commissions for various sales amounts entered into a worksheet in several ways. You can use a complex formula with nested IF functions, such as the following: =IF(A1= 40000 COMMISSION2 = Sales * Tier4 Case Is >= 20000 COMMISSION2 = Sales * Tier3 Case Is >= 10000 COMMISSION2 = Sales * Tier2 Case Is < 10000 COMMISSION2 = Sales * Tier1 End Select COMMISSION2 = COMMISSION2 + (COMMISSION2 * Years / 100) End Function
Figure 25-3 shows the COMMISSION2 function in use. The formula in cell D2 is =COMMISSION2(B2,C2)
The workbook, commission function.xlsm, shown in Figure 25-3, is available on the companion CD-ROM.
34_475362-ch25.indd 684
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
685
Figure 25-3: Calculating sales commissions based on sales amount and years employed.
Text Manipulation Functions Text strings can be manipulated with functions in a variety of ways, including reversing the display of a text string, scrambling the characters in a text string, or extracting specific characters from a text string. This section offers a number of function examples that manipulate text strings. The companion CD-ROM contains a workbook named text manipulation functions.xlsm that demonstrates all the functions in this section.
Reversing a string The following REVERSETEXT function returns the text in a cell backward: Function REVERSETEXT(text As String) As String ‘ Returns its argument, reversed REVERSETEXT = StrReverse(text) End Function
This function simply uses the VBA StrReverse function. The following formula, for example, returns tfosorciM: =REVERSETEXT(“Microsoft”)
Scrambling text The following function returns the contents of its argument with the characters randomized. For example, using Microsoft as the argument may return oficMorts, or some other random permutation.
34_475362-ch25.indd 685
4/14/10 10:31 PM
686
Part VI: Developing Custom Worksheet Functions
Function SCRAMBLE(text As Variant) As String ‘ Scrambles its string argument Dim TextLen As Long Dim i As Long Dim RandPos As Long Dim Temp As String Dim Char As String * 1 If TypeName(text) = “Range” Then Temp = text.Range(“A1”).text ElseIf IsArray(text) Then Temp = text(LBound(text)) Else Temp = text End If TextLen = Len(Temp) For i = 1 To TextLen Char = Mid(Temp, i, 1) RandPos = WorksheetFunction.RandBetween(1, TextLen) Mid(Temp, i, 1) = Mid(Temp, RandPos, 1) Mid(Temp, RandPos, 1) = Char Next i SCRAMBLE = Temp End Function
This function loops through each character and then swaps it with another character in a randomly selected position. You may be wondering about the use of Mid. Note that when Mid is used on the right side of an assignment statement, it is a function. However, when Mid is used on the left side of the assignment statement, it is a statement. Consult the Help system for more information about Mid.
Returning an acronym The ACRONYM function returns the first letter (in uppercase) of each word in its argument. For example, the following formula returns IBM: =ACRONYM(“International Business Machines”)
The listing for the ACRONYM Function procedure follows: Function ACRONYM(text As String) As String ‘ Returns an acronym for text Dim TextLen As Long Dim i As Long text = Application.Trim(text) TextLen = Len(text) ACRONYM = Left(text, 1)
34_475362-ch25.indd 686
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
687
For i = 2 To TextLen If Mid(text, i, 1) = “ “ Then ACRONYM = ACRONYM & Mid(text, i + 1, 1) End If Next i ACRONYM = UCase(ACRONYM) End Function
This function uses the Excel TRIM function to remove any extra spaces from the argument. The first character in the argument is always the first character in the result. The For-Next loop examines each character. If the character is a space, the character after the space is appended to the result. Finally, the result converts to uppercase by using the VBA UCase function.
Does the text match a pattern? The following function returns TRUE if a string matches a pattern composed of text and wildcard characters. The ISLIKE function is remarkably simple, and is essentially a wrapper for the useful VBA Like operator. Function ISLIKE(text As String, pattern As String) As Boolean ‘ Returns true if the first argument is like the second ISLIKE = text Like pattern End Function
The supported wildcard characters are as follows: ?
Matches any single character
*
Matches zero or more characters
#
Matches any single digit (0–9)
[list]
Matches any single character in the list
[!list]
Matches any single character not in the list
The following formula returns TRUE because the question mark (?) matches any single character. If the first argument were “Unit12”, the function would return FALSE. =ISLIKE(“Unit1”,”Unit?”)
The function also works with values. The following formula, for example, returns TRUE if cell A1 contains a value that begins with 1 and has exactly three numeric digits: =ISLIKE(A1,”1##”)
34_475362-ch25.indd 687
4/14/10 10:31 PM
688
Part VI: Developing Custom Worksheet Functions
The following formula returns TRUE because the first argument is a single character contained in the list of characters specified in the second argument: =ISLIKE(“a”,”[aeiou]”)
If the character list begins with an exclamation point (!),the comparison is made with characters not in the list. For example, the following formula returns TRUE because the first argument is a single character that does not appear in the second argument’s list: =ISLIKE(“g”,”[!aeiou]”)
To match one of the special characters from the table above, put that character in brackets. This formula returns TRUE because the pattern is looking for three consecutive question marks. The question marks in the pattern are in brackets so they no longer represent any single character: =ISLIKE(“???”,”[?][?][?]”)
The Like operator is very versatile. For complete information about the VBA Like operator, consult the Help system.
Does a cell contain a particular word What if you need to determine if a particular word is contained in a string? Excel’s FIND function can determine if a text string is contained in another text string. For example, the formula that follows returns 5, the character position of rate in the string The rate has changed: =FIND(“rate”,”The rate has changed”)
The following formula also returns 5: =FIND(“rat”,”The rate has changed”)
However, Excel provides no way to determine if a particular word is contained in a string. Here’s a VBA function that returns TRUE if the second argument is contained in the first argument: Function EXACTWORDINSTRING(Text As String, Word As String) As Boolean EXACTWORDINSTRING = “ “ & UCase(Text) & _ “ “ Like “*[!A–Z]” & UCase(Word) & “[!A–Z]*” End Function
34_475362-ch25.indd 688
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
689
Figure 25-4 shows this function in use. Column A contains the text used as the first argument, and column B contains the text used as the second argument. Cell C1 contains this formula, which was copied down the column: =EXACTWORDINSTRING(A1,B1)
Figure 25-4: A VBA function that determines if a particular word is contained in a string.
Thanks to Rick Rothstein for suggesting this function — which is much more efficient than my original function.
A workbook that demonstrates the EXACTWORDINSTRING function is available on the companion CD-ROM. The filename is exact word.xlsm.
Does a cell contain text? A number of Excel’s worksheet functions are at times unreliable when dealing with text in a cell. For example, the ISTEXT function returns FALSE if its argument is a number that’s formatted as Text. The following CELLHASTEXT function returns TRUE if the cell argument contains text or contains a value formatted as Text: Function CELLHASTEXT(cell As Range) As Boolean ‘ Returns TRUE if cell contains a string ‘ or cell is formatted as Text Dim UpperLeft as Range CELLHASTEXT = False Set UpperLeft = cell.Range(“A1”) If UpperLeft.NumberFormat = “@” Then CELLHASTEXT = True Exit Function End If If Not IsNumeric(UpperLeft.Value) Then CELLHASTEXT = True Exit Function End If End Function
34_475362-ch25.indd 689
4/14/10 10:31 PM
690
Part VI: Developing Custom Worksheet Functions
The following formula returns TRUE if cell A1 contains a text string or if the cell is formatted as Text: =CELLHASTEXT(A1)
Extracting the nth Element from a String The EXTRACTELEMENT function is a custom worksheet function that extracts an element from a text string based on a specified separator character. Assume that cell A1 contains the following text: 123-456-789-9133-8844
For example, the following formula returns the string 9133, which is the fourth element in the string. The string uses a hyphen (-) as the separator. =EXTRACTELEMENT(A1,4,”-”)
The EXTRACTELEMENT function uses three arguments: h txt: The text string from which you’re extracting. This can be a literal string or a cell reference. h n: An integer that represents the element to extract. h separator: A single character used as the separator. If you specify a space as the Separator character, multiple spaces are treated as a single space (almost always what you want). If n exceeds the number of elements in the string, the function returns an empty string.
The VBA code for the EXTRACTELEMENT function follows: Function EXTRACTELEMENT(Txt As String, n As Long, Separator As String) As String ‘ Returns the nth element of a text string, where the ‘ elements are separated by a specified separator character Dim AllElements As Variant AllElements = Split(Txt, Separator) EXTRACTELEMENT = AllElements(n – 1) End Function
This function uses the VBA Split function, which returns a variant array that contains each element of the text string. This array begins with 0 (not 1), so using n–1 references the desired element.
34_475362-ch25.indd 690
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
691
Spelling out a number The SPELLDOLLARS function returns a number spelled out in text — as on a check. For example, the following formula returns the string One hundred twenty-three and 45/100 dollars: =SPELLDOLLARS(123.45)
Figure 25-5 shows some additional examples of the SPELLDOLLARS function. Column C contains formulas that use the function. For example, the formula in C1 is =SPELLDOLLARS(A1)
Note that negative numbers are spelled out and enclosed in parentheses.
Figure 25-5: Examples of the SPELLDOLLARS function.
The SPELLDOLLARS function is too lengthy to list here, but you can view the complete listing in spelldollars function.xlsm on the companion CD-ROM.
Counting Functions Chapter 7 contains many formula examples to count cells based on various criteria. If you can’t arrive at a formula-based solution for a counting problem, then you can probably create a custom function. This section contains three functions that perform counting. The companion CD-ROM contains the workbook counting functions.xlsm that demonstrates the functions in this section.
34_475362-ch25.indd 691
4/14/10 10:31 PM
692
Part VI: Developing Custom Worksheet Functions
Counting pattern-matched cells The COUNTIF function accepts limited wildcard characters in its criteria: the question mark and the asterisk, to be specific. If you need more robust pattern matching, you can use the LIKE operator in a custom function. Function COUNTLIKE(rng As Range, pattern As String) As Long ‘ Count the cells in a range that match a pattern Dim cell As Range Dim cnt As Long For Each cell In rng.Cells If cell.Text Like pattern Then cnt = cnt + 1 Next cell COUNTLIKE = cnt End Function
The following formula counts the number of cells in B4:B11 that contain the letter e: =COUNTLIKE(B4:B11,”*[eE]*”)
Counting sheets in a workbook The following COUNTSHEETS function accepts no arguments and returns the number of sheets in the workbook from where it’s called: Function COUNTSHEETS() As Long COUNTSHEETS = Application.Caller.Parent.Parent.Sheets.Count End Function
This function uses Application.Caller to get the range where the formula was entered. Then it uses two Parent properties to go to the sheet and the workbook. Once at the workbook level, the Count property of the Sheets property is returned. The count includes worksheets and chart sheets.
Counting words in a range The WORDCOUNT function accepts a range argument and returns the number of words in that range:
34_475362-ch25.indd 692
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
693
Function WORDCOUNT(rng As Range) As Long ‘ Count the words in a range of cells Dim cell As Range Dim WdCnt As Long Dim tmp As String For Each cell In rng.Cells tmp = Application.Trim(cell.Value) If WorksheetFunction.IsText(tmp) Then WdCnt = WdCnt + (Len(tmp) – _ Len(Replace(tmp, “ “, “”)) + 1) End If Next cell WORDCOUNT = WdCnt End Function
I use a variable, tmp, to store the cell contents with extra spaces removed. Looping through the cells in the supplied range, the ISTEXT worksheet function is used to determine whether the cell has text. If it does, the number of spaces are counted and added to the total. Then one more space is added because a sentence with three spaces has four words. Spaces are counted by comparing the length of the text string with the length after the spaces have been removed with the VBA Replace function.
Counting colors The COUNTREDS function accepts a range argument and returns the number of cells whose font is red. Function COUNTREDS(rng As Range) As Long ‘ Count cells whose font color is red Dim cell As Range For Each cell In rng.Cells If cell.Font.Color = vbRed Then COUNTREDS = COUNTREDS + 1 Next cell End Function
The Color property of each cell’s Font object is compared with vbRed, which is a built-in constant whose intrinsic value is the same as Excel’s value for the color red. This function is very specialized. However, a more general function — one in which the color to be counted is supplied as an argument — could be written. Although this section deals with counting, many of the functions can easily be converted into summing functions. The COUNTREDS function, for example, could be changed to SUMREDS with only a slight change to the loop: SUMREDS = SUMREDS + cell.Value
34_475362-ch25.indd 693
4/14/10 10:31 PM
694
Part VI: Developing Custom Worksheet Functions
Date Functions Chapter 6 presents a number of useful Excel functions and formulas for calculating dates, times, and time periods by manipulating date and time serial values. This section presents additional functions that deal with dates. The companion CD-ROM contains a workbook, date functions.xlsm, that demonstrates the functions presented in this section.
Calculating the next Monday The following NEXTMONDAY function accepts a date argument and returns the date of the following Monday: Function NEXTMONDAY(d As Date) As Date NEXTMONDAY = d + 8 – WeekDay(d, vbMonday) End Function
This function uses the VBA WeekDay function, which returns an integer that represents the day of the week for a date (1 = Sunday, 2 = Monday, and so on). It also uses a predefined constant, vbMonday. The following formula returns 12/27/2010, which is the first Monday after Christmas Day, 2010 (which is a Saturday): =NEXTMONDAY(DATE(2010,12,25))
The function returns a date serial number. You will need to change the number format of the cell to display this serial number as an actual date.
If the argument passed to the NEXTMONDAY function is a Monday, the function returns the following Monday. If you prefer the function to return the same Monday, use this modified version: Function NEXTMONDAY2(d As Date) As Date If WeekDay(d) = vbMonday Then NEXTMONDAY2 = d Else NEXTMONDAY2 = d + 8 – WeekDay(d, vbMonday) End If End Function
34_475362-ch25.indd 694
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
695
Calculating the next day of the week The following NEXTDAY function is a variation on the NEXTMONDAY function. This function accepts two arguments: A date and an integer between 1 and 7 that represents a day of the week (1 = Sunday, 2 = Monday, and so on). The NEXTDAY function returns the date for the next specified day of the week. Function NEXTDAY(d As Date, day As Integer) As Variant ‘ Returns the next specified day ‘ Make sure day is between 1 and 7 If day < 1 Or day > 7 Then NEXTDAY = CVErr(xlErrNA) Else NEXTDAY = d + 8 – WeekDay(d, day) End If End Function
The NEXTDAY function uses an If statement to ensure that the day argument is valid (that is, between 1 and 7). If the day argument is not valid, the function returns #N/A. Because the function can return a value other than a date, it is declared as type Variant.
Which week of the month? The following MONTHWEEK function returns an integer that corresponds to the week of the month for a date: Function MONTHWEEK(d As Date) As Variant ‘ Returns the week of the month for a date Dim FirstDay As Integer ‘
Check for valid date argument If Not IsDate(d) Then MONTHWEEK = CVErr(xlErrNA) Exit Function End If
‘
Get first day of the month FirstDay = WeekDay(DateSerial(Year(d), Month(d), 1))
‘
Calculate the week number MONTHWEEK = Application.RoundUp((FirstDay + day(d) – 1) / 7, 0) End Function
34_475362-ch25.indd 695
4/14/10 10:31 PM
696
Part VI: Developing Custom Worksheet Functions
Working with dates before 1900 Many users are surprised to discover that Excel can’t work with dates prior to the year 1900. To correct this deficiency, I created a series of extended date functions. These functions enable you to work with dates in the years 0100 through 9999. The extended date functions are h XDATE(y,m,d,fmt): Returns a date for a given year, month, and day. As an option, you can provide a date formatting string. h XDATEADD(xdate1,days,fmt): Adds a specified number of days to a date. As an option, you can provide a date formatting string. h XDATEDIF(xdate1,xdate2): Returns the number of days between two dates. h XDATEYEARDIF(xdate1,xdate2): Returns the number of full years between two dates (useful for calculating ages). h XDATEYEAR(xdate1): Returns the year of a date. h XDATEMONTH(xdate1): Returns the month of a date. h XDATEDAY(xdate1): Returns the day of a date. h XDATEDOW(xdate1): Returns the day of the week of a date (as an integer between 1 and 7). Figure 25-6 shows a workbook that uses a few of these functions.
Figure 25-6: Examples of the extended date function.
34_475362-ch25.indd 696
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
697
These functions are available on the companion CD-ROM, in a file named extended date functions.xlsm. The CD also contains a Word file (extended date functions help.docx) that describes these functions.
The extended date functions don’t make any adjustments for changes made to the calendar in 1582. Consequently, working with dates prior to October 15, 1582, may not yield correct results.
Returning the Last Nonempty Cell in a Column or Row This section presents two useful functions: LASTINCOLUMN, which returns the contents of the last nonempty cell in a column, and LASTINROW, which returns the contents of the last nonempty cell in a row. Chapter 15 presents array formulas for this task, but you may prefer to use a custom function. The companion CD-ROM contains last nonempty cell.xlsm, a workbook that demonstrates the functions presented in this section.
Each of these functions accepts a range as its single argument. The range argument can be a column reference (for LASTINCOLUMN) or a row reference (for LASTINROW). If the supplied argument is not a complete column or row reference (such as 3:3 or D:D), the function uses the column or row of the upper-left cell in the range. For example, the following formula returns the contents of the last nonempty cell in column B: =LASTINCOLUMN(B5)
The following formula returns the contents of the last nonempty cell in row 7: =LASTINROW(C7:D9)
The LASTINCOLUMN function The following is the LASTINCOLUMN function:
34_475362-ch25.indd 697
4/14/10 10:31 PM
698
Part VI: Developing Custom Worksheet Functions
Function LASTINCOLUMN(rng As Range) As Variant ‘ Returns the contents of the last nonempty cell in a column Dim LastCell As Range With rng.Parent With .Cells(.Rows.Count, rng.Column) If Not IsEmpty(.Value) Then LASTINCOLUMN = .Value ElseIf IsEmpty(.End(xlUp).Value) Then LASTINCOLUMN = “” Else LASTINCOLUMN = .End(xlUp).Value End If End With End With End Function
Notice the references to the Parent of the range. This is done in order to make the function work with arguments that refer to a different worksheet or workbook.
The LASTINROW function The following is the LASTINROW function: Function LASTINROW(rng As Range) As Variant ‘ Returns the contents of the last nonempty cell in a row With rng.Parent With .Cells(rng.Row, .Columns.Count) If Not IsEmpty(.Value) Then LASTINROW = .Value ElseIf IsEmpty(.End(xlToLeft).Value) Then LASTINROW = “” Else LASTINROW = .End(xlToLeft).Value End If End With End With End Function
In Chapter 15, I describe array formulas that return the last cell in a column or row.
34_475362-ch25.indd 698
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
699
Multisheet Functions You may need to create a function that works with data contained in more than one worksheet within a workbook. This section contains two VBA custom functions that enable you to work with data across multiple sheets, including a function that overcomes an Excel limitation when copying formulas to other sheets. The companion CD-ROM contains the workbook multisheet functions.xlsm that demonstrates the multisheet functions presented in this section.
Returning the maximum value across all worksheets If you need to determine the maximum value in a cell (for example, B1) across a number of worksheets, use a formula like this one: =MAX(Sheet1:Sheet4!B1)
This formula returns the maximum value in cell B1 for Sheet1, Sheet4, and all of the sheets in between. But what if you add a new sheet (Sheet5) after Sheet4? Your formula does not adjust automatically, so you need to edit it to include the new sheet reference: =MAX(Sheet1:Sheet5!B1)
The following function accepts a single-cell argument and returns the maximum value in that cell across all worksheets in the workbook. For example, the following formula returns the maximum value in cell B1 for all sheets in the workbook: =MAXALLSHEETS(B1)
If you add a new sheet, you don’t need to edit the formula. Function MAXALLSHEETS(cell as Range) As Variant Dim MaxVal As Double Dim Addr As String Dim Wksht As Object Application.Volatile Addr = cell.Range(“A1”).Address MaxVal = –9.9E+307 For Each Wksht In cell.Parent.Parent.Worksheets If Not Wksht.Name = cell.Parent.Name Or _ Not Addr = Application.Caller.Address Then If IsNumeric(Wksht.Range(Addr)) Then
34_475362-ch25.indd 699
4/14/10 10:31 PM
700
Part VI: Developing Custom Worksheet Functions
If Wksht.Range(Addr) > MaxVal Then _ MaxVal = Wksht.Range(Addr).Value End If End If Next Wksht If MaxVal = –9.9E+307 Then MaxVal = CVErr(xlErrValue) MAXALLSHEETS = MaxVal End Function
The For Each statement uses the following expression to access the workbook: cell.Parent.Parent.Worksheets
The parent of the cell is a worksheet, and the parent of the worksheet is the workbook. Therefore, the For Each-Next loop cycles among all worksheets in the workbook. The first If statement inside the loop checks whether the cell being checked is the cell that contains the function. If so, that cell is ignored to avoid a circular reference error. You can easily modify the MAXALLSHEETS function to perform other cross-worksheet calculations: Minimum, Average, Sum, and so on.
The SHEETOFFSET function A recurring complaint about Excel (including Excel 2010) is its poor support for relative sheet references. For example, suppose that you have a multisheet workbook, and you enter a formula like the following on Sheet2: =Sheet1!A1+1
This formula works fine. However, if you copy the formula to the next sheet (Sheet3), the formula continues to refer to Sheet1. Or if you insert a sheet between Sheet1 and Sheet2, the formula continues to refer to Sheet1, when most likely, you want it to refer to the newly inserted sheet. In fact, you can’t create formulas that refer to worksheets in a relative manner. However, you can use the SHEETOFFSET function to overcome this limitation. Following is a VBA Function procedure named SHEETOFFSET: Function SHEETOFFSET(Offset As Long, Optional cell As Variant) ‘ Returns cell contents at Ref, in sheet offset Dim WksIndex As Long, WksNum As Long Dim wks As Worksheet Application.Volatile If IsMissing(cell) Then Set cell = Application.Caller
34_475362-ch25.indd 700
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
701
WksNum = 1 For Each wks In Application.Caller.Parent.Parent.Worksheets If Application.Caller.Parent.Name = wks.Name Then SHEETOFFSET = Worksheets(WksNum + Offset)_ .Range(cell(1).Address).Value Exit Function Else WksNum = WksNum + 1 End If Next wks End Function
The SHEETOFFSET function accepts two arguments: h offset: The sheet offset, which can be positive, negative, or 0. h cell: (Optional) A single-cell reference. If this argument is omitted, the function uses the same cell reference as the cell that contains the formula. For more information about optional arguments, see the section, “Using optional arguments,” later in this chapter. The following formula returns the value in cell A1 of the sheet before the sheet that contains the formula: =SHEETOFFSET(–1,A1)
The following formula returns the value in cell A1 of the sheet after the sheet that contains the formula: =SHEETOFFSET(1,A1)
Advanced Function Techniques In this section, I explore some even more advanced functions. The examples in this section demonstrate some special techniques that you can use with your custom functions.
Returning an error value In some cases, you may want your custom function to return a particular error value. Consider the simple REVERSETEXT function, which I presented earlier in this chapter:
34_475362-ch25.indd 701
4/14/10 10:31 PM
702
Part VI: Developing Custom Worksheet Functions
Function REVERSETEXT(text As String) As String ‘ Returns its argument, reversed REVERSETEXT = StrReverse(text) End Function
This function reverses the contents of its single-cell argument (which can be text or a value). If the argument is a multicell range, the function returns #VALUE! Assume that you want this function to work only with strings. If the argument does not contain a string, you want the function to return an error value (#N/A). You may be tempted to simply assign a string that looks like an Excel formula error value. For example: REVERSETEXT = “#N/A”
Although the string looks like an error value, it is not treated as such by other formulas that may reference it. To return a real error value from a function, use the VBA CVErr function, which converts an error number to a real error. Fortunately, VBA has built-in constants for the errors that you want to return from a custom function. These constants are listed here: h xlErrDiv0 h xlErrNA h xlErrName h xlErrNull h xlErrNum h xlErrRef h xlErrValue The following is the revised REVERSETEXT function: Function REVERSETEXT(text As Variant) As Variant ‘ Returns its argument, reversed If WorksheetFunction.ISNONTEXT(text) Then REVERSETEXT = CVErr(xlErrNA) Else REVERSETEXT = StrReverse(text) End If End Function
34_475362-ch25.indd 702
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
703
First, change the argument from a String data type to a Variant. If the argument’s data type is String, Excel tries to convert whatever it gets (for example, number, Boolean value) to a String and usually succeeds. Next, the Excel ISNONTEXT function is used to determine whether the argument is not a text string. If the argument is not a text string, the function returns the #N/A error. Otherwise, it returns the characters in reverse order. The data type for the return value of the original REVERSETEXT function was String because the function always returned a text string. In this revised version, the function is declared as a Variant because it can now return something other than a string.
Returning an array from a function Most functions that you develop with VBA return a single value. It’s possible, however, to write a function that returns multiple values in an array. Part IV deals with arrays and array formulas. Specifically, these chapters provide examples of a single formula that returns multiple values in separate cells. As you’ll see, you can also create custom functions that return arrays.
VBA includes a useful function called Array. The Array function returns a variant that contains an array. It’s important to understand that the array returned is not the same as a normal array composed of elements of the variant type. In other words, a variant array is not the same as an array of variants. If you’re familiar with using array formulas in Excel, you have a head start understanding the VBA Array function. You enter an array formula into a cell by pressing Ctrl+Shift+Enter. Excel inserts brackets around the formula to indicate that it’s an array formula. See Chapter 15 for more details on array formulas. The lower bound of an array created by using the Array function is, by default, 0. However, the lower bound can be changed if you use an Option Base statement.
The following MONTHNAMES function demonstrates how to return an array from a Function procedure: Function MONTHNAMES() As Variant MONTHNAMES = Array( _ “Jan”, “Feb”, “Mar”, “Apr”, _ “May”, “Jun”, “Jul”, “Aug”, _ “Sep”, “Oct”, “Nov”, “Dec”) End Function
34_475362-ch25.indd 703
4/14/10 10:31 PM
704
Part VI: Developing Custom Worksheet Functions
Figure 25-7 shows a worksheet that uses the MONTHNAMES function. You enter the function by selecting A4:L4 and then entering the following formula: {=MONTHNAMES()}
Figure 25-7: The MONTHNAMES function entered as an array formula.
As with any array formula, you must press Ctrl+Shift+Enter to enter the formula. Don’t enter the brackets — Excel inserts the brackets for you.
The MONTHNAMES function, as written, returns a horizontal array in a single row. To display the array in a vertical range in a single column (as in A7:A18 in Figure 25-5), select the range and enter the following formula: {=TRANSPOSE(MONTHNAMES())}
Alternatively, you can modify the function to do the transposition. The following function uses the Excel TRANSPOSE function to return a vertical array: Function VMONTHNAMES() As Variant VMONTHNAMES = Application.Transpose(Array( _ “Jan”, “Feb”, “Mar”, “Apr”, _ “May”, “Jun”, “Jul”, “Aug”, _ “Sep”, “Oct”, “Nov”, “Dec”)) End Function
The workbook monthnames.xlsm that demonstrates MONTHNAMES and VMONTHNAMES is available on the companion CD-ROM.
34_475362-ch25.indd 704
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
705
Returning an array of nonduplicated random integers The RANDOMINTEGERS function returns an array of nonduplicated integers. This function is intended for use in a multicell array formula. Figure 25-8 shows a worksheet that uses the following formula in the range A3:D12: {=RANDOMINTEGERS()}
Figure 25-8: An array formula generates nonduplicated consecutive integers, arranged randomly.
This formula was entered into the entire range by using Ctrl+Shift+Enter. The formula returns an array of nonduplicated integers, arranged randomly. Because 40 cells contain the formula, the integers range from 1 to 40. The following is the code for RANDOMINTEGERS: Function RANDOMINTEGERS() Dim FuncRange As Range
‘
‘
34_475362-ch25.indd 705
Dim V() As Integer, ValArray() As Integer Dim CellCount As Double Dim i As Integer, j As Integer Dim r As Integer, c As Integer Dim Temp1 As Variant, Temp2 As Variant Dim RCount As Integer, CCount As Integer Randomize Create Range object Set FuncRange = Application.Caller Return an error if FuncRange is too large CellCount = FuncRange.Count If CellCount > 1000 Then RANDOMINTEGERS = CVErr(xlErrNA) Exit Function
4/14/10 10:31 PM
706
Part VI: Developing Custom Worksheet Functions
End If ‘
Assign variables RCount = FuncRange.Rows.Count CCount = FuncRange.Columns.Count ReDim V(1 To RCount, 1 To CCount) ReDim ValArray(1 To 2, 1 To CellCount)
‘ ‘
Fill array with random numbers and consecutive integers For i = 1 To CellCount ValArray(1, i) = Rnd ValArray(2, i) = i Next i
‘
Sort ValArray by the random number dimension For i = 1 To CellCount For j = i + 1 To CellCount If ValArray(1, i) > ValArray(1, j) Then Temp1 = ValArray(1, j) Temp2 = ValArray(2, j) ValArray(1, j) = ValArray(1, i) ValArray(2, j) = ValArray(2, i) ValArray(1, i) = Temp1 ValArray(2, i) = Temp2 End If Next j Next i
‘
Put the randomized values into the V array i = 0 For r = 1 To RCount For c = 1 To CCount i = i + 1 V(r, c) = ValArray(2, i) Next c Next r RANDOMINTEGERS = V End Function
The workbook random integers function.xlsm containing the RANDOMINTEGERS function is available on the companion CD-ROM.
Randomizing a range The following RANGERANDOMIZE function accepts a range argument and returns an array that consists of the input range in random order:
34_475362-ch25.indd 706
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
707
Function RANGERANDOMIZE(rng) Dim V() As Variant, ValArray() As Variant Dim CellCount As Double Dim i As Integer, j As Integer Dim r As Integer, c As Integer Dim Temp1 As Variant, Temp2 As Variant Dim RCount As Integer, CCount As Integer Randomize ‘
Return an error if rng is too large CellCount = rng.Count If CellCount > 1000 Then RANGERANDOMIZE = CVErr(xlErrNA) Exit Function End If
‘
Assign variables RCount = rng.Rows.Count CCount = rng.Columns.Count ReDim V(1 To RCount, 1 To CCount) ReDim ValArray(1 To 2, 1 To CellCount)
‘ ‘
Fill ValArray with random numbers and values from rng For i = 1 To CellCount ValArray(1, i) = Rnd ValArray(2, i) = rng(i) Next i
‘
Sort ValArray by the random number dimension For i = 1 To CellCount For j = i + 1 To CellCount If ValArray(1, i) > ValArray(1, j) Then Temp1 = ValArray(1, j) Temp2 = ValArray(2, j) ValArray(1, j) = ValArray(1, i) ValArray(2, j) = ValArray(2, i) ValArray(1, i) = Temp1 ValArray(2, i) = Temp2 End If Next j Next i
‘
Put the randomized values into the V array i = 0 For r = 1 To RCount For c = 1 To CCount i = i + 1 V(r, c) = ValArray(2, i) Next c
34_475362-ch25.indd 707
4/14/10 10:31 PM
708
Part VI: Developing Custom Worksheet Functions
Next r RANGERANDOMIZE = V End Function
The code closely resembles the code for the RANDOMINTEGERS function. Figure 25-9 shows the function in use. The following array formula, which is in E15:F27, returns the contents of B15:C27 in a random order: {=RANGERANDOMIZE(B15:C27)}
Figure 25-9: The RANGERANDOMIZE function returns the contents of a range, but in a randomized order.
The workbook range randomize function.xlsm, which contains the RANGERANDOMIZE function, is available on the companion CD-ROM.
Using optional arguments Many of the built-in Excel worksheet functions use optional arguments. For example, the LEFT function returns characters from the left side of a string. Its official syntax is as follows: LEFT(text,num_chars)
The first argument is required, but the second is optional. If you omit the optional argument, Excel assumes a value of 1.
34_475362-ch25.indd 708
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
709
Custom functions that you develop in VBA can also have optional arguments. You specify an optional argument by preceding the argument’s name with the keyword Optional. The following is a simple function that returns the user’s name: Function USER() USER = Application.UserName End Function
Suppose that in some cases, you want the user’s name to be returned in uppercase letters. The following function uses an optional argument: Function USER(Optional UpperCase As Variant) As String If IsMissing(UpperCase) Then UpperCase = False If UpperCase = True Then USER = Ucase(Application.UserName) Else USER = Application.UserName End If End Function
If you need to determine whether an optional argument was passed to a function, you must declare the optional argument as a variant data type. Then you can use the IsMissing function within the procedure, as demonstrated in this example.
If the argument is FALSE or omitted, the user’s name is returned without any changes. If the argument is TRUE, the user’s name converts to uppercase (using the VBA Ucase function) before it is returned. Notice that the first statement in the procedure uses the VBA IsMissing function to determine whether the argument was supplied. If the argument is missing, the statement sets the UpperCase variable to FALSE (the default value). Optional arguments also allow you to specify a default value in the declaration, rather than testing it with the IsMissing function. The preceding function can be rewritten in this alternate syntax as Function USER(Optional UpperCase As Boolean = False) As String If UpperCase = True Then USER = UCase(Application.UserName) Else USER = Application.UserName End If End Function
34_475362-ch25.indd 709
4/14/10 10:31 PM
710
Part VI: Developing Custom Worksheet Functions
If no argument is supplied, UpperCase is automatically assigned a value of FALSE. This has the advantage of allowing you type the argument appropriately instead of with the generic Variant data type. If you use this method, however, there is no way to tell whether the user omitted the argument or supplied the default argument. All the following formulas are valid in either syntax (and the first two have the same effect): =USER() =USER(False) =USER(True)
Using an indefinite number of arguments Some of the Excel worksheet functions take an indefinite number of arguments. A familiar example is the SUM function, which has the following syntax: SUM(number1,number2...)
The first argument is required, but you can have as many as 254 additional arguments. Here’s an example of a formula that uses the SUM function with four range arguments: =SUM(A1:A5,C1:C5,E1:E5,G1:G5)
You can mix and match the argument types. For example, the following example uses three arguments — a range, followed by a value, and finally an expression: =SUM(A1:A5,12,24*3)
You can create Function procedures that have an indefinite number of arguments. The trick is to use an array as the last (or only) argument, preceded by the keyword ParamArray. ParamArray can apply only to the last argument in the procedure. It is always a variant data type, and it is always an optional argument (although you don’t use the Optional
keyword).
A simple example of indefinite arguments The following is a Function procedure that can have any number of single-value arguments. It simply returns the sum of the arguments.
34_475362-ch25.indd 710
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
711
Function SIMPLESUM(ParamArray arglist() As Variant) As Double Dim arg as Variant For Each arg In arglist SIMPLESUM = SIMPLESUM + arg Next arg End Function
The following formula returns the sum of the single-cell arguments: =SIMPLESUM(A1,A5,12)
The most serious limitation of the SIMPLESUM function is that it does not handle multicell ranges. This improved version does: Function SIMPLESUM(ParamArray arglist() As Variant) As Double Dim arg as Variant Dim cell as Range For Each arg In arglist If TypeName(arg) = “Range” Then For Each cell In arg SIMPLESUM = SIMPLESUM + cell.Value Next cell Else SIMPLESUM = SIMPLESUM + arg End If Next arg End Function
This function checks each entry in the Arglist array. If the entry is a range, then the code uses a For Each-Next loop to sum the cells in the range. Even this improved version is certainly no substitute for the Excel SUM function. Try it by using various types of arguments, and you’ll see that it fails unless each argument is a value or a range reference. Also, if an argument consists of an entire column, you’ll find that the function is very slow because it evaluates every cell — even the empty ones.
Emulating the Excel SUM function This section presents a Function procedure called MYSUM. Unlike the SIMPLESUM function listed in the previous section, MYSUM emulates the Excel SUM function perfectly. Before you look at the code for the MYSUM function, take a minute to think about the Excel SUM function. This very versatile function can have any number of arguments (even missing arguments),
34_475362-ch25.indd 711
4/14/10 10:31 PM
712
Part VI: Developing Custom Worksheet Functions
and the arguments can be numerical values, cells, ranges, text representations of numbers, logical values, and even embedded functions. For example, consider the following formula: =SUM(A1,5,”6”,,TRUE,SQRT(4),B1:B5,{1,3,5})
This formula — which is a valid formula — contains all the following types of arguments, listed here in the order of their presentation: h A single cell reference (A1) h A literal value (5) h A string that looks like a value (“6”) h A missing argument h A logical value (TRUE) h An expression that uses another function (SQRT) h A range reference (B1:B5) h An array ({1,3,5}) The following is the listing for the MYSUM function that handles all these argument types: Function MySum(ParamArray args() As Variant) As Variant ‘ Emulates Excel’s SUM function ‘ Variable declarations Dim i As Variant Dim TempRange As Range, cell As Range Dim ECode As String Dim m, n MySum = 0 ‘ Process each argument For i = 0 To UBound(args) ‘ Skip missing arguments If Not IsMissing(args(i)) Then ‘ What type of argument is it? Select Case TypeName(args(i)) Case “Range” ‘ Create temp range to handle full row or column ranges Set TempRange = Intersect(args(i).Parent.UsedRange, args(i)) For Each cell In TempRange If IsError(cell) Then MySum = cell ‘ return the error Exit Function End If
34_475362-ch25.indd 712
4/14/10 10:31 PM
Chapter 25: VBA Custom Function Examples
713
If cell = True Or cell = False Then MySum = MySum + 0 Else If IsNumeric(cell) Or IsDate(cell) Then _ MySum = MySum + cell End If Next cell Case “Variant()” n = args(i) For m = LBound(n) To UBound(n) MySum = MySum(MySum, n(m)) ‘recursive call Next m Case “Null” ‘ignore it Case “Error” ‘return the error MySum = args(i) Exit Function Case “Boolean” ‘ Check for literal TRUE and compensate If args(i) = “True” Then MySum = MySum + 1 Case “Date” MySum = MySum + args(i) Case Else MySum = MySum + args(i) End Select End If Next i End Function
The workbook sum function emulation.xlsm containing the MYSUM function is available on the companion CD-ROM.
As you study the code for MYSUM, keep the following points in mind: h Missing arguments (determined by the IsMissing function) are simply ignored. h The procedure uses the VBA TypeName function to determine the type of argument (Range, Error, or something else). Each argument type is handled differently. h For a range argument, the function loops through each cell in the range and adds its value to a running total. h The data type for the function is Variant because the function needs to return an error if any of its arguments is an error value. h If an argument contains an error (for example, #DIV0!), the MYSUM function simply returns the error — just like the Excel SUM function.
34_475362-ch25.indd 713
4/14/10 10:31 PM
714
Part VI: Developing Custom Worksheet Functions
h The Excel SUM function considers a text string to have a value of 0 unless it appears as a literal argument (that is, as an actual value, not a variable). Therefore, MYSUM adds the cell’s value only if it can be evaluated as a number (VBA’s IsNumeric function is used for this). h Dealing with Boolean arguments is tricky. For MYSUM to emulate SUM exactly, it needs to test for a literal TRUE in the argument list and compensate for the difference (that is, add 2 to –1 to get 1). h For range arguments, the function uses the Intersect method to create a temporary range that consists of the intersection of the range and the sheet’s used range. This handles cases in which a range argument consists of a complete row or column, which would take forever to evaluate. You may be curious about the relative speeds of SUM and MYSUM. MYSUM, of course, is much slower, but just how much slower depends on the speed of your system and the formulas themselves. On my system, a worksheet with 5,000 SUM formulas recalculated instantly. After I replaced the SUM functions with MYSUM functions, it took about 8 seconds. MYSUM may be improved a bit, but it can never come close to SUM’s speed. By the way, I hope you understand that the point of this example is not to create a new SUM function. Rather, it demonstrates how to create custom worksheet functions that look and work like those built into Excel.
34_475362-ch25.indd 714
4/14/10 10:31 PM
PART
VII
Appendixes Appendix A Excel Function Reference
Appendix B Using Custom Number Formats
Appendix C Additional Excel Resources
Appendix D What’s on the CD-ROM?
35_475362-pp07.indd 715
4/14/10 10:32 PM
35_475362-pp07.indd 716
4/14/10 10:32 PM
APPENDIX
A
Excel Function Reference This appendix contains a complete listing of the Excel worksheet functions. The functions are arranged alphabetically in tables by categories used by the Insert Function dialog box. For more information about a particular function, including its arguments, select the function in the Insert Function dialog box and click Help on This Function. A workbook that contains this information is available on the companion CD-ROM. The filename is worksheet functions.xlsx.
717
36_475362-bapp01.indd 717
4/14/10 10:32 PM
718
Part VII: Appendixes
Table A-1: Compatibility Category Functions Function
What It Does
BETADIST
Returns the cumulative beta probability density function.
BETAINV
Returns the inverse of the cumulative beta probability density function.
BINOMDIST
Returns the individual term binomial distribution probability.
CHIDIST
Returns the one-tailed probability of the chi-squared distribution.
CHIINV
Returns the inverse of the one-tailed probability of the chi-squared distribution.
CHITEST
Returns the test for independence.
CONFIDENCE
Returns the confidence interval for a population mean.
COVAR
Returns covariance, the average of the products of paired deviations.
CRITBINOM
Returns the smallest value for which the cumulative binomial distribution is less than or equal to a criterion value.
EXPONDIST
Returns the exponential distribution.
FDIST
Returns the F probability distribution.
FINV
Returns the inverse of the F probability distribution.
FTEST
Returns the result of an f-Test.
GAMMADIST
Returns the gamma distribution.
GAMMAINV
Returns the inverse of the gamma cumulative distribution.
HYPGEOMDIST
Returns the hypergeometric distribution.
LOGINV
Returns the inverse of the lognormal distribution.
LOGNORMDIST
Returns the cumulative lognormal distribution.
MODE
Returns the most common value in a data set.
NEGBINOMDIST
Returns the negative binomial distribution.
NORMDIST
Returns the normal cumulative distribution.
NORMINV
Returns the inverse of the normal cumulative distribution.
NORMSDIST
Returns the standard normal cumulative distribution.
NORMSINV
Returns the inverse of the standard normal cumulative distribution.
PERCENTILE
Returns the kth percentile of values in a range.
PERCENTRANK
Returns the percentage rank of a value in a data set.
POISSON
Returns the Poisson distribution.
QUARTILE
Returns the quartile of a data set.
RANK
Returns the rank of a number in a list of numbers.
STDEV
Estimates standard deviation based on a sample, ignoring text and logical values.
STDEVP
Calculates standard deviation based on the entire population, ignoring text and logical values.
TDIST
Returns the Student’s t-distribution.
36_475362-bapp01.indd 718
4/14/10 10:33 PM
719
Appendix A: Excel Function Reference
Function
What It Does
TINV
Returns the inverse of the Student’s t-distribution.
TTEST
Returns the probability associated with a Student’s t-Test.
VAR
Estimates variance based on a sample, ignoring logical values and text.
VARP
Calculates variance based on the entire population, ignoring logical values and text.
WEIBULL
Returns the Weibull distribution.
ZTEST
Returns the two-tailed P-value of a z-Test.
The functions in the Compatibility category all have new versions in Excel 2010. These new functions are listed in the Statistical category.
Table A-2: Cube Category Functions Function
What It Does
CUBEKPIMEMBER*
Returns a key performance indicator name, property, and measure, and displays the name and property in the cell.
CUBEMEMBER*
Returns a member or tuple in a cube hierarchy.
CUBEMEMBERPROPERTY*
Returns the value of a member property in the cube.
CUBERANKEDMEMBER*
Returns the nth, or ranked, member in a set.
CUBESET*
Defines a calculated set of members or tuples by sending a set expression to the cube on the server.
CUBESETCOUNT*
Returns the number of items in a set.
CUBEVALUE*
Returns an aggregated value from a cube.
* Indicates a function introduced in Excel 2007.
Table A-3: Database Category Functions Function
What It Does
DAVERAGE
Averages the values in a column of a list or database that match conditions you specify.
DCOUNT
Counts the cells that contain numbers in a column of a list or database that match conditions you specify.
DCOUNTA
Counts the nonblank cells in a column of a list or database that match conditions you specify.
DGET
Extracts a single value from a column of a list or database that matches conditions you specify.
DMAX
Returns the largest number in a column of a list or database that matches conditions you specify.
DMIN
Returns the smallest number in a column of a list or database that matches conditions you specify. continued
36_475362-bapp01.indd 719
4/14/10 10:33 PM
720
Part VII: Appendixes
Table A-3: Database Category Functions (continued) Function
What It Does
DPRODUCT
Multiplies the values in a column of a list or database that match conditions you specify.
DSTDEV
Estimates the standard deviation of a population based on a sample by using the numbers in a column of a list or database that match conditions you specify.
DSTDEVP
Calculates the standard deviation of a population based on the entire population, using the numbers in a column of a list or database that match conditions you specify.
DSUM
Adds the numbers in a column of a list or database that match conditions you specify.
DVAR
Estimates the variance of a population based on a sample by using the numbers in a column of a list or database that match conditions you specify.
DVARP
Calculates the variance of a population based on the entire population by using the numbers in a column of a list or database that match conditions you specify.
Table A-4: Date & Time Category Functions Function
What It Does
DATE
Returns the serial number of a particular date.
DATEVALUE
Converts a date in the form of text to a serial number.
DAY
Converts a serial number to a day of the month.
DAYS360
Calculates the number of days between two dates, based on a 360-day year.
EDATE
Returns the serial number of the date that is the indicated number of months before or after the start date.
EOMONTH
Returns the serial number of the last day of the month before or after a specified number of months.
HOUR
Converts a serial number to an hour.
MINUTE
Converts a serial number to a minute.
MONTH
Converts a serial number to a month.
NETWORKDAYS
Returns the number of whole workdays between two dates.
NETWORKDAYS.INTL*
Returns the number of whole workdays between two dates (international version).
NOW
Returns the serial number of the current date and time.
SECOND
Converts a serial number to a second.
TIME
Returns the serial number of a particular time.
TIMEVALUE
Converts a time in the form of text to a serial number.
TODAY
Returns the serial number of today’s date.
WEEKDAY
Converts a serial number to a day of the week.
WEEKNUM
Returns the week number in the year.
WORKDAY
Returns the serial number of the date before or after a specified number of work days.
36_475362-bapp01.indd 720
4/14/10 10:33 PM
Appendix A: Excel Function Reference
721
Function
What It Does
WORKDAY.INTL*
Returns the serial number of the date before or after a specified number of work days (international version).
YEAR
Converts a serial number to a year.
YEARFRAC
Returns the year fraction representing the number of whole days between start_date and end_date.
* Indicates a function introduced in Excel 2010.
Table A-5: Engineering Category Functions Function
What It Does
BESSELI
Returns the modified Bessel function In(x).
BESSELJ
Returns the Bessel function Jn(x).
BESSELK
Returns the modified Bessel function Kn(x).
BESSELY
Returns the Bessel function Yn(x).
BIN2DEC
Converts a binary number to decimal.
BIN2HEX
Converts a binary number to hexadecimal.
BIN2OCT
Converts a binary number to octal.
COMPLEX
Converts real and imaginary coefficients into a complex number.
CONVERT
Converts a number from one measurement system to another.
DEC2BIN
Converts a decimal number to binary.
DEC2HEX
Converts a decimal number to hexadecimal.
DEC2OCT
Converts a decimal number to octal.
DELTA
Tests whether two values are equal.
ERF
Returns the error function.
ERF.PRECISE*
Returns the error function.
ERFC
Returns the complementary error function.
ERFC.PRECISE*
Returns the complementary error function.
GESTEP
Tests whether a number is greater than a threshold value.
HEX2BIN
Converts a hexadecimal number to binary.
HEX2DEC
Converts a hexadecimal number to decimal.
HEX2OCT
Converts a hexadecimal number to octal.
IMABS
Returns the absolute value (modulus) of a complex number.
IMAGINARY
Returns the imaginary coefficient of a complex number.
IMARGUMENT
Returns the argument theta, an angle expressed in radians.
IMCONJUGATE
Returns the complex conjugate of a complex number. continued
36_475362-bapp01.indd 721
4/14/10 10:33 PM
722
Part VII: Appendixes
Table A-5: Engineering Category Functions (continued) Function
What It Does
IMCOS
Returns the cosine of a complex number.
IMDIV
Returns the quotient of two complex numbers.
IMEXP
Returns the exponential of a complex number.
IMLN
Returns the natural logarithm of a complex number.
IMLOG10
Returns the base-10 logarithm of a complex number.
IMLOG2
Returns the base-2 logarithm of a complex number.
IMPOWER
Returns a complex number raised to an integer power.
IMPRODUCT
Returns the product of complex numbers.
IMREAL
Returns the real coefficient of a complex number.
IMSIN
Returns the sine of a complex number.
IMSQRT
Returns the square root of a complex number.
IMSUB
Returns the difference of two complex numbers.
IMSUM
Returns the sum of complex numbers.
OCT2BIN
Converts an octal number to binary.
OCT2DEC
Converts an octal number to decimal.
OCT2HEX
Converts an octal number to hexadecimal.
* Indicates a function introduced in Excel 2010.
Table A-6: Financial Category Functions Function
What It Does
ACCRINT
Returns the accrued interest for a security that pays periodic interest.
ACCRINTM
Returns the accrued interest for a security that pays interest at maturity.
AMORDEGRC
Returns the depreciation for each accounting period.
AMORLINC
Returns the depreciation for each accounting period (the depreciation coefficient depends on the life of the assets).
COUPDAYBS
Returns the number of days from the beginning of the coupon period to the settlement date.
COUPDAYS
Returns the number of days in the coupon period that contains the settlement date.
COUPDAYSNC
Returns the number of days from the settlement date to the next coupon date.
COUPNCD
Returns the next coupon date after the settlement date.
COUPNUM
Returns the number of coupons payable between the settlement date and the maturity date.
COUPPCD
Returns the previous coupon date before the settlement date.
CUMIPMT
Returns the cumulative interest paid between two periods.
36_475362-bapp01.indd 722
4/14/10 10:33 PM
723
Appendix A: Excel Function Reference
Function
What It Does
CUMPRINC
Returns the cumulative principal paid on a loan between two periods.
DB
Returns the depreciation of an asset for a specified period, using the fixed-decliningbalance method.
DDB
Returns the depreciation of an asset for a specified period, using the double-decliningbalance method or some other method that you specify.
DISC
Returns the discount rate for a security.
DOLLARDE
Converts a dollar price, expressed as a fraction, into a dollar price expressed as a decimal number.
DOLLARFR
Converts a dollar price, expressed as a decimal number, into a dollar price expressed as a fraction.
DURATION
Returns the annual duration of a security with periodic interest payments.
EFFECT
Returns the effective annual interest rate.
FV
Returns the future value of an investment.
FVSCHEDULE
Returns the future value of an initial principal after applying a series of compound interest rates.
INTRATE
Returns the interest rate for a fully invested security.
IPMT
Returns the interest payment for an investment for a given period.
IRR
Returns the internal rate of return for a series of cash flows.
ISPMT
Returns the interest associated with a specific loan payment.
MDURATION
Returns the Macauley modified duration for a security with an assumed par value of $100.
MIRR
Returns the internal rate of return where positive and negative cash flows are financed at different rates.
NOMINAL
Returns the annual nominal interest rate.
NPER
Returns the number of periods for an investment.
NPV
Returns the net present value of an investment based on a series of periodic cash flows and a discount rate.
ODDFPRICE
Returns the price per $100 face value of a security with an odd first period.
ODDFYIELD
Returns the yield of a security with an odd first period.
ODDLPRICE
Returns the price per $100 face value of a security with an odd last period.
ODDLYIELD
Returns the yield of a security with an odd last period.
PMT
Returns the periodic payment for an annuity.
PPMT
Returns the payment on the principal for an investment for a given period.
PRICE
Returns the price per $100 face value of a security that pays periodic interest.
PRICEDISC
Returns the price per $100 face value of a discounted security.
PRICEMAT
Returns the price per $100 face value of a security that pays interest at maturity.
PV
Returns the present value of an investment. continued
36_475362-bapp01.indd 723
4/14/10 10:33 PM
724
Part VII: Appendixes
Table A-6: Financial Category Functions (continued) Function
What It Does
RATE
Returns the interest rate per period of an annuity.
RECEIVED
Returns the amount received at maturity for a fully invested security.
SLN
Returns the straight-line depreciation of an asset for one period.
SYD
Returns the sum-of-years’ digits depreciation of an asset for a specified period.
TBILLEQ
Returns the bond-equivalent yield for a Treasury bill.
TBILLPRICE
Returns the price per $100 face value for a Treasury bill.
TBILLYIELD
Returns the yield for a Treasury bill.
VDB
Returns the depreciation of an asset for a specified or partial period using a doubledeclining-balance method.
XIRR
Returns the internal rate of return for a schedule of cash flows that is not necessarily periodic.
XNPV
Returns the net present value for a schedule of cash flows that is not necessarily periodic.
YIELD
Returns the yield on a security that pays periodic interest.
YIELDDISC
Returns the annual yield for a discounted security, for example, a Treasury bill.
YIELDMAT
Returns the annual yield of a security that pays interest at maturity.
Table A-7: Information Category Functions Function
What It Does
CELL
Returns information about the formatting, location, or contents of a cell.
ERROR.TYPE
Returns a number corresponding to an error type.
INFO
Returns information about the current operating environment.
ISBLANK
Returns TRUE if the value is blank.
ISERR
Returns TRUE if the value is any error value except #N/A.
ISERROR
Returns TRUE if the value is any error value.
ISEVEN
Returns TRUE if the number is even.
ISLOGICAL
Returns TRUE if the value is a logical value.
ISNA
Returns TRUE if the value is the #N/A error value.
ISNONTEXT
Returns TRUE if the value is not text.
ISNUMBER
Returns TRUE if the value is a number.
ISODD
Returns TRUE if the number is odd.
ISREF
Returns TRUE if the value is a reference.
ISTEXT
Returns TRUE if the value is text.
N
Returns a value converted to a number.
NA
Returns the error value #N/A.
TYPE
Returns a number indicating the data type of a value.
36_475362-bapp01.indd 724
4/14/10 10:33 PM
Appendix A: Excel Function Reference
725
Table A-8: Logical Category Functions Function
What It Does
AND
Returns TRUE if all its arguments are TRUE.
FALSE
Returns the logical value FALSE.
IF
Specifies a logical test to perform.
IFERROR*
Returns a different result if the first argument evaluates to an error.
NOT
Reverses the logic of its argument.
OR
Returns TRUE if any argument is TRUE.
TRUE
Returns the logical value TRUE.
* Indicates a function introduced in Excel 2007.
Table A-9: Lookup & Reference Category Functions Function
What It Does
ADDRESS
Returns a reference as text to a single cell in a worksheet.
AREAS
Returns the number of areas in a reference.
CHOOSE
Chooses a value from a list of values.
COLUMN
Returns the column number of a reference.
COLUMNS
Returns the number of columns in a reference
GETPIVOTDATA
Returns data stored in a PivotTable.
HLOOKUP
Searches for a value in the top row of a table and then returns a value in the same column from a row you specify in the table.
HYPERLINK
Creates a shortcut that opens a document on your hard drive, a server, or the Internet.
INDEX
Uses an index to choose a value from a reference or array.
INDIRECT
Returns a reference indicated by a text value.
LOOKUP
Returns a value from either a one-row or one-column range or from an array.
MATCH
Returns the relative position of an item in an array.
OFFSET
Returns a reference offset from a given reference.
ROW
Returns the row number of a reference.
ROWS
Returns the number of rows in a reference.
RTD
Returns real-time data from a program that supports COM automation.
TRANSPOSE
Returns the transpose of an array.
VLOOKUP
Searches for a value in the leftmost column of a table and then returns a value in the same row from a column you specify in the table.
36_475362-bapp01.indd 725
4/14/10 10:33 PM
726
Part VII: Appendixes
Table A-10: Math & Trig Category Functions Function
What It Does
ABS
Returns the absolute value of a number.
ACOS
Returns the arccosine of a number.
ACOSH
Returns the inverse hyperbolic cosine of a number.
AGGREGATE**
Returns an aggregate in a list or database.
ASIN
Returns the arcsine of a number.
ASINH
Returns the inverse hyperbolic sine of a number.
ATAN
Returns the arctangent of a number.
ATAN2
Returns the arctangent from x and y coordinates.
ATANH
Returns the inverse hyperbolic tangent of a number.
CEILING
Rounds a number to the nearest integer or to the nearest multiple of significance.
CEILING.PRECISE**
Rounds a number up to the nearest integer or to the nearest multiple of significance, regardless of the sign of the number.
COMBIN
Returns the number of combinations for a given number of objects.
COS
Returns the cosine of a number.
COSH
Returns the hyperbolic cosine of a number.
DEGREES
Converts radians to degrees.
EVEN
Rounds a number up to the nearest even integer.
EXP
Returns e raised to the power of a given number.
FACT
Returns the factorial of a number.
FACTDOUBLE
Returns the double factorial of a number.
FLOOR
Rounds a number down, toward 0.
FLOOR.PRECISE**
Rounds a number down to the nearest integer or to the nearest multiple of significance, regardless of the sign.
GCD
Returns the greatest common divisor.
INT
Rounds a number down to the nearest integer.
ISO.CEILING**
Returns a number that is rounded up to the nearest integer or to the nearest multiple of significance.
LCM
Returns the least common multiple.
LN
Returns the natural logarithm of a number.
LOG
Returns the logarithm of a number to a specified base.
LOG10
Returns the base 10 logarithm of a number.
MDETERM
Returns the matrix determinant of an array.
MINVERSE
Returns the matrix inverse of an array.
MMULT
Returns the matrix product of two arrays.
MOD
Returns the remainder from division.
36_475362-bapp01.indd 726
4/14/10 10:33 PM
Appendix A: Excel Function Reference
727
Function
What It Does
MROUND
Returns a number rounded to the desired multiple.
MULTINOMIAL
Returns the multinomial of a set of numbers.
ODD
Rounds a number up to the nearest odd integer.
PI
Returns the value of pi.
POWER
Returns the result of a number raised to a power.
PRODUCT
Multiplies its arguments.
QUOTIENT
Returns the integer portion of a division.
RADIANS
Converts degrees to radians.
RAND
Returns a random number between 0 and 1.
RANDBETWEEN
Returns a random number between the numbers that you specify.
ROMAN
Converts an Arabic numeral to Roman, as text.
ROUND
Rounds a number to a specified number of digits.
ROUNDDOWN
Rounds a number down, toward 0.
ROUNDUP
Rounds a number up, away from 0.
SERIESSUM
Returns the sum of a power series based on the formula.
SIGN
Returns the sign of a number.
SIN
Returns the sine of the given angle.
SINH
Returns the hyperbolic sine of a number.
SQRT
Returns a positive square root.
SQRTPI
Returns the square root of pi.
SUBTOTAL
Returns a subtotal in a list or database.
SUM
Adds its arguments.
SUMIF
Adds the cells specified by a given criteria.
SUMIFS*
Adds the cells specified by a multiple criteria.
SUMPRODUCT
Returns the sum of the products of corresponding array components.
SUMSQ
Returns the sum of the squares of the arguments.
SUMX2MY2
Returns the sum of the difference of squares of corresponding values in two arrays.
SUMX2PY2
Returns the sum of the sum of squares of corresponding values in two arrays.
SUMXMY2
Returns the sum of squares of differences of corresponding values in two arrays.
TAN
Returns the tangent of a number.
TANH
Returns the hyperbolic tangent of a number.
TRUNC
Truncates a number (you specify the precision of the truncation).
* Indicates a function introduced in Excel 2007. ** Indicates a function introduced in Excel 2010.
36_475362-bapp01.indd 727
4/14/10 10:33 PM
728
Part VII: Appendixes
Table A-11: Statistical Category Functions Function
What It Does
AVEDEV
Returns the average of the absolute deviations of data points from their mean.
AVERAGE
Returns the average of its arguments.
AVERAGEA
Returns the average of its arguments and includes evaluation of text and logical values.
AVERAGEIF *
Returns the average for the cells specified by a given criterion.
AVERAGEIFS *
Returns the average for the cells specified by multiple criteria.
BETA.DIST **
Returns the beta cumulative distribution function.
BETA.INV **
Returns the inverse of the cumulative distribution function for a specified beta distribution.
BINOM.DIST **
Returns the individual term binomial distribution probability.
BINOM.INV **
Returns the smallest value for which the cumulative binomial distribution is less than or equal to a criterion value.
CHISQ.DIST **
Returns the cumulative beta probability density function.
CHISQ.DIST.RT **
Returns the one-tailed probability of the chi-squared distribution.
CHISQ.INV **
Returns the cumulative beta probability density function.
CHISQ.INV.RT **
Returns the inverse of the one-tailed probability of the chi-squared distribution.
CHISQ.TEST **
Returns the test for independence.
CONFIDENCE.NORM **
Returns the confidence interval for a population mean.
CONFIDENCE.T **
Returns the confidence interval for a population mean, using a Student’s t-distribution.
CORREL
Returns the correlation coefficient between two data sets.
COUNT
Counts how many numbers are in the list of arguments.
COUNTA
Counts how many values are in the list of arguments.
COUNTBLANK
Counts the number of blank cells in the argument range.
COUNTIF
Counts the number of cells that meet the criteria you specify in the argument.
COUNTIFS *
Counts the number of cells that meet multiple criteria.
COVARIANCE.P **
Returns covariance, the average of the products of paired deviations.
COVARIANCE.S **
Returns the sample covariance, the average of the products’ deviations for each data point pair in two data sets.
DEVSQ
Returns the sum of squares of deviations.
EXPON.DIST **
Returns the exponential distribution.
F.DIST **
Returns the F probability distribution.
F.DIST.RT **
Returns the F probability distribution.
F.INV **
Returns the inverse of the F probability distribution.
F.INV.RT **
Returns the inverse of the F probability distribution.
36_475362-bapp01.indd 728
4/14/10 10:33 PM
729
Appendix A: Excel Function Reference
Function
What It Does
F.TEST **
Returns the result of an f-Test.
FISHER
Returns the Fisher transformation.
FISHERINV
Returns the inverse of the Fisher transformation.
FORECAST
Returns a value along a linear trend.
FREQUENCY
Returns a frequency distribution as a vertical array.
GAMMA.DIST **
Returns the gamma distribution.
GAMMA.INV **
Returns the inverse of the gamma cumulative distribution.
GAMMALN
Returns the natural logarithm of the gamma function, G(x).
GAMMALN.PRECISE**
Returns the natural logarithm of the gamma function, G(x).
GEOMEAN
Returns the geometric mean.
GROWTH
Returns values along an exponential trend.
HARMEAN
Returns the harmonic mean.
HYPGEOM.DIST **
Returns the hypergeometric distribution.
INTERCEPT
Returns the intercept of the linear regression line.
KURT
Returns the kurtosis of a data set.
LARGE
Returns the kth largest value in a data set.
LINEST
Returns the parameters of a linear trend.
LOGEST
Returns the parameters of an exponential trend.
LOGNORM.DIST **
Returns the cumulative lognormal distribution.
LOGNORM.INV **
Returns the inverse of the lognormal cumulative distribution.
MAX
Returns the maximum value in a list of arguments, ignoring logical values and text.
MAXA
Returns the maximum value in a list of arguments, including logical values and text.
MEDIAN
Returns the median of the given numbers.
MIN
Returns the minimum value in a list of arguments, ignoring logical values and text.
MINA
Returns the minimum value in a list of arguments, including logical values and text.
MODE.MULT **
Returns a vertical array of the most frequently occurring, or repetitive values in an array or range of data.
MODE.SNGL **
Returns the most common value in a data set.
NEGBINOM.DIST **
Returns the negative binomial distribution.
NORM.DIST **
Returns the normal cumulative distribution.
NORM.INV **
Returns the inverse of the normal cumulative distribution.
NORM.S.DIST **
Returns the standard normal cumulative distribution. continued
36_475362-bapp01.indd 729
4/14/10 10:33 PM
730
Part VII: Appendixes
Table A-11: Statistical Category Functionss (continued) Function
What It Does
NORM.S.INV **
Returns the inverse of the standard normal cumulative distribution.
PEARSON
Returns the Pearson product moment correlation coefficient.
PERCENTILE.EXC **
Returns the kth percentile of values in a range, where k is in the range 0..1, exclusive.
PERCENTILE.INC **
Returns the kth percentile of values in a range.
PERCENTRANK.EXC **
Returns the rank of a value in a data set as a percentage (0...1, exclusive) of the data set.
PERCENTRANK.INC **
Returns the percentage rank of a value in a data set.
PERMUT
Returns the number of permutations for a given number of objects.
POISSON.DIST **
Returns the Poisson distribution.
PROB
Returns the probability that values in a range are between two limits.
QUARTILE.EXC **
Returns the quartile of the data set, based on percentile values from 0...1, exclusive.
QUARTILE.INC **
Returns the quartile of a data set.
RANK.AVG **
Returns the rank of a number in a list of numbers.
RANK.EQ **
Returns the rank of a number in a list of numbers.
RSQ
Returns the square of the Pearson product moment correlation coefficient.
SKEW
Returns the skewness of a distribution.
SLOPE
Returns the slope of the linear regression line.
SMALL
Returns the kth smallest value in a data set.
STANDARDIZE
Returns a normalized value.
STDEV.P **
Calculates standard deviation based on the entire population.
STDEV.S **
Estimates standard deviation based on a sample.
STDEVA
Estimates standard deviation based on a sample, including text and logical values.
STDEVPA
Calculates standard deviation based on the entire population, including text and logical values.
STEYX
Returns the standard error of the predicted y-value for each x in the regression.
T.DIST
Returns the Percentage Points (probability) for the Student’s t-distribution.
T.DIST.2T **
Returns the Percentage Points (probability) for the Student’s t-distribution.
T.DIST.RT **
Returns the Student’s t-distribution.
T.INV **
Returns the t-value of the Student’s t-distribution as a function of the probability and the degrees of freedom.
T.INV.2T **
Returns the inverse of the Student’s t-distribution.
T.TEST **
Returns the probability associated with a Student’s t-Test.
TREND
Returns values along a linear trend.
36_475362-bapp01.indd 730
4/14/10 10:33 PM
731
Appendix A: Excel Function Reference
Function
What It Does
TRIMMEAN
Returns the mean of the interior of a data set.
VAR.P **
Calculates variance based on the entire population.
VAR.S **
Estimates variance based on a sample.
VARA
Estimates variance based on a sample, including logical values and text.
VARPA
Calculates variance based on the entire population, including logical values and text.
WEIBULL.DIST **
Returns the Weibull distribution.
Z.TEST **
Returns the one-tailed probability-value of a z-Test.
* Indicates a function introduced in Excel 2007. ** Indicates a function introduced in Excel 2010.
Table A-12: Text Category Functions Function
What It Does
BAHTTEXT
Converts a number to Baht text.
CHAR
Returns the character specified by the code number.
CLEAN
Removes all nonprintable characters from text.
CODE
Returns a numeric code for the first character in a text string.
CONCATENATE
Joins several text items into one text item.
DOLLAR
Converts a number to text, using currency format.
EXACT
Checks to see whether two text values are identical.
FIND
Finds one text value within another (case sensitive).
FIXED
Formats a number as text with a fixed number of decimals.
LEFT
Returns the leftmost characters from a text value.
LEN
Returns the number of characters in a text string.
LOWER
Converts text to lowercase.
MID
Returns a specific number of characters from a text string, starting at the position you specify.
PROPER
Capitalizes the first letter in each word of a text value.
REPLACE
Replaces characters within text.
REPT
Repeats text a given number of times.
RIGHT
Returns the rightmost characters from a text value.
SEARCH
Finds one text value within another (not case-sensitive).
SUBSTITUTE
Substitutes new text for old text in a text string.
T
Returns the text referred to by value. continued
36_475362-bapp01.indd 731
4/14/10 10:33 PM
732
Part VII: Appendixes
Table A-12: Text Category Functions (continued) Function
What It Does
TEXT
Formats a number and converts it to text.
TRIM
Removes excess spaces from text.
UPPER
Converts text to uppercase.
VALUE
Converts a text argument to a number.
36_475362-bapp01.indd 732
4/14/10 10:33 PM
APPENDIX
B
Using Custom Number Formats Although Excel provides a good variety of built-in number formats, you may find that none of these suits your needs. This appendix describes how to create custom number formats and provides many examples.
About Number Formatting By default, all cells use the General number format. This is basically a “what you type is what you get” format. If the cell is not wide enough to show the entire number, the General format rounds numbers with decimals and uses scientific notation for large numbers. In many cases, you may want to format a cell with something other than the General number format. The key thing to remember about number formatting is that it affects only how a value is displayed. The actual number remains intact, and any formulas that use a formatted number use the actual number. An exception to this rule occurs if you specify the Precision as Displayed option on the Calculation tab of the Options dialog box. If that option is in effect, formulas will use the values that are actually displayed in the cells. In general, using this option is not a good idea because it changes the underlying values in your worksheet.
One more thing to keep in mind: If you use Excel’s Find and Replace dialog box (choose Home➜ Editing➜Find & Select➜Find), characters that are displayed are a result of number formatting (for example, a currency symbol) and are not searchable by default. To locate information based on formatting, use the Search In Value option in the Find and Replace dialog box.
733
37_475362-bapp02.indd 733
4/14/10 10:33 PM
734
Part VII: Appendixes
Automatic number formatting Excel is smart enough to perform some formatting for you automatically. For example, if you enter 12.3% into a cell, Excel knows that you want to use a percentage format and applies it automatically. If you use commas to separate thousands (such as 123,456), Excel applies comma formatting for you. And if you precede your value with a currency symbol, Excel formats the cell for currency. You have an option when it comes to entering values into cells formatted as a percentage. Access the Excel Options dialog box and click the Advanced tab. If the check box labeled Enable Automatic Percent Entry is checked (the default setting), you can simply enter a normal value into a cell formatted to display as a percent (for example, enter 12.5 for 12.5%). If this check box isn’t checked, you must enter the value as a decimal (for example, .125 for 12.5%).
Excel automatically applies a built-in number format to a cell based on the following criteria: h If a number contains a slash (/), it may be converted to a date format or a fraction format. h If a number contains a hyphen (-), it may be converted to a date format. h If a number contains a colon (:), or is followed by a space and the letter A or P, it may be converted to a time format. h If a number contains the letter E (in either uppercase or lowercase), it may be converted to scientific notation or exponential format. To avoid automatic number formatting when you enter a value, pre-format the cell with the desired number format or precede your entry with an apostrophe. (The apostrophe makes the entry text, so number formatting is not applied to the cell.)
Formatting numbers by using the Ribbon The Number group on the Home tab of the Ribbon contains several controls that enable you to apply common number formats quickly. The Number Format drop-down control gives you quick access to 11 common number formats. In addition, the Number group contains some buttons. When you click one of these buttons, the selected cells take on the specified number format. Table B-1 summarizes the formats that these buttons perform in the U.S. English version of Excel. Some of these buttons actually apply predefined styles to the selected cells. Access Excel’s styles by using the style gallery, in the Styles group of the Home tab.
37_475362-bapp02.indd 734
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
735
Table B-1: Number-Formatting Buttons on the Ribbon Button Name
Formatting Applied
Accounting Number Format
Adds a dollar sign to the left, separates thousands with a comma, and displays the value with two digits to the right of the decimal point. This is a drop-down control, so that you can select other common currency symbols.
Percent Style
Displays the value as a percentage, with no decimal places.
Comma Style
Separates thousands with a comma and displays the value with two digits to the right of the decimal place.
Increase Decimal
Increases the number of digits to the right of the decimal point by one.
Decrease Decimal
Decreases the number of digits to the right of the decimal point by one.
Using shortcut keys to format numbers Another way to apply number formatting is to use shortcut keys. Table B-2 summarizes the shortcut key combinations that you can use to apply common number formatting to the selected cells or range. Notice that these are the shifted versions of the number keys along the top of a typical keyboard.
Table B-2: Number-Formatting Keyboard Shortcuts Key Combination
Formatting Applied
Ctrl+Shift+~
General number format (that is, unformatted values).
Ctrl+Shift+!
Two decimal places, thousands separator, and a hyphen for negative values.
Ctrl+Shift+@
Time format with the hour, minute, and AM or PM.
Ctrl+Shift+#
Date format with the day, month, and year.
Ctrl+Shift+$
Currency format with two decimal places. (Negative numbers appear in parentheses.)
Ctrl+Shift+%
Percentage format with no decimal places.
Ctrl+Shift+^
Scientific notation number format with two decimal places.
Using the Format Cells dialog box to format numbers For maximum control of number formatting, use the Number tab of the Format Cells dialog box. You can access this dialog box in any of several ways: h Click the dialog box selector in the Home➜Number group. h Choose Home➜Number➜Number Format➜More Number Formats. h Press Ctrl+1.
37_475362-bapp02.indd 735
4/14/10 10:33 PM
736
Part VII: Appendixes
The Number tab of the Format Cells dialog box contains 12 categories of number formats from which to choose. When you select a category from the list box, the right side of the dialog box changes to display appropriate options. Following is a list of the number-format categories along with some general comments: h General: The default format; it displays numbers as integers, decimals, or in scientific notation if the value is too wide to fit into the cell. h Number: Enables you to specify the number of decimal places, whether to use your system thousands separator (for example, a comma) to separate thousands, and how to display negative numbers. h Currency: Enables you to specify the number of decimal places, to choose a currency symbol, and to display negative numbers. This format always uses the system thousands separator symbol (for example, a comma) to separate thousands. h Accounting: Differs from the Currency format in that the currency symbols always line up vertically, regardless of the number of digits displayed in the value. h Date: Enables you to choose from a variety of date formats and select the locale for your date formats. h Time: Enables you to choose from a number of time formats and select the locale for your time formats. h Percentage: Enables you to choose the number of decimal places; always displays a percent sign. h Fraction: Enables you to choose from among nine fraction formats. h Scientific: Displays numbers in exponential notation (with an E): 2.00E+05 = 200,000. You can choose the number of decimal places to display to the left of E. h Text: When applied to a value, causes Excel to treat the value as text (even if it looks like a value). This feature is useful for such items as numerical part numbers and credit card numbers. h Special: Contains additional number formats. The list varies, depending on the locale you choose. For the English (United States) locale, the formatting options are Zip Code, Zip Code +4, Phone Number, and Social Security Number. h Custom: Enables you to define custom number formats not included in any of the other categories. If the cell displays a series of hash marks after you apply a number format (such as #########), it usually means that the column isn’t wide enough to display the value with the number format that you selected. Either make the column wider (by dragging the right border of the column header) or change the number format. A series of hash marks also can mean that the cell contains an invalid date or time.
37_475362-bapp02.indd 736
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
737
Creating a Custom Number Format The Custom category on the Number tab of the Format Cells dialog box (see Figure B-1) enables you to create number formats not included in any of the other categories. Excel gives you a great deal of flexibility in creating custom number formats. When you create a custom number format, it can be used to format any cells in the workbook. You can create as many custom number formats as you need.
Figure B-1: The Number tab of the Format Cells dialog box.
Custom number formats are stored with the workbook in which they are defined. To make the custom format available in a different workbook, you can just copy a cell that uses the custom format to the other workbook.
You construct a number format by specifying a series of codes as a number format string. You enter this code sequence in the Type field after you select the Custom category on the Number tab of the Format Cells dialog box. Here’s an example of a simple number format code: 0.000
37_475362-bapp02.indd 737
4/14/10 10:33 PM
738
Part VII: Appendixes
This code consists of placeholders and a decimal point; it tells Excel to display the value with three digits to the right of the decimal place. Here’s another example: 00000
This custom number format has five placeholders and displays the value with five digits (no decimal point). This format is good to use when the cell holds a five-digit ZIP code. (In fact, this is the code actually used by the Zip Code format in the Special category.) When you format the cell with this number format and then enter a ZIP code, such as 06604 (Bridgeport, CT), the value is displayed with the leading zero. If you enter this number into a cell with the General number format, it displays 6604 (no leading zero). Scroll through the list of number formats in the Custom category of the Format Cells dialog box to see many more examples. In many cases, you can use one of these codes as a starting point, and you’ll need to customize it only slightly. The companion CD-ROM contains a workbook with many custom number format examples. The file is named number formats.xlsx.
Parts of a number format string A custom format string can have up to four sections, which enables you to specify different format codes for positive numbers, negative numbers, zero values, and text. You do so by separating the codes with a semicolon. The codes are arranged in the following order: Positive format; Negative format; Zero format; Text format
If you don’t use all four sections of a format string, Excel interprets the format string as follows: h If you use only one section: The format string applies to all types of entries. h If you use two sections: The first section applies to positive values and zeros, and the second section applies to negative values. h If you use three sections: The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros. h If you use all four sections: The last section applies to text stored in the cell. The following is an example of a custom number format that specifies a different format for each of these types: [Green]General;[Red]General;[Black]General;[Blue]General
37_475362-bapp02.indd 738
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
739
Pre-formatting cells Usually, you’ll apply number formats to cells that already contain values. You also can format cells with a specific number format before you make an entry. Then, when you enter information, it takes on the format that you specified. You can pre-format specific cells, entire rows or columns, or even the entire worksheet. Rather than pre-format an entire worksheet, however, you can change the number format for the Normal style. (Unless you specify otherwise, all cells use the Normal style.) Change the Normal style by displaying the Style gallery (choose Home➜Styles). Right-click the Normal style icon and then choose Modify to display the Style dialog box. In the Style dialog box, click the Format button and then choose the new number format that you want to use for the Normal style.
This custom number format example takes advantage of the fact that colors have special codes. A cell formatted with this custom number format displays its contents in a different color, depending on the value. When a cell is formatted with this custom number format, a positive number is green, a negative number is red, a zero is black, and text is blue. If you want to apply cell formatting automatically (such as text or background color) based on the cell’s contents, a much better solution is to use Excel’s Conditional Formatting feature. Chapter 19 covers conditional formatting.
Custom number format codes Table B-3 lists the formatting codes available for custom formats, along with brief descriptions.
Table B-3: Codes Used to Create Custom Number Formats Code
Comments
General
Displays the number in General format.
#
Digit placeholder. Displays only significant digits, and does not display insignificant zeros.
0 (zero)
Digit placeholder. Displays insignificant zeros if a number has fewer digits than there are zeros in the format.
?
Digit placeholder. Adds spaces for insignificant zeros on either side of the decimal point so that decimal points align when formatted with a fixed-width font. You can also use ? for fractions that have varying numbers of digits.
.
Decimal point.
%
Percentage.
,
Thousands separator. continued
37_475362-bapp02.indd 739
4/14/10 10:33 PM
740
Part VII: Appendixes
Table B-3: Codes Used to Create Custom Number Formats (continued) Code
Comments
E- E+ e- e+
Scientific notation.
$ - + / ( ) : space
Displays this character.
\
Displays the next character in the format.
*
Repeats the next character, to fill the column width.
_ (underscore)
Leaves a space equal to the width of the next character.
“text”
Displays the text inside the double quotation marks.
@
Text placeholder.
[color]
Displays the characters in the color specified. Can be any of the following text strings (not case sensitive): Black, Blue, Cyan, Green, Magenta, Red, White, or Yellow.
[Color n]
Displays the corresponding color in the color palette, where n is a number from 0 to 56.
[condition value]
Enables you to set your own criterion for each section of a number format.
Table B-4 lists the codes used to create custom formats for dates and times.
Table B-4: Codes Used in Creating Custom Formats for Dates and Times Code
Comments
m
Displays the month as a number without leading zeros (1–12).
mm
Displays the month as a number with leading zeros (01–12).
mmm
Displays the month as an abbreviation (Jan–Dec).
mmmm
Displays the month as a full name (January–December).
mmmmm
Displays the first letter of the month (J–D).
d
Displays the day as a number without leading zeros (1–31).
dd
Displays the day as a number with leading zeros (01–31).
ddd
Displays the day as an abbreviation (Sun–Sat).
dddd
Displays the day as a full name (Sunday–Saturday).
yy or yyyy
Displays the year as a two-digit number (00–99) or as a four-digit number (1900–9999).
h or hh
Displays the hour as a number without leading zeros (0–23) or as a number with leading zeros (00–23).
m or mm
Displays the minute as a number without leading zeros (0–59) or as a number with leading zeros (00–59).
s or ss
Displays the second as a number without leading zeros (0–59) or as a number with leading zeros (00–59).
[]
Displays hours greater than 24 or minutes or seconds greater than 60.
AM/PM
Displays the hour using a 12-hour clock. If no AM/PM indicator is used, the hour uses a 24-hour clock.
37_475362-bapp02.indd 740
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
741
Where did those number formats come from? Excel may create custom number formats without you realizing it. When you use the Increase Decimal or Decrease Decimal button on the Home➜Number group of the Ribbon (or in the Mini Toolbar), Excel creates new custom number formats, which appear on the Number tab of the Format Cells dialog box. For example, if you click the Increase Decimal button five times, the following custom number formats are created: 0.0 0.000 0.0000 0.000000
A format string for two decimal places is not created because that format string is built in.
Custom Number Format Examples The remainder of this appendix consists of useful examples of custom number formats. You can use most of these format codes as-is. Others may require slight modification to meet your needs.
Scaling values You can use a custom number format to scale a number. For example, if you work with very large numbers, you may want to display the numbers in thousands (that is, displaying 1,000,000 as 1,000). The actual number, of course, will be used in calculations that involve that cell. The formatting affects only how it displays.
Displaying values in thousands The following format string displays values without the last three digits to the left of the decimal place, and no decimal places. In other words, the value appears as if it’s divided by 1,000 and rounded to no decimal places. #,###,
A variation of this format string follows. A value with this number format appears as if it’s divided by 1,000 and rounded to two decimal places. #,###.00,
Table B-5 shows examples of these number formats.
37_475362-bapp02.indd 741
4/14/10 10:33 PM
742
Part VII: Appendixes
Table B-5: Examples of Displaying Values in Thousands Value
Number Format
Display
123456
#,###,
123
1234565
#,###,
1,235
–323434
#,###,
–323
123123.123
#,###,
123
499
#,###,
(blank)
500
#,###,
1
123456
#,###.00,
123.46
1234565
#,###.00,
1,234.57
–323434
#,###.00,
–323.43
123123.123
#,###.00,
123.12
499
#,###.00,
.50
500
#,###.00,
.50
Displaying values in hundreds The following format string displays values in hundreds, with two decimal places. A value with this number format appears as if it’s divided by 100 and rounded to two decimal places. 0”.”00
Table B-6 shows examples of these number formats.
Table B-6: Examples of Displaying Values in Hundreds Value
Number Format
Display
546
0”.”00
5.46
100
0”.”00
1.00
9890
0”.”00
98.90
500
0”.”00
5.00
–500
0”.”00
–5.00
0
0”.”00
0.00
Displaying values in millions The following format string displays values in millions, with no decimal places. A value with this number appears as if it’s divided by 1,000,000 and rounded to no decimal places. #,###,,
37_475362-bapp02.indd 742
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
743
A variation of this format string follows. A value with this number appears as if it’s divided by 1,000,000 and rounded to two decimal places. #,###.00,,
Another variation follows. This adds the letter M to the end of the value. #,###,,”M”
The following format string is a bit more complex. It adds the letter M to the end of the value — and also displays negative values in parentheses as well as displaying zeros. #,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
Table B-7 shows examples of these format strings.
Table B-7: Examples of Displaying Values in Millions Value
Number Format
Display
123456789
#,###,,
123
1.23457E+11
#,###,,
123,457
1000000
#,###,,
1
5000000
#,###,,
5
–5000000
#,###,,
–5
0
#,###,,
(blank)
123456789
#,###.00,,
123.46
1.23457E+11
#,###.00,,
123,457.00
1000000
#,###.00,,
1.00
5000000
#,###.00,,
5.00
–5000000
#,###.00,,
–5.00
0
#,###.00,,
.00
123456789
#,###,,”M”
123M
1.23457E+11
#,###,,”M”
123,457M
1000000
#,###,,”M”
1M
5000000
#,###,,”M”
5M
–5000000
#,###,,”M”
–5M
0
#,###,,”M”
M
123456789
#,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
123.5M continued
37_475362-bapp02.indd 743
4/14/10 10:33 PM
744
Part VII: Appendixes
Table B-7: Examples of Displaying Values in Millions (continued) Value
Number Format
Display
1.23457E+11
#,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
123,456.8M
1000000
#,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
1.0M
5000000
#,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
5.0M
–5000000
#,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
(5.0M)
0
#,###.0,,”M”_);(#,###.0,,”M)”;0.0”M”_)
0.0M
Adding zeros to a value The following format string displays a value with three additional zeros and no decimal places. A value with this number format appears as if it’s rounded to no decimal places and then multiplied by 1,000. #”,000”
Examples of this format string, plus a variation that adds six zeros, are shown in Table B-8.
Table B-8: Examples of Displaying a Value with Extra Zeros Value
Number Format
Display
1
#”,000”
1,000
1.5
#”,000”
2,000
43
#”,000”
43,000
–54
#”,000”
–54,000
5.5
#”,000”
6,000
0.5
#”,000,000”
1,000,000
0
#”,000,000”
,000,000
1
#”,000,000”
1,000,000
1.5
#”,000,000”
2,000,000
43
#”,000,000”
43,000,000
–54
#”,000,000”
–54,000,000
5.5
#”,000,000”
6,000,000
0.5
#”,000,000”
1,000,000
Hiding zeros In the following format string, the third element of the string is empty, which causes zero-value cells to display as blank:
37_475362-bapp02.indd 744
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
745
General;-General;
This format string uses the General format for positive and negative values. You can, of course, substitute any other format codes for the positive and negative parts of the format string.
Displaying leading zeros To display leading zeros, create a custom number format that uses the 0 character. For example, if you want all numbers to display with ten digits, use the number format string that follows. Values with fewer than ten digits will display with leading zeros. 0000000000
You also can force all numbers to display with a fixed number of leading zeros. The format string that follows, for example, prepends three zeros to each number: “000”#
In the following example, the format string uses the repeat character code (an asterisk) to apply enough leading zeros to fill the entire width of the cell: *00
Displaying fractions Excel supports quite a few built-in fraction number formats. (Select the Fraction category from the Number tab of the Format Cells dialog box.) For example, to display the value .125 as a fraction with 8 as the denominator, select As Eighths (4/8) from the Type list. You can use a custom format string to create other fractional formats. For example, the following format string displays a value in 50ths: # ??/50
To display the fraction reduced to its lowest terms, use a question mark after the slash symbol. For example, the value 0.125 can be expressed as 2/16, and 2/16 can be reduced to 1/8. Here’s an example of a number format that displays the value as a fraction reduced to its simplest terms: # ?/?
37_475362-bapp02.indd 745
4/14/10 10:33 PM
746
Part VII: Appendixes
If you omit the leading hash symbol, the value displays without a leading value. For example, the value 2.5 would display as 5/2 using this number format code: ?/?
The following format string displays a value in terms of fractional dollars. For example, the value 154.87 displays as 154 and 87/100 Dollars. 0 “and “??/100 “Dollars”
The following example displays the value in 16ths, with an appended double quotation mark. This format string is useful when you deal with inches (for example, 2/16). # ??/16\”
Displaying N/A for text The following number format string uses General formatting for all cell entries except text. Text entries appear as N/A. 0.0;0.0;0.0;”N/A”
You can, of course, modify the format string to display specific formats for values. The following variation displays values with one decimal place: 0.0;0.0;0.0;”N/A”
Displaying text in quotes The following format string displays numbers normally but surrounds text with double quotation marks: General;General;General;\”@\”
Repeating a cell entry The following number format is perhaps best suited as an April Fool’s gag played on an office mate. It displays the contents of the cell three times. For example, if the cell contains the text Budget, the cell displays Budget Budget Budget. If the cell contains the number 12, it displays as 12 12 12. @ @ @
37_475362-bapp02.indd 746
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
747
Testing custom number formats When you create a custom number format, don’t overlook the Sample box in the Number tab of the Format Cells dialog box. This box displays the value in the active cell using the format string in the Type box. It’s a good idea to test your custom number formats by using the following data: a positive value, a negative value, a zero value, and text. Often, creating a custom number format takes several attempts. Each time you edit a format string, it is added to the list. When you finally get the correct format string, access the Format Cells dialog box one more time and delete your previous attempts.
Displaying a negative sign on the right The following format string displays negative values with the negative sign to the right of the number. Positive values have an additional space on the right, so both positive and negative numbers align properly on the right. 0.00_-;0.00-
To make the negative numbers more prominent, you can add a color code to the negative part of the number format string: 0.00_-;[Red]0.00-
Conditional number formatting Conditional formatting refers to formatting that is applied based on the contents of a cell. Excel’s Conditional Formatting feature provides the most efficient way to perform conditional formatting of numbers, but you also can use custom number formats. A conditional number formatting string is limited to three conditions: Two of them are explicit, and the third one is implied (that is, everything else). The conditions are enclosed in square brackets and must be simple numeric comparisons.
The following format string displays different text (no value), depending on the value in the cell. This format string essentially separates the numbers into three groups: less than or equal to 4, greater than or equal to 8, and other. [=8]”High”* 0;”Medium”* 0
37_475362-bapp02.indd 747
4/14/10 10:33 PM
748
Part VII: Appendixes
The following number format is useful for telephone numbers. Values greater than 9999999 (that is, numbers with area codes) are displayed as (xxx) xxx-xxxx. Other values (numbers without area codes) are displayed as xxx-xxxx. [>9999999](000) 000-0000;000-0000
For U.S. ZIP codes, you might want to use the format string that follows. This displays ZIP codes using five digits. But if the number is greater than 99999, it uses the ZIP-plus-four format (xxxxx-xxxx). [>99999]00000-0000;00000
Coloring values Custom number format strings can display the cell contents in various colors. The following format string, for example, displays positive numbers in red, negative numbers in green, zero values in black, and text in blue: [Red]General;[Green]-General;[Black]General;[Blue]General
Following is another example of a format string that uses colors. Positive values display normally; negative numbers and text cause Error! to display in red. General;[Red]”Error!”;0;[Red]”Error!”
Using the following format string, values that are less than 2 display in red. Values greater than 4 display in green. Everything else (text, or values between 2 and 4) displays in black. [Red][4]General;[Black]General
As seen in the preceding examples, Excel recognizes color names such as [Red] and [Blue]. It also can use other colors from the color palette, indexed by a number. The following format string, for example, displays the cell contents using the 16th color in the color palette: [Color16]General
Excel’s conditional formatting is a much better way to color text in a cell based on the cell’s value.
37_475362-bapp02.indd 748
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
749
Formatting dates and times When you enter a date into a cell, Excel formats the date using the system short date format. You can change this format using the Windows Control Panel (Regional and Language options). Excel provides many useful built-in date and time formats. Table B-9 shows some other custom date and time formats that you may find useful. The first column of the table shows the date/ time serial number.
Table B-9: Useful Custom Date and Time Formats Value
Number Format
Display
40363
mmmm d, yyyy (dddd)
July 4, 2010 (Sunday)
40363
“It’s” dddd!
It’s Sunday!
40363
dddd, mm/dd/yyyy
Sunday, 07/04/2010
40363
“Month: “mmm
Month: July
40363
General (m/d/yyyy)
40363 (7/4/2010)
0.345
h “Hours”
8 Hours
0.345
h:mm o’clock
8:16 o’clock
0.345
h:mm a/p”m”
8:16 am
0.78
h:mm a/p”.m.”
6:43 p.m.
See Chapter 6 for more information about Excel’s date and time serial number system.
Displaying text with numbers The ability to display text with a value is one of the most useful benefits of using a custom number format. To add text, just create the number format string as usual (or use a built-in number format as a starting point) and put the text within quotation marks. The following number format string, for example, displays a value with the text (US Dollars) added to the end: #,##0.00 “(US Dollars)”
Here’s another example that displays text before the number: “Average: “0.00
37_475362-bapp02.indd 749
4/14/10 10:33 PM
750
Part VII: Appendixes
If you use the preceding number format, you’ll find that the negative sign appears before the text for negative values. To display number signs properly, use this variation: “Average: “0.00;”Average: “-0.00
The following format string displays a value with the words Dollars and Cents. For example, the number 123.45 displays as 123 Dollars and .45 Cents. 0 “Dollars and” .00 “Cents”
Displaying a zero with dashes The following number format string displays zero values as a series of dashes: #,##0.0;-###0.0;------
You can, of course, create lots of variations. For example, you can replace the six hyphens with any of the following: -0~~ “” “[NULL]”
When using angle brackets or square brackets, you must place them within quotation marks.
Formatting numbers using the TEXT function Excel’s TEXT function accepts a number format string as its second argument. For example, the following formula displays the contents of cell A1 using a custom number format that displays a fraction: =TEXT(A1,”# ??/50”)
However, not all formatting codes work when used in this manner. For example, colors and repeating characters are ignored. The following formula does not display the contents of cell A1 in red: =TEXT(A1,”[Red]General”)
37_475362-bapp02.indd 750
4/14/10 10:33 PM
Appendix B: Using Custom Number Formats
751
Using special symbols Your number format strings can use special symbols, such as the copyright symbol, degree symbol, and so on. The easiest way to insert a symbol into a number format string is to enter it into a cell. Copy the character and then paste it into your custom number format string (using Ctrl+V). Use the Insert➜Text➜Symbol command, which displays the Insert Symbol dialog box, to enter a special character into a cell.
Suppressing certain types of entries You can use number formatting to hide certain types of entries. For example, the following format string displays text but not values: ;;
This format string displays values (with one decimal place) but not text or zeros: 0.0;-0.0;;
This format string displays everything except zeros (values display with one decimal place): 0.0;-0.0;;@
You can use the following format string to completely hide the contents of a cell: ;;;
Note that when the cell is activated, however, the cell’s contents are visible on the Formula bar. Refer to Part VI for more information about creating custom worksheet functions using VBA.
Filling a cell with a repeating character The asterisk (*) symbol specifies a repeating character in a number format string. The repeating character completely fills the cell, and adjusts if the column width changes. The following format string, for example, displays the contents of a cell padded on the right with dashes: General*-;-General*-;General*-;General*-
37_475362-bapp02.indd 751
4/14/10 10:33 PM
752
Part VII: Appendixes
Displaying a number format string in a cell Excel doesn’t have a worksheet function that displays the number format for a specified cell. You can, however, create your own function using VBA. Insert the following function procedure into a VBA module: Function NumberFormat(cell) As String ‘ Returns the number format string for a cell Application.Volatile True NumberFormat = cell.Range(“A1”).NumberFormat End Function
Then you can create a formula such as the following: =NumberFormat(C4)
This formula returns the number format for cell C4. If you change a number format, use Ctrl+Alt+F9 to force the function to be reevaluated.
Displaying leading dots The following custom number format is a variation on the accounting format. Using this number format displays the dollar sign on the left and the value on the right. The space in between is filled with dots. ($*.#,##0.00_);_($*.(#,##0.00);_($* “-”??_);_(@_)
37_475362-bapp02.indd 752
4/14/10 10:33 PM
APPENDIX
C
Additional Excel Resources If I’ve done my job, the information provided in this book will be very useful to you. The book, however, cannot cover every conceivable topic. Therefore, I’ve compiled a list of additional resources that you may find helpful. I classify these resources into four categories: the Excel Help system, Microsoft technical support, Internet newsgroups, and Internet Web sites.
The Excel Help System Some users tend to forget about an excellent source of information that’s readily available: the Excel Help system. This Help information is available by clicking the question mark icon in the upper-right corner of Excel’s window. Or, just press F1. Either of these methods displays Excel Help in a new window. Then, type your search query and click Search. The Search button is a drop-down control that lets you specify what and where to search.
The Excel Help system isn’t perfect; it often provides only superficial help and ignores some topics altogether. But, if you’re stuck, a quick search of the Help system may be worth a try.
Microsoft Technical Support Technical support is the common term for assistance provided by a software vendor. In this case, I’m talking about assistance that comes directly from Microsoft. Microsoft technical support is available in several different forms.
753
38_475362-bapp03.indd 753
4/14/10 10:34 PM
754
Part VII: Appendixes
Support options The Microsoft support options are constantly changing. To find out what options are available (both free and fee-based), go to http://support.microsoft.com
Microsoft Knowledge Base Perhaps your best bet for solving a problem may be the Microsoft Knowledge Base, which is the primary Microsoft product information source. It’s an extensive, searchable database that consists of tens of thousands of detailed articles containing technical information, bug lists, fix lists, and more. You have free and unlimited access to the Knowledge Base via the Internet. To access the Knowledge Base, use the following URL and then click Search the Knowledge Base: http://support.microsoft.com/search
Microsoft Excel home page The official home page of Excel is at http://www.microsoft.com/office/excel
This site contains a variety of material, such as tips, templates, answers to questions, training materials, and links to companion products.
Microsoft Office home page For information about Office 2010 (including Excel), try this site: http://office.microsoft.com
You’ll find product updates, add-ins, examples, and lots of other useful information. As you know, the Internet is a dynamic entity that changes rapidly. Web sites are often reorganized, so a particular URL listed in this appendix may not be available when you try to access it.
38_475362-bapp03.indd 754
4/14/10 10:34 PM
Appendix C: Additional Excel Resources
755
Internet Newsgroups Usenet is an Internet service that provides access to several thousand special interest groups that enable you to communicate with people who share common interests. A newsgroup works like a public bulletin board. You can post a message or questions, and (usually) others reply to your message. Thousands of newsgroups cover virtually every topic you can think of (and many that you haven’t thought of). Typically, questions posted on a newsgroup are answered within 24 hours — assuming, of course, that you ask the questions in a manner that makes others want to reply.
Accessing newsgroups by using a newsreader You can use newsreader software to access the Usenet newsgroups. Many such programs are available, but you probably already have one installed: Microsoft Windows Mail (formerly known as Outlook Express), which is installed with Internet Explorer. Microsoft maintains an extensive list of newsgroups, including quite a few devoted to Excel. If your ISP doesn’t carry the Microsoft newsgroups, you can access them directly from the Microsoft news server. (In fact, that’s the preferred method.) You need to configure your newsreader software (not your Web browser) to access the Microsoft news server at this address: msnews.microsoft.com
Accessing newsgroups by using a Web browser As an alternative to using newsreader software, you can read and post to the Microsoft newsgroups directly from your Web browser. This option is often significantly slower than using standard newsgroup software and is best suited for situations in which newsgroup access is prohibited by network policies. h Access thousands of newsgroups at Google Groups. The URL is http://groups.google.com
h Access the Microsoft newsgroups (including Excel newsgroups) from this URL: www.microsoft.com/communities/newsgroups/default.mspx
Table C-1 lists the most popular English-language Excel newsgroups found on the Microsoft news server (and also available at Google Groups).
38_475362-bapp03.indd 755
4/14/10 10:34 PM
756
Part VII: Appendixes
Table C-1: Popular Excel-Related Newsgroups Newsgroup
Topic
microsoft.public.excel
General Excel topics
microsoft.public.excel.charting
Building charts with Excel
microsoft.public.excel.interopoledde
OLE, DDE, and other cross-application issues
microsoft.public.excel.macintosh
Excel issues on the Macintosh operating system
microsoft.public.excel.misc
General topics that don’t fit one of the other categories
microsoft.public.excel.newusers
Help for newcomers to Excel
microsoft.public.excel.printing
Printing with Excel
microsoft.public.excel.programming
Programming Excel with VBA macros
microsoft.public.excel.templates
Spreadsheet Solutions templates and other Xlt files
microsoft.public.excel.worksheet.functions
Worksheet functions
A dozen tips for posting to a newsgroup If you’re new to online newsgroups, here are some pointers: 1. Conduct a search upfront to make sure that your question has not already been answered. 2. Make the subject line descriptive. Postings with a subject line such as Help me! and Another Question are less likely to be answered than postings with a more specific subject, such as Sizing a Chart’s Plot Area. 3. Specify the Excel version that you use. In many cases, the answer to your question depends on your version of Excel. 4. For best results, ask only one question per message. 5. Make your question as specific as possible. 6. Keep your question brief and to the point but provide enough information so that someone can answer it adequately. 7. Indicate what you’ve done to try to answer your own question. 8. Post in the appropriate newsgroup, and don’t cross-post to other groups unless the question applies to multiple groups. 9. Don’t type in all uppercase or all lowercase; check your grammar and spelling. 10. Don’t include a file attachment. 11. Avoid posting in HTML format. Plain text is the preferred format. 12. If you request an e-mail reply in addition to a newsgroup reply, don’t use an anti-spam e-mail address that requires the responder to modify your address. Why cause extra work for someone doing you a favor?
38_475362-bapp03.indd 756
4/14/10 10:34 PM
Appendix C: Additional Excel Resources
757
Searching newsgroups The fastest way to find a quick answer to a question is to search the past newsgroup postings. Often, searching past newsgroup postings is an excellent alternative to posting a question to the newsgroup because you can get the answer immediately. Unless your question is very obscure, there’s an excellent chance that your question has already been asked and answered. The best source for searching newsgroup postings is Google Groups, at the following Web address: http://groups.google.com
How does searching work? Suppose that you have a problem identifying unique values in a range of cells. You can perform a search using the following keywords: Excel, Range, and Unique. The Google search engine probably will find dozens of newsgroup postings that deal with these topics. If the number of results is too large, refine your search by adding search terms. Sifting through the messages may take a while, but you have an excellent chance of finding an answer to your question. In fact, I estimate that at least 90 percent of the questions posted in the Excel newsgroups can be answered by searching Google.
Internet Web sites The World Wide Web (WWW) has dozens of excellent sites devoted to Excel. I list a few of my favorites here.
The Spreadsheet Page This is my own Web site, which contains files to download, developer tips, instructions for accessing Excel Easter eggs, spreadsheet jokes, an extensive list of links to other Excel sites, and information about my books. The URL is http://spreadsheetpage.com
Daily Dose of Excel This is a frequently updated Weblog created by Dick Kusleika, with about a dozen contributors. It covers a variety of topics, and readers can leave comments. The URL is http://dailydoseofexcel.com
38_475362-bapp03.indd 757
4/14/10 10:34 PM
758
Part VII: Appendixes
Jon Peltier’s Excel page Those who frequent the microsoft.public.excel.charting newsgroup are familiar with Jon Peltier. Jon has an uncanny ability to solve practically any chart-related problem. His Web site contains many Excel tips and an extensive collection of charting examples. The URL is http://peltiertech.com/Excel
Pearson Software consulting This site, maintained by Chip Pearson, contains dozens of useful examples of VBA and clever formula techniques. The URL is www.cpearson.com/excel.htm
Contextures This site is maintained by Deborah Dalgleish, and covers Excel and Access. The URL is http://contextures.com/
David McRitchie’s Excel pages David’s site is jam-packed with useful Excel information and is updated frequently. The URL is www.mvps.org/dmcritchie/excel/excel.htm
Pointy Haired Dilbert An interesting Excel blog by Chandoo. The URL is http://chandoo.org/wp/
Mr. Excel Mr. Excel, also known as Bill Jelen, maintains an extensive site devoted to Excel. The site also features a message board. The URL is www.mrexcel.com
38_475362-bapp03.indd 758
4/14/10 10:34 PM
APPENDIX
D
What’s on the CD-ROM? This appendix provides you with information on the contents of the CD that accompanies this book. For the latest and greatest information, please refer to the ReadMe file located at the root of the CD. This appendix provides information on the following topics: h System requirements h Using the CD h Files and software on the CD h Troubleshooting
System Requirements Make sure that your computer meets these minimum requirements: h A Windows PC with Microsoft Excel 2010 installed. h A CD-ROM drive.
Using the CD To install the items from the CD to your hard drive, follow these steps: 1. Insert the CD into your computer’s CD-ROM drive. A window appears displaying the License Agreement.
759
39_475362-bapp04.indd 759
4/14/10 10:34 PM
760
Part VII: Appendixes
The interface won’t launch if you have Autorun (or Autoplay) disabled. In that case, choose Start➜Run. In the dialog box that appears, type D:\start.exe. (Replace D with the proper letter if your CD drive uses a different letter. If you don’t know the letter, see how your CD drive is listed under My Computer.)
2. Press Accept to continue. You can then view the directory structure on the CD.
Files and Software on the CD The following sections provide more details about the software and other materials available on the CD.
eBook version of Excel 2010 Formulas The complete text of the book that you hold in your hands is provided on the CD in Adobe’s Portable Document Format (PDF). You can read and quickly search the contents of this PDF file by using Adobe’s Acrobat Reader, also included on the CD. Adobe Reader is a freeware application for viewing files in the Adobe Portable Document format.
Shareware programs are fully functional, trial versions of copyrighted programs. If you like particular programs, register with their authors for a nominal fee and receive licenses, enhanced versions, and technical support. Freeware programs are copyrighted games, applications, and utilities that are free for personal use. Unlike shareware, these programs do not require a fee or provide technical support. GNU software is governed by its own license, which is included inside the folder of the GNU product. See the GNU license for more details. Trial, demo, or evaluation versions are usually limited either by time or functionality (such as being unable to save projects). Some trial versions are very sensitive to system date changes. If you alter your computer’s date, the programs will “time out” and will no longer be functional.
Examples files for Excel 2010 Formulas Most of the chapters in this book refer to workbook files that are available on the CD-ROM. Each chapter has its own subdirectory on the CD. For example, you can find the files for Chapter 5 in the following directory: examples\chapter 05
39_475362-bapp04.indd 760
4/14/10 10:34 PM
Appendix D: What’s on the CD-ROM?
761
The files are Excel 2010 workbook files that have either of the following extensions: h XLSX: An Excel workbook file h XLSM: An Excel workbook file that contains VBA macros When you open an XLSM file, Excel may display a Security Warning below the Formula bar. To enable macros, click the Enable Content button in the Security Warning panel. Because the files on this CD are from a trusted source, you may want to copy the files to your hard drive, and then designate the folder as a trusted location. To do so, follow these steps: 1. Open an Explorer window, and select the CD-ROM drive that contains the companion CD-ROM. 2. Right-click the folder that corresponds to the root folder for the example files, and select Copy from the shortcut menu. 3. Activate the folder on your hard drive where you’d like to copy the files. Right-click the directory, and then select Paste from the shortcut menu. The CD-ROM files are then copied to a subfolder in the folder that you specified in Step 3. To designate this new folder as a trusted location: 1. Start Excel and choose File➜Options to display the Excel Options dialog box. 2. In the Excel Options dialog box, click the Trust Center tab. 3. Click the Trust Center Settings button. 4. In the Trust Center dialog box, click the Trusted Locations tab. 5. Click the Add New Location button to display the Microsoft Office Trusted Location dialog box. 6. In the Microsoft Office Trusted Location dialog box, click the Browse button, and locate the folder that contains the files that you copied from the CD-ROM. 7. Make sure that you select the option labeled Subfolders of This Location Are Also Trusted. After performing these steps, when you open XLSM files from this location, the macros are enabled and you don’t see the security warning. Following is a list of the chapter example files with a brief description of each. Note that not all chapters have example files.
Chapter 1 h worksheet controls.xlsx: Demonstrates the use of controls placed directly on a worksheet.
39_475362-bapp04.indd 761
4/14/10 10:34 PM
762
Part VII: Appendixes
Chapter 5 h character set.xlsm: Displays the characters in any font installed on your system. h text formula examples.xlsx: Contains examples of formulas that work with text. h text histogram.xlsx: Demonstrates how to create a simple histogram directly in a range.
Chapter 6 h day of the week count.xlsx: Demonstrates how to count the occurrences of a day of the week. h gmt conversion.xlsx: Demonstrates how to convert times between time zones. h holidays.xlsx: Contains formulas to calculate the dates of various U.S. holidays. h jogging log.xlsx: Demonstrates how to work with time values that do not represent a time of day. h ordinal dates.xlsx: Demonstrates a formula to express a date as an ordinal number. h time sheet.xlsm: Calculates a weekly time sheet. h work days.xlsx: Demonstrates the NETWORKDAYS function.
Chapter 7 h adjustable bins.xlsx: Demonstrates formulas that create adjustable bins for a frequency distribution. h basic counting.xlsx: Demonstrates some basic counting formulas. h conditional summing.xlsx: Demonstrates various ways to calculate conditional sums. h count unique.xlsx: Demonstrates how to count unique (nonduplicated) entries in a range. h counting text in a range.xlsx: Contains various formulas that count occurrences of specific text. h cumulative sum.xlsx: Demonstrates how to display a cumulative sum of values. h frequency distribution.xlsx: Demonstrates three ways to create a frequency distribution. h multiple criteria counting.xlsx: Demonstrates formulas that perform multiple criteria counting.
Chapter 8 h basic lookup examples.xlsx: Contains examples of lookup formulas. h specialized lookup examples.xlsx: Contains examples of specialized lookup formulas.
39_475362-bapp04.indd 762
4/14/10 10:34 PM
Appendix D: What’s on the CD-ROM?
763
Chapter 9 h database formulas.xlsx: Demonstrates database functions. h nested subtotals.xlsx: Demonstrates how to create nested subtotals. h real estate database.xlsx: Contains a table of real estate listings, used to demonstrate advanced filtering. h real estate table.xlsx: Contains a table of real estate listings, used to demonstrate sorting and filtering. h table formulas.xlsx: Demonstrates how to use structured references to data within a table.
Chapter 10 h simultaneous equations.xlsx: Demonstrates how to solve simultaneous equations using matrix functions. h solve right triangle.xlsm: Demonstrates how to solve right triangles. h unit conversion tables.xlsx: Contains conversion factors for a variety of measurement units.
Chapter 11 h basic financial formulas.xlsx: Demonstrates various financial functions: PV, FV, PMT, RATE, and NPER. h bond calculations.xlsx: Demonstrates the PRICE and YIELD functions. h extending basic functions.xlsx: Demonstrates how to combine various financial functions. h payment components.xlsx: Demonstrates the IPMT and PPMT functions. h rate conversion.xlsx: Demonstrates the EFFECT and NOMINAL functions.
Chapter 12 h depreciation.xlsx: Demonstrates the depreciation functions. h fvschedule.xlsx: Demonstrates the FVSCHEDULE function. h internal rate of return.xlsx: Demonstrates the IRR function. h irregular cash flows.xlsx: Demonstrates the XMPV and XIRR functions. h multiple irr.xlsx: Demonstrates the MIRR function. h net present value.xlsx: Demonstrates the NPV function.
39_475362-bapp04.indd 763
4/14/10 10:34 PM
764
Part VII: Appendixes
Chapter 13 h amortization.xlsx: Contains a simple loan amortization schedule. h financial statements.xlsx: Contains several types of financial statements. h indices.xlsx: Demonstrates how to create indices. h loan data tables.xlsx: Demonstrates a one-way and a two-way data table.
Chapter 15 h array formula calendar.xlsx: Demonstrates how to display a calendar using a single multicell array formula. h multi-cell array formulas.xlsx: Demonstrates various multicell array formulas. h single-cell array formulas.xlsx: Demonstrates various single-cell array formulas. h yearly calendar.xlsx: Demonstrates how to create a yearly calendar using multicell array formulas.
Chapter 16 h iterative chart animation.xlsx: Contains an example of an animated chart based on an intentional circular reference. h net profit (circular).xlsm: Demonstrates an intentional circular reference. h net profit (not circular).xlsx: Demonstrates an alternative to using a curricular reference formula. h recursive equations.xlsx: Demonstrates how to solve recursive equations by using an intentional circular reference. h simultaneous equations.xlsx : Demonstrates how to solve simultaneous equations by using an intentional circular reference. h unique random integers.xlsx: Demonstrates how to generate a list of unique random integers by using an intentional circular reference.
Chapter 17 h box plot.xlsx: Demonstrates how to create a box plot. h chart from combo box.xlsx: Demonstrates how to display a chart series by selecting the data from a combo box. h clock chart.xlsm: Displays a fully functional analog clock, created with an XY chart.
39_475362-bapp04.indd 764
4/14/10 10:34 PM
Appendix D: What’s on the CD-ROM?
765
h comparative histogram.xlsx: Demonstrates how to create a comparative histogram. h conditional colors.xlsx: Demonstrates how to create a column chart with colors that depend on the value of each data point. h function plot 2D.xlsx: Plots functions with one variable. h function plot 3D.xlsm: Plots functions with two variables. h gantt chart.xlsx: Demonstrates how to create a Gantt chart. h gauge chart.xlsx: Demonstrates how to create a gauge chart. h hypocycloid: animated.xlsm: Plots an animated hypocycloid curve. h hypocycloid chart.xlsx: Plots a hypocycloid curve. h linear trendline.xlsx: Demonstrates linear trendlines. h nonlinear trendlines.xlsx: Demonstrates nonlinear trendlines. h plot circles.xlsx: Demonstrates how to plot a circle using an XY chart. h plot every nth data point.xlsx: Demonstrates how to plot every nth value in a chart. h plot last n data points.xlsx: Demonstrates how to plot the most recent n values in a chart. h thermometer chart.xlsx: Demonstrates how to create a thermometer chart.
Chapter 18 h bank accounts.xlsx: The bank account pivot table examples. h calculated fields and items.xlsx: The pivot table calculated fields and items example. h county data.xlsx: A pivot table example. h employee list.xlsx: The pivot table grouping example. h hourly readings.xlsx: The pivot table grouping by time example. h income and expense.xlsx: The pivot table referencing example. h music list.xlsx: The pivot table report example. h normalized data.xlsx: Contains an example of normalized data, suitable for a pivot table. h pivot chart slicer.xlsx: Demonstrates the use of pivot chart slicers. h reverse pivot.xlsm: Contains a VBA macro to convert a summary table into a normalized data table. h sales by date.xlsx: The pivot table grouping by date example. h test scores.xlsx: The pivot table frequency distribution example.
39_475362-bapp04.indd 765
4/14/10 10:34 PM
766
Part VII: Appendixes
Chapter 19 h animated color scale.xlsm: Uses a VBA macro to animate color scale conditional formatting. h color scale example.xlsx: Demonstrates conditional formatting using color scales. h conditional formatting examples.xlsx: Contains examples of various types of conditional formatting. h conditional formatting formulas.xlsx: Demonstrates conditional formatting formulas. h conditional formatting with VBA functions.xlsm : Demonstrates conditional formatting using VBA functions. h data bars examples.xlsx: Demonstrates conditional formatting data bars. h data validation examples.xlsx: Contains data validation examples. h extreme color scale.xlsx: Demonstrates a conditional formatting color scale. h icon set examples.xlsx: Demonstrates conditional formatting icon sets.
Chapter 20 h credit card validation.xlsx: Contains a megaformula to determine if a number is a valid credit card number. h name generator.xlsx: Contains a megaformula to generate random names. h no middle name.xlsx: Contains a megaformula to remove middle names from full names. h position of last space.xlsx: Contains a megaformula to determine the position of the last space character in a text string. h time test intermediate.xlsx: Uses intermediate formulas to remove middle names from full names. h time test megaformula.xlsx: Uses megaformulas to remove middle names from full names. h time test named megaformula.xlsx: Uses a named megaformula to remove middle names from full names. h total interest.xlsx: Demonstrates a simple megaformula.
Chapter 24 h function examples.xlsm: Contains VBA function examples.
Chapter 25 h celltype function.xlsm: Contains a VBA function that describes the contents of a cell. h commission function.xlsm: Contains a VBA function to calculate sales commissions.
39_475362-bapp04.indd 766
4/14/10 10:34 PM
Appendix D: What’s on the CD-ROM?
767
h counting functions.xlsm: Contains VBA functions that perform counting. h date functions.xlsm: Contains VBA functions that work with dates. h exact word.xlsm: Demonstrates the VBA function EXACTWORDINSTRING. h extended date functions.xlsm: Contains VBA functions that work with pre-1900 dates. h extended date functions help.docx: A Word document that describes the functions in extended date functions.xlsm. h last nonempty cell.xlsm: Contains VBA functions that return the last nonempty cell in a row or column. h monthnames.xlsm: Contains a VBA function that returns an array. h multisheet functions.xlsm: Contains a VBA function designed to work across multiple worksheets. h random functions.xlsm: Contains VBA functions that deal with random numbers. h random integers function.xlsm: Contains a VBA function that returns an array of nonduplicated random integers. h range randomize function.xlsm: Contains a VBA function that returns an array of randomized cells. h simple functions.xlsm: Contains simple VBA function examples. h spelldollars function.xlsm: Contains a VBA function that spells out a numerical value. h statfunction function.xlsm: Contains a VBA function that returns a variety of statistical calculations. h sum function emulation.xlsm: Contains a VBA function that emulates Excel’s SUM function. h text manipulation functions.xlsm: Contains VBA functions that manipulate text.
Appendix A h worksheet functions.xlsx: Contains an interactive list of all Excel 2010 worksheet functions.
Appendix B h number formats.xlsx: Contains examples of custom number formats.
Troubleshooting If you have difficulty installing or using any of the materials on the companion CD, try the following solutions:
39_475362-bapp04.indd 767
4/14/10 10:34 PM
768
Part VII: Appendixes
h Turn off any antivirus software that you may have running. Installers sometimes mimic virus activity and can make your computer incorrectly believe that it is being infected by a virus. (Be sure to turn the antivirus software back on later.) h Close all running programs. The more programs that you’re running, the less memory is available to other programs. Installers also typically update files and programs; if you keep other programs running, the installation may not work properly. h Reference the ReadMe: Please refer to the ReadMe file located at the root of the CD-ROM for the latest product information at the time of publication. If you still have trouble with the CD, please call the Customer Care phone number: 800-762-2974. Outside the United States, call 1-317-572-3994. You can also contact Customer Service via the Web at www.wiley.com/techsupport. Wiley Publishing, Inc., will provide technical support only for installation and other general quality-control items; for technical support on an application, consult the program’s vendor. To place additional orders or to request information about other Wiley products, please call 877-762-2974.
39_475362-bapp04.indd 768
4/14/10 10:34 PM
Index Symbols (+) addition operator, 45, 48, 644 (=) assignment operator, 26, 45, 48, 644 (*) asterisk operator, 134, 263 (@) at symbol, 40, 253 (\) backslash operator, 644 (:) colon operator, 45, 48 (,) comma operator, 45, 48 #DIV/0! error, 59 (/) division operator, 45, 48, 644 (^) exponentiation operator, 45, 48, 644 (>) greater than operator, 45, 48 (>=) greater than or equal to operator, 45, 48, 644 (####) hash marks, 575–576 (=) operator, 45, 48, 644 GROWTH function, 729
H hard-coding values used in formulas, avoiding, 50 HARMEAN function, 729 hash marks (####), 146, 173, 575–576 Help system, 28–29 HEX2BIN function, 721 HEX2DEC function, 721 HEX2OCT function, 721 hidden names, 75 Hidden property, 665–666 HLOOKUP function, 214, 216–217, 220–221, 725 holidays, calculating dates for, 164–167 HOUR function, 169, 720 HYPERLINK function, 725 HYPGEOMDIST function, 718 HYPGEOM.DIST function, 729
I icon sets, conditional formatting with, 528–532 identity operations, 387 IF function, 105, 204–205, 725 IFERROR function, 138–139, 349, 392, 725 If-Then construct, 649–650 IMABS function, 721 IMAGINARY function, 721 IMARGUMENT function, 721 IMCONJUGATE function, 721 IMCOS function, 722
4/14/10 10:35 PM
Index
IMDIV function, 722 IMEXP function, 722 IMLN function, 722 IMLOG2 function, 722 IMLOG10 function, 722 Imp operator, 645 imported numbers treated as text, 120 IMPOWER function, 722 IMPRODUCT function, 722 IMREAL function, 722 IMSIN function, 722 IMSQRT function, 722 IMSUB function, 722 IMSUM function, 722 INDEX function, 81–82, 214, 219, 222, 375, 725 indices, creating, 362–363 indirect cell precedents, 591 indirect circular references, 417 INDIRECT function, 96–97, 97, 383, 725 INFO function, 724 information functions, 116, 724 Insert Function dialog box, 111–112, 620–624 INT function, 285, 288–289, 726 Integer data type, 639 intentional circular references animating a chart using iteration, 426–427 examples, 421–427 overview, 417–420 potential problems with, 427 recursive equation, solving, 423–424 simultaneous equations, solving, 424–425 unique random integers, generating, 421–422 INTERCEPT function, 729 interest rates, 310–312 intermediate formulas, eliminating, 387–388 Internet features, 34 interpolation, 230, 444 Intersect function, 666–667 INTRATE function, 723 invalid data, identifying, 543–544 IPMT function, 308–309, 723 IRR function geometric growth rates, calculating, 329–330 multiple IRRs, 331–332 overview, 327–328 rate of return, calculating, 328–329 verification of, 330–331 irregular cash flows, 334–336 ISBLANK function, 724 ISERR function, 187, 724 ISERROR function, 187, 724 ISEVEN function, 724
40_475362-bindex.indd 777
777
ISLOGICAL function, 724 ISNA function, 187, 724 ISNONTEXT function, 186, 724 ISNUMBER function, 724 ISO.CEILING function, 285, 726 ISODD function, 724 ISREF function, 724 ISTEXT function, 121–122, 724 iteration settings, 420–421
J Jelen, Bill (Mr. Excel), 758 Jon Peltier’s Excel page (Web site), 758
K Kapor, Mitch (Lotus), 12 key names, keyboard conventions for, 3 keyboard conventions, 2–3 keyboard shortcuts, 25–26 KURT function, 729 Kusleika, Dick (Daily Dose of Excel), 757
L LARGE function, 106, 729 LASTINCOLUMN function, 697–698 LASTINROW function, 698 LCM function, 726 leading dots, displaying, 752 leading zeros, displaying, 745 leap year bug, 150–151 LEFT function, 132, 731 LEN function, 128, 731 less than (=), 45, 48, 644 less than (