MASTERING™ MICROSOFT® EXCEL 2002
Gini Courter Annette Marquis
SYBEX®
4002fm.qxd 7/18/01 2:43 PM Page i
MASTERING
MICROSOFT EXCEL 2002
4002fm.qxd 7/18/01 2:43 PM Page ii
This page intentionally left blank
4002fm.qxd 7/18/01 2:43 PM Page iii
™
MASTERING
MICROSOFT EXCEL 2002
®
Gini Courter Annette Marquis
San Francisco • Paris • Düsseldorf • Soest • London
4002fm.qxd 7/18/01 2:43 PM Page iv
Associate Publisher: Cheryl Applewood Acquisitions and Developmental Editor: Bonnie Bills Editor: Brianne Hope Agatep Production Editor: Dennis Fitzgerald Technical Editor: Karla Browning Book Designers: Patrick Dintino, Catalin Dulfu, Franz Baumhackl Electronic Publishing Specialist: Robin Kibby Proofreaders: Laurie O’Connell, Suzanne Stein Indexer: Nancy Guenther Cover Designer: Design Site Cover Illustrator: Jack D. Myers Copyright © 2001 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. No part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission of the publisher. Some material adapted from Mastering Microsoft Office XP Premium Edition by Gini Courter and Annette Marquis with Karla Browning © 2001, SYBEX, Inc., ISBN 0-7821-4000-9. Library of Congress Card Number: 2001092670 ISBN: 0-7821-4002-5 SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc. in the United States and/or other countries. Mastering is a trademark of SYBEX Inc. Screen reproductions produced with FullShot 99. FullShot 99 © 1991–1999 Inbit Incorporated. All rights reserved. FullShot is a trademark of Inbit Incorporated. Screen reproductions produced with Collage Complete. Collage Complete is a trademark of Inner Media Inc. Internet screen shot(s) using Microsoft Internet Explorer 5 reprinted by permission from Microsoft Corporation. TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer.
The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever possible. Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s). The author and the publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or indirectly from this book. Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1
4002fm.qxd 7/18/01 2:43 PM Page v
To those who use Excel to make numbers and other data understandable and meaningful. This book is for you.
This page intentionally left blank
4002fm.qxd 7/18/01 2:43 PM Page vii
ACKNOWLEDGMENTS
C
ollaboration is the new buzzword of the 21st century, and a book like this is the absolute model of collaboration. From the authors to the editorial staff, the production team, and all the people who package the book, store it, ship it, and sell it. Each project has its challenges and its opportunities, and we can never say enough about how Sybex works to keep the crises at a minimum and, despite everything, still manages to get the book out on time. The staff is always good spirited, enthusiastic, and diligent. We especially want to thank Bonnie Bills, our Acquisitions and Developmental Editor. Bonnie was patient, understanding, and persistent in the early stages of the project. Bonnie is always a pleasure to work with. This was one of our first projects with production editor Dennis Fitzgerald, and we hope it’s not our last. Dennis knew when to push, when to back off, when to get anxious, and when to feel relieved. He handled the project with care and caring, and made it all move along through even the rough spots. Thanks, Dennis. We also would like to thank our editor, Brianne Agatep, for her great suggestions and attention to detail. Without that careful attention, a book like this would be worthless. Brianne made the book more readable and more accurate. Special thanks to our tech editor, Karla Browning, a wonderful Excel trainer, for working the book through and offering technical suggestions to improve it. This is one of many books where we’ve worked with Carl Montgomery to write the cover copy in such a way that it might perk readers’ interest. Without his words, the book might languish on the shelves and we would all be a little poorer. Thanks, Carl, for helping this book and all the others find their way onto people’s desktops and book shelves. We appreciate it. Although we never interact with them directly, the book wouldn’t exist without the hard work of the production team. Thanks to Robin Kibby, the Electronic Publishing Specialist, who took our manuscript and transformed it into the book you hold now. We’d also like to thank the proofreaders, Laurie O’Connell and Suzanne Stein. Many people’s first look inside a book is at the index, and we had the fortune to have Nancy Guenther create the index for this book. We’d also like to thank Jeff Gammon, who worked on the Mastering Microsoft Excel 2002 page of the Sybex website.
4002fm.qxd 7/18/01 2:43 PM Page viii
CONTENTS AT A GLANCE Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi
PART I • PUTTING EXCEL 2002 TO WORK FOR YOU
1
1
Working in Excel 2002
2
Creating Excel Worksheets
41
3
Formatting Text and Worksheets
87
4
Using Names and External References
PART II • USING EXCEL’S FUNCTIONS
3
119
145
5
Calculating with Functions
147
6
Manipulating Text and Dates
169
7
Using Decision Making Functions
197
8
Using Financial Functions
217
PART III • USING CHARTS AND GRAPHICS 9
Creating Easy-to-Understand Charts
239 241
10 Advanced Charting in Excel 2002
263
11 Using Drawing and Graphics Tools
295
PART IV • MANAGING DATA WITH EXCEL 2002
337
12 Using an Excel Database
339
13 Using Excel 2002 to Present Information
387
14 Creating Workbooks for Other Users
427
15 Creating Forms in Excel 2002
449
PART V • OUT OF THE BOX WITH EXCEL 2002
473
16 Using Excel with Other Databases
475
17 Importing and Exporting with Excel 2002
523
18 Using Excel 2002 with the Web
551
4002fm.qxd 7/18/01 2:43 PM Page ix
Contents at a Glance
PART VI • ANALYSIS AND COLLABORATION WITH EXCEL 2002
581
19 Solving Business Problems Using the Analysis Tools
583
20 Using Excel’s Workgroup Tools
611
PART VII • AUTOMATING EXCEL 2002 WITH MACROS AND VBA
641
21 Automating Excel with Macros
643
22 Using Visual Basic with Excel
669
23 Do-It-Yourself Functions
695
24 Creating an Excel Application
715
PART VIII • APPENDICES
765
A
Customizing Excel 2002
766
B
VBA Quick Reference
791
C
Using MapPoint 2002 with Excel 2002
851
D
Creating Simple Smart Tags for Excel 2002
859
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .868
ix
4002fm.qxd 7/18/01 2:43 PM Page x
CONTENTS Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi
PART I • PUTTING EXCEL 2002 TO WORK FOR YOU 1
Working in Excel 2002
1 3
What’s New in Excel 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Launching Excel 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 New Features in the Excel Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 Using Task Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 Personalized Menus and Toolbars Respond to the Way You Work . . . . . . . . . . . . . . . . .14 Using the Open and Save As Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16 Repairing Damaged Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20 Interacting with Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21 More Help Completing Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22 Paste Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23 Reversing or Disabling AutoCorrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25 Collaboration with Excel 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26 Moving Beyond the Standard Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27 Speech Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27 Handwriting Recognition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35 Multilanguage Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38 Minimizing the Impact of Crashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38 Recovering From an Application Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38 Saving When You Crash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39 Setting Timed Recovery Save Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39 Making Use of Office Safe Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39 Other Recovery Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40 Closing Workbooks and Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40
2
Creating Excel Worksheets
41
Entering and Editing Cell Entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42 The Excel Application Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42 Worksheet Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44 Moving the Cell Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45 Entering Text and Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .46 Selecting Multiple Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49 Using Find and Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50
4002fm.qxd 7/18/01 2:43 PM Page xi
xi
Contents
Working with Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52 Creating Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53 Filling Formulas, Numbers, and Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59 Using the AutoFill Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60 Formatting Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62 Using the Formatting Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63 Using the Format Cells Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64 Previewing and Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73 Printing Your Worksheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73 Using Print Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74 Adjusting Margins in Print Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75 Changing Page Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76 Setting Print Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84
3
Formatting Text and Worksheets
87
Formatting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88 Changing Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88 Aligning Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89 Applying Borders and Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94 Using the Format Painter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97 Applying AutoFormats and Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98 Creating Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98 Applying Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100 Modifying and Deleting Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100 Copying Styles between Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100 Adjusting Worksheet Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Changing the Zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Adjusting Column Width and Row Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Changing Row Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 Inserting and Deleting Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 Freezing, Splitting, and Hiding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104 Hiding Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .105 Inserting and Deleting Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106 Moving and Copying Cell Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106 Using Paste Special . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110 Correcting Worksheet Spelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113 Checking Spelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113 Using AutoCorrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .116
4
Using Names and External References
119
Working with Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120 Selecting Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121 Entering Common Data in Multiple Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121 Copying and Moving Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122 Inserting and Deleting Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123 Naming Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124 Naming a Range Using the Name Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125
4002fm.qxd 7/18/01 2:43 PM Page xii
xii
Contents
Using the Define Name Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126 Creating Names from a Row or Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127 Using Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128 Stretching Names to the Max . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129 Linking to Other Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133 Linking with Paste Link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135 Working with Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135 Linking with Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137 Creating Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Editing Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142 Enabling and Using Smart Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142
PART II • USING EXCEL’S FUNCTIONS 5
Calculating with Functions
145 147
Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .148 Entering Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150 Relative and Absolute Cell References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153 Using Everyday Statistical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156 Finding and Fixing Formula Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158 Resolving Logical Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Working with Error Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Using the Formula Auditing Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161 Resolving Circular References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .166 Automatic and Manual Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .167
6
Manipulating Text and Dates
169
Working with Text in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170 Removing Spaces and Nonprinting Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170 Parsing Data with LEFT, RIGHT, and MID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 Using Functions to Change Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 Finding the Position of Text in a Cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 Putting Text Strings Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178 Converting Text to Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179 Working with Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180 Date/Time Forms That Excel Recognizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181 Basic Math with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .183 Using Date and Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186
7
Using Decision Making Functions
197
Using IF Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .198 Using IF to Take Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .198 Using AND and OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .202 Using the Summary IF Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .202 Using Excel’s Lookup Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .204 Using VLOOKUP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .206
4002fm.qxd 7/18/01 2:43 PM Page xiii
Contents
Using HLOOKUP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207 Using LOOKUP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208 Using Match and Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .209 Using the Lookup Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .210 Trapping Errors with Logical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .214
8
Using Financial Functions
217
Working with Present and Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .218 Calculating a Loan Payment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .219 Calculating the Loan Term . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .221 Calculating the Interest Rate for a Loan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .222 Calculating Loan Principal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .222 Creating an Amortization Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .222 Calculating Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227 Using the Depreciation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .232 Rounding Numbers in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .234 Using the QUOTIENT and MOD Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .235 Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238
PART III • USING CHARTS AND GRAPHICS 9
Creating Easy-to-Understand Charts
239 241
A Quick Overview of Chart Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .242 Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243 Series Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243 Creating a Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .246 Selecting Data for the Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247 Using the Chart Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .248 Editing and Formatting Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .252 Moving, Sizing, and Printing Chart Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .252 Adding a Data Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .253 Deleting a Data Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254 Formatting Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254
10 Advanced Charting in Excel 2002
263
Creating Specialized Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .264 Creating an Area Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265 Creating a Surface Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .270 Creating a Donut Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .270 Creating a Scatter Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .272 Creating a Bubble Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .273 Creating a Radar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .275 Creating a Stock Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .277 Creating a Combination Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .279 Creating and Saving Chart Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .282 Setting the Default Chart Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .282
xiii
4002fm.qxd 7/18/01 2:43 PM Page xiv
xiv
Contents
Additional Charting Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283 Setting Chart Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .285 Customizing Fill and Line Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .288 Applying Custom Fills . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .289 Using Pictures of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .291 Storing Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .293
11 Using Drawing and Graphics Tools
295
Using Microsoft Draw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296 Inserting AutoShapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .297 Creating Curve, Freeform, and Scribble Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .298 Creating Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .299 Adding Line Art Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .300 Designing WordArt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .303 Formatting Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .305 Constructing Diagrams and Organizational Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . .312 Accessing Clips from Microsoft Clip Organizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .316 Searching for the Clip You Want . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .317 Finding Similar Clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .319 Exploring Your Clip Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .319 Creating a New Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .322 Assigning Keywords to Clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .323 Improving Your Clip Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .326 Inserting Pictures into Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .330 Resizing Clip Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .330 Modifying Pictures with the Picture Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .331 Gaining Control of Size and Other Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .332 Inserting Pictures from Other Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .335 Inserting Scanned Graphics and Digital Photos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .335
PART IV • MANAGING DATA WITH EXCEL 2002 12 Using an Excel Database
337 339
Basic Database Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .340 Choosing a Database Application: Excel or Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . .343 Sorting an Excel Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .345 Multilevel Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .346 Filtering a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349 Applying an AutoFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349 Using Advanced Filters to Extract a Subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .354 Creating Subtotals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .360 How Excel Creates Subtotals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .362 Using Data Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .365 Adding and Deleting Records in a Data Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .366 Searching for Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .366 Using Dfunctions to Summarize a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .367
4002fm.qxd 7/18/01 2:43 PM Page xv
Contents
Applying Conditional Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .370 Setting the First Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .371 Using Cell References in Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373 Using Formulas as Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .374 Using the Conditional Sum Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .379 Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .382 Using the Formula Auditing Toolbar to Check Validation . . . . . . . . . . . . . . . . . . . . . . . .385
13 Using Excel 2002 to Present Information
387
Grouping and Outlining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .388 Creating and Using an Auto Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391 Reviewing Worksheet Structure for Outlining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .392 Manually Outlining a Worksheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .393 Formatting an Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .395 Creating Pivot Tables and Pivot Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .397 Creating a Table with the Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .399 Changing PivotTable Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .402 Changing the Summary and Format for Data Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . .408 Setting Pivot Table Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .409 Applying a Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .411 Using External Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .412 Creating a Pivot Table from Consolidation Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . .413 Keeping the Pivot Table Updated . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .417 Using Custom Calculations in Pivot Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .418 Drilling Down in a Pivot Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .423 Creating Separate Pivot Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .424 Creating Pivot Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .424
14 Creating Workbooks for Other Users
427
Using and Creating Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .428 Working with Existing Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .428 Creating Templates for Personal Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .430 Creating Templates for Other Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .433 Protecting Workbooks, Worksheets, and Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .435 Protecting Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .435 Protecting Worksheets and Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .436 Creating Worksheets for Nonusers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .442 Taking the Spreadsheet Out of Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .443
15 Creating Forms in Excel 2002
449
Creating Printable Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .450 Setting Up the Printed Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .452 Creating a Tool Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .452 Understanding ActiveX and Form Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .453 ActiveX Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .454 Form Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .456
xv
4002fm.qxd 7/18/01 2:43 PM Page xvi
xvi
Contents
Adding Form Controls to Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .458 Using Command Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .459 Using List Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .464 Using Scroll Bars and Spinners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .469 Using Group Boxes, Option Buttons, and Check Boxes . . . . . . . . . . . . . . . . . . . . . . . . .471
PART V • OUT OF THE BOX WITH EXCEL 2002
473
16 Using Excel with Other Databases
475
Using the Template Wizard with Data Tracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .477 Working with Access and Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483 Copying Data from Excel to Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .484 Converting an Excel Worksheet to an Access Database . . . . . . . . . . . . . . . . . . . . . . . . .486 Using Access Forms and Reports in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .489 Importing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .491 Understanding Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .492 Using an Existing Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .494 Creating a New Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .496 Retrieving External Data with Microsoft Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498 Working with Query Results in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .508 3D Pivot Analysis with OLAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .512 Understanding OLAP Cubes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .513 Opening an Existing OLAP Cube . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .514 Using an Existing OLAP Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .514 Selecting an Existing OLAP Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .514 Creating a New OLAP Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .514 Creating a New OLAP Cube . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .516 Working with a Cube in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .520
17 Importing and Exporting with Excel 2002
523
Converting, Linking, and Embedding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .524 Converting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .525 Embedding and Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .529 Linking and Embedding in Excel Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .531 Working with Embedded and Linked Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .532 Inserting and Linking Entire Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .532 Creating New Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .535 Using Excel in Office XP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .536 Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .537 PowerPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .539 Outlook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .541 Importing Data from Other Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .545 Parsing Imported Data with the Text Import Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . .547 Using Refreshable Text Importing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .549
4002fm.qxd 7/18/01 2:43 PM Page xvii
Contents
18 Using Excel 2002 with the Web
551
Working with Web Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .552 Creating a Web Folder Shortcut in Windows 2000/Me . . . . . . . . . . . . . . . . . . . . . . . . .552 Creating a Web Folder Shortcut in Windows 98/NT 4.0 . . . . . . . . . . . . . . . . . . . . . . . . .554 Saving Files in Web Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .554 Publishing Excel Documents on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .555 Saving a Static Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .555 Publishing an Interactive Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .557 Appending to an Existing Web Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .567 Automatically Republishing Web Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .567 The L’s: Excel, HTML, XML, and MHTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .569 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .569 MHTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .572 Creating Web Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .573 Starting in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .574 Using the Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .575 Bringing It Full Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .578
PART VI • ANALYSIS AND COLLABORATION WITH EXCEL 2002 19 Solving Business Problems Using the Analysis Tools
581 583
Creating Data Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .584 Creating a Data Table with Two Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .586 Forecasting and Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .587 Making Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .588 Building an Accurate Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .588 Using Goal Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .592 Using Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .594 Using Solver with Multiple Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .598 Saving Solver Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .602 Using Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .603 Merging Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .604 Summarizing Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .606 Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .608 Creating Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .609
20 Using Excel’s Workgroup Tools
611
Working with Workgroups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .612 E-mailing Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .612 Routing Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .613 Sharing Workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .617 Using Send for Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .623 Saving a Workbook to an Exchange Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .626 Using SharePoint Team Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .627 Creating a Team Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .629 Making New Workbooks Available . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .630
xvii
4002fm.qxd 7/19/01 11:21 AM Page xviii
xviii
Contents
Importing a List from a Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .634 Learning More about SharePoint Team Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .637 Holding Virtual Meetings to Share Excel Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .638
PART VII • AUTOMATING EXCEL 2002 WITH MACROS AND VBA 21 Automating Excel with Macros
641 643
Creating Macros in Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .644 Storing a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .646 Running Macros from the Macros Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .647 Deleting Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .648 Opening a File That Contains Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .649 Working in the Visual Basic IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .651 Making Macros Easy to Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .656 Design Decisions for the User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .656 Customizing the Command Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .657 Running a Macro from a Form Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .667
22 Using Visual Basic with Excel
669
What Is Visual Basic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .671 Making Use of Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .675 The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .676 Hello World! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .678 Creating the Application Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .680 Changing Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .686 Writing the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .688 Proof of Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .691 To Err Is Human . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .691 Compiling and Distributing Your Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .692 Going Further with Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .692
23 Do-It-Yourself Functions
695
Creating User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .696 The Years of Service User-Defined Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .697 The Count Weekends User-Defined Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .700 Using Custom Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .702 Calling User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .702 User-Defined Functions on a Worksheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .703 Creating an Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .705 Testing and Debugging In-Depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .706 Using the Debugging Toolbar and Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .707 Windows API Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .714
4002fm.qxd 7/18/01 2:43 PM Page xix
Contents
24 Creating an Excel Application
715
Getting the Help You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .716 Introducing the Excel Visual Basic Help File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .716 Integrating Excel with the Other Office Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .724 Adding Object Library References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .725 Create an Application Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .726 Referencing Excel from another Office Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . .727 An Example: Retirement Countdown Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .729 Creating the Retirement Countdown Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .731 Creating the Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .731 Adding Controls to the Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .733 Creating the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .737 Coding the Cancel Command Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .738 Coding the OK Command Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .739 Calculate Retirement Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .749 Using Custom Command Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .762 Life after Retirement Countdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .763
PART VIII • APPENDICES A
Customizing Excel 2002
765 766
Customizing Excel Options in the Options Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . .767 View Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .767 Edit Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .769 General Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .771 Transition Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .774 Custom Lists Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .774 International Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .775 Save Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .775 Error Checking Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .776 Spelling Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .778 Security Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .781 Recovering Files Manually in Excel 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .785 Additional Methods for Recovering Data from Damaged Workbooks . . . . . . . . . . . . .786
B
VBA Quick Reference
791
Using Comments, Blank Lines, and Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .792 Understanding VBA Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .793 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .794 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .794 Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .794 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .795 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .795 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .795 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .796 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .804 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .805
xix
4002fm.qxd 7/18/01 2:43 PM Page xx
xx
Contents
VBA Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .806 VBA Programming Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .808 Sequential Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .808 Looping Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .808 While… Wend Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .813 Nesting Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .815 Using Conditional Branching Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .815 The Excel Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .819 Using the Application Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .821 Using the Workbook Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .821 Using the Worksheets and Sheets Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .822 Working with Excel Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .828 Activate and Deactivate Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .834 AddinInstall and AddinUninstall Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .835 Calculate Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .836 Change Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .837 BeforeClose Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .838 DragOver and DragPlot Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .838 BeforeDoubleClick and BeforeRightClick Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .839 FollowHyperlink Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .841 MouseDown, MouseMove, and MouseUp Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .842 NewSheet and NewWorkbook Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .842 Open Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .843 PivotTable Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .843 AfterRefresh and BeforeRefresh Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .845 BeforePrint Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .845 BeforeSave Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .846 SelectionChange and SeriesChange Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .847 Window Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .848
C
Using MapPoint 2002 with Excel 2002
851
MapPoint 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .853 Importing and Mapping Excel Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .854 Exporting Data to Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .856 Integration with Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .857
D
Creating Simple Smart Tags for Excel 2002
859
Tools for Creating Smart Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .860 The Smart Tag Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .861 Creating the List File in Notepad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .862 Namespace, Name, and Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .863 Creating the File Using SmartTagMOSTLGenerator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .866
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .868
4002fm.qxd 7/19/01 11:20 AM Page xxi
INTRODUCTION e are in the middle of an information revolution. Each of us has immediate access to more data than at any time in human history. Three examples illustrate this:
w Web Data
The growth of Internet- and intranet-based data is exponential: sites that only two years ago had 100 pages now have thousands. Organizations that published static pages of data, periodically updated, are moving their data to active server pages or web parts.
Business to Business (B2B) Data As Extensible Markup Language (XML) matures, more organizations will exchange XML data, replacing paper or e-mailed invoices, orders, and bid information. XML data definitions (DTDs or schemas) have been published for over a dozen major industries, and scores more are working on common definitions to facilitate data exchange. Organizational Data
More powerful servers, server software that can work seamlessly across multiple servers, and better document indexing software have fueled two trends: a movement away from desktop databases back to large corporate data stores, and collections of organizational data such as geographic and graphic data that were previously too large or too dense to aggregate.
Data has grown exponentially, and so have the demands to use data: to analyze, calculate, report, and publish your results. Using even a fraction of the mountain of data in today’s work world requires great tools—tools that support multiple methods of reporting, that integrate well with other desktop applications, and that are relatively easy to learn and intuitive to use. If you are looking for a single tool that can really help you use business data, Microsoft Excel 2002 is the tool you’ve been looking for. Excel 2000 and Excel 2002 both were major upgrades of Microsoft’s time-tested spreadsheet software. With Excel 2002, you can pull live data from a staggering variety of sources, add calculations, create forecasts and other analyses, export to XML or HTML as well as more traditional data formats, and publish your results on screen, on paper, or on the Web. And you don’t need to do this work alone. Excel 2002 is a
4002fm.qxd 7/19/01 11:20 AM Page xxii
xxii
Introduction
collaboration tool with built-in support for workbook review, routing, and online collaboration with NetMeeting and SharePoint Team Services. Microsoft has revamped the user interface in myriad ways, some large, some subtle, to make this powerful tool even easier to use.
What’s in This Book Mastering Microsoft Excel 2002 provides you with the tools and information you need to use Excel effectively. We assume that you have some familiarity with Microsoft Office products, but you may or may not have used Excel previously. If you’re familiar with Excel 2000, you will probably be especially interested in those sections of this book marked with a New icon. The New icon identifies features that have been added or significantly changed in this version of Excel.
NOTE
If you’re new to the Office applications, this isn’t the book for you. For new users, we recommend Microsoft® Excel 2002 Simply Visual™ from Sybex.
Second in use only to Microsoft Word, Excel has millions of users. Unlike Word, Excel is not easy to learn by simply trying things until something works: with Excel, there are too many things to try. We train thousands of Excel users every year. Many are experienced Excel users, but not efficient Excel users. There’s an easy explanation. Many users learn Excel through trial and error while trying to meet a deadline: the end of a project, a budget deadline, or the day that a response to an RFP is due. Happy to find any solution that works, they don’t have time to look for a more efficient solution, a better method that would make the job easier and faster. And this solution is the solution they’ll use the next time they need to complete the same task. This book is designed to help you use Excel efficiently and effectively, whether you’re crunching numbers, creating forecasts, or analyzing a database. We’ll show you how to use robust functions that replace complex formulas or manual operations, and high-end tools that replace multi-step processes in business worksheets. Mastering Microsoft Excel 2002 begins with Excel’s most common use: as a spreadsheet. After examining how to create, format, and calculate in worksheets, we discuss Excel’s extended features—charting, pivot tables, reporting, web publishing, and automation—and explore ways to apply Excel for analysis and reporting in a business environment. Part I, “Putting Excel 2002 to Work for You,” takes you on a quick tour of the features and functionality of Excel 2002. If you’re new to Excel or are upgrading to Excel 2002 directly from Excel 97, this section will show you the whole picture
4002fm.qxd 7/18/01 2:43 PM Page xxiii
Introduction
so you can create worksheets quickly and easily in Excel 2002. If you’ve worked with Excel 2000, scan Part I for some of the exciting new and enhanced features such as speech and handwriting recognition and useful, different ways to use legacy features like named ranges. Part II, “Using Excel’s Functions,” focuses on creating formulas with functions. Chapter 5 is functions 101: using functions and fixing formula problems. Chapters 6, 7, and 8 cover the text and date functions, logical functions, and financial functions, with a special emphasis on using the logical functions to trap and handle errors in other formulas. The functions don’t end with the close of Part II—other functions and formulas are introduced throughout the book. In Part III, “Using Charts and Graphics,” you’ll see how to present Excel numeric data visually. In Chapter 9, you’ll learn how to create and format basic charts: the columns, bars, and pies that are the bread and butter of the charting world. In Chapter 10, you’ll enhance your charting toolkit with more specialized charts including donut charts, radar charts, surface charts, bubble charts, and area charts. Chapter 11 focuses on the other illustration tools, including the drawing tools and clip art. Part IV, “Managing Data with Excel 2002,” is dedicated to Excel’s powerful database features. Chapter 12 starts with the fundamentals including database structure, importing, sorting, filtering, and conditional formatting. Chapter 13 thoroughly explores one of Excel’s most powerful and least understood features: pivot tables. In Chapters 14 and 15, we examine an important aspect of data management: making Excel data accessible with templates and streamlining data entry with forms and form controls. In Part V, “Out of the Box with Excel 2002,” you’ll see how to use Excel with nonnative data, other applications, and the Web. Chapter 16 focuses on an application closely related to Excel, Microsoft Access, and the Excel add-ins that link Access reports and forms to Excel databases, as well as importing data from other data sources and databases with Excel 2002’s new data import features. Chapter 17 is all about integration, using Excel 2002 as a member of the Office XP suite. Whether you’re interested in analyzing web data in Excel or publishing Excel data on the Web, you’ll find the tools and techniques you need in Chapter 18. In Part VI, “Analysis and Collaboration with Excel 2002,” you’ll find out how to use Excel’s business forecasting tools, often called the What If tools. Chapter 19 covers a wide range of features from data tables to Goal Seek and Solver, scenarios to reports and report management. And in Chapter 20, you’ll learn how to collaborate with Excel’s workgroup tools, including document routing, sharing workbooks, and tracking changes as well as two new Excel 2002 features, Send for Review and SharePoint Team Services.
xxiii
4002fm.qxd 7/18/01 2:43 PM Page xxiv
xxiv
Introduction
Although building custom applications is not for everybody, if you want to create applications using an Office application as the backbone, Excel is the best application to start with. Excel is included in more custom applications than any other Office program. Excel’s macro recording tools provide a good entry point for Office automation. In Part VII, “Automating Excel 2002 with Macros and VBA,” you’ll learn the basics of Excel automation and delve into the structure of Visual Basic for Applications, the programming language of Excel 2002. Chapter 23 walks you through creating custom functions. User-defined functions are an easy way to build your organization’s business rules into Excel worksheets. Create the sample applications in Chapter 24, and you’ll have hands-on practice automating Excel from another Office application, creating an Excel-based application that creates charts and Word documents. If you’d like to learn about programming or if you are a programmer who wants to develop Excel applications, you’ll find something of value in this part. The four appendices offer additional references to help make you an expert Excel user. Appendix A covers Excel’s customization options so you can tweak Excel to work the way you do. Appendix B is a quick reference for the Visual Basic for Applications chapters, including the Excel Object Model. This version of Microsoft Excel does not include the Data Map feature that was included with Excel 97 and 2000, but you won’t miss this feature much, because Excel 2002 uses the mapping application MapPoint 2002, and Appendix C gives you a quick introduction to it. Appendix D is a guide to creating simple smart tags for use in Excel 2002.
Conventions Used in This Book Throughout the book, you’ll find practical suggestions for making Excel work for you. “Mastering the Opportunities” sidebars provide ideas about using Excel most effectively. “Mastering Troubleshooting” sidebars provide you with information about how to avoid problems with Excel and how to recover from problems you may be experiencing.
Mastering the Opportunities This type of sidebar expands on the information in the text by providing some real-life examples of how you can use Excel 2002 in your everyday work.
4002fm.qxd 7/18/01 2:43 PM Page xxv
Introduction
Mastering Troubleshooting This type of sidebar explains some possible pitfalls and provides tips or tricks you can use to get around them.
In addition to the sidebars, you’ll find Notes, Tips, Expert Tips, and Warnings scattered throughout the chapters.
NOTE
Notes provide explanations that will help you understand a particular topic
better.
TIP
Tips show you quick ways to stretch Excel just a little further, with suggestions for shortcuts and alternate methods.
EXPERT TIP
Expert Tips give higher-level examples and suggestions for those who like to try new things and add valuable tools to their toolkits.
WARNING
Warnings point out potential problems and ways of avoiding them.
All of these extra features are designed to take you a step beyond the typical user and make you an Excel master. Mastering Excel 2002 includes functions and (lots of) formulas. When a function is introduced, we’ll show you the syntax: the function name and the arguments (pieces of information you need to provide for the function to return a result). The function is in program font, and the arguments in italics.
xxv
4002fm.qxd 7/18/01 2:43 PM Page xxvi
xxvi
Introduction
The syntax of the IF function is =IF(logical test, result if true, result if false). When this function is used in an example, it is once again presented in program font, but there are no italics: =IF(OR(J5=”B”,J5=”A”),”Honor Roll”,””)
In the first example, the syntax of the function, logical test, result if true and result if false are placeholders—variables that represent and explain the choices you’ll make when you use the function. =IF and the parentheses are not italicized, because you type them in exactly as they appear in the syntax. In the second example, the function and arguments are entered exactly as printed, so nothing is italicized.
What You’ll Find on the Web www
Throughout the book you will see an icon that indicates that material (such as downloadable worksheets) or links can be found on the website for this book. From the Sybex website (www.sybex.com) type 4002 in the Search text box, then click the Go button. Click the link to Mastering Microsoft Excel 2002 to take you to the web page for this book.
How to Use This Book to Master Excel 2002 Although we would like you to start with page one and devour each word as you work your way through to Appendix D, we recognize there are some topics that may not apply to your business environment or work setting. As a result, we’ve come to accept the fact that there is no formula that all users should follow to make the most of Mastering Microsoft Excel 2002. New users should cover the first nine chapters pretty thoroughly in order to grasp the essential Excel concepts. We have ordered the chapters in the sequence we think will be easiest for you to learn, but if they are not in the order you need, feel free to skip around. When there is knowledge that is essential to the current topic, we have included cross-references to where that topic is covered. The book is written in narrative form to give you more information about each topic rather than just showing you what to do to accomplish a particular task. However, we’ve included numbered steps whenever it seemed appropriate, so you can follow along with the specific task at hand.
4002fm.qxd 7/18/01 2:43 PM Page xxvii
Introduction
If you are an experienced Excel user, you’ll find a number of new features in Excel 2002 and enough design changes to be disconcerting. This book is well indexed, and you should be able to find information about any topic you want to explore in more detail. But be sure to read Chapter 1 for a look at some of the best new features in Excel 2002. If you are a power user, you will find a lot of information about using Visual Basic for Applications to build custom Excel applications in Part VII and information that will get you started creating smart tags in Appendix D. Whatever approach you take to mastering Excel, this book will answer most of your questions and make you feel comfortable with this powerful application. We’d love to hear your comments or answer your specific questions. Send us a message. Words of praise and stories of success are always welcome! —Gini Courter and Annette Marquis
[email protected] xxvii
4002fm.qxd 7/18/01 2:43 PM Page xxviii
This page intentionally left blank
4002c01.qxd 7/17/01 1:37 PM Page 1
PA R T
I
PUTTING EXCEL 2002 TO WORK FOR YOU ◗
New features in Excel 2002
◗
Collaborating with Excel 2002
◗
Entering data and working with numbers
◗
Creating custom formats
◗
Formatting text and worksheets
◗
Hiding rows and columns
◗
Creating and naming ranges
◗
Linking workbooks
◗
Using smart tags
4002c01.qxd 7/17/01 1:37 PM Page 2
This page intentionally left blank
4002c01.qxd 7/17/01 1:37 PM Page 3
CHAPTER
WORKING IN EXCEL 2002 F E ATU R I NG
New features in Excel 2002
Exploring the user interface
Working with toolbars
Using task panes
Working with the Office Clipboard
Getting help
Using new input methods
Exploring language support
Recovering documents
1
4002c01.qxd 7/17/01 1:37 PM Page 4
o matter what your experience level is with Excel, Excel 2002 has much to offer you that’s new and improved. If you’re an Office user who hasn’t worked extensively with Excel, you’re in for a real treat. In the opinion of many users, Excel is one of the best designed business applications ever written—powerful and intuitive with plenty of depth and breadth. If you’re an experienced Excel user moving to Excel 2002 from a previous version, you’ll find much that’s new. In this chapter, we focus on the new features in Excel 2002 and what you need to know to begin working in the new version. We assume you’ve used Excel or other applications in Office 97 or Office 2000, so we’ll only briefly discuss features that function as they did in previous versions of Office.
n
What’s New in Excel 2002 In Excel 2000, the last update of Excel, many of the new features were obvious only to developers and advanced users. But this latest version of Excel has been drastically altered at many levels. Features introduced in Excel 95 and 97 have been revamped to include functionality requested by users. Also new in Excel are some interface enhancements that appear throughout the Office XP suite, including the new task pane, document recovery, speech and handwriting recognition, and smart tags.
New Feature
Where to Find Out about It
New User-Interface Features
Support for voice and handwritten input
Chapter 1
Context-based task panes that display the Office clipboard, New/Open options, and other features on demand
Chapter 1
Smart tags that link to external data in other Office applications and the Internet
Chapters 4 and 17 and Appendix D
Option buttons that automatically appear when you insert, paste, or fill data
Chapter 3
A border drawing tool
Chapter 3
Colored sheet tabs, and other worksheet formatting tools
Chapter 2
Find and replace options that allow you to find or replace across all worksheets in a workbook
Chapter 2
Expanded AutoSum to include Average, Count, Min, and Max
Chapter 2
4002c01.qxd 7/17/01 1:37 PM Page 5
What’s New in Excel 2002
5
PART
Where to Find Out about It
New User-Interface Features
An improved Formula Auditing toolbar with a watch window (like in Visual Basic) used to track values and formulas in any open workbook and formula evaluator that displays the results for each portion of a nested formula
Chapter 5
Screen tips describing function syntax that appear when you type a formula
Chapter 2
New Graphics Features
Graphics in headers and footers
Chapter 2
A gallery of conceptual diagrams including Venn diagrams, organization charts, and target diagrams has been added to the Drawing toolbar
Chapter 12
The improved GDI+ graphics system, resulting in better transparency, blending, smoothing, and sharpness
Chapter 11
New Data and Query Features
The ability to e-mail a selection rather than an entire workbook
Chapter 20
A new visual interface for selecting HTML tables to import, copy, or link to Excel
Chapter 18
Support for query to Extensible Markup Language (XML) files, the data communication format for the .NET platform
Chapter 16
A Data Connection Wizard that streamlines the process of acquiring external data
Chapter 16
Automatically republishing previously published workbooks during the save operation so the latest version of a workbook appears on your website
Chapter 18
Tools to create Web Parts to summarize data for digital dashboards
Chapter 18
Workbook storage in Microsoft Exchange Server folders
Chapter 20
New Recovery Features
Document recovery that saves workbooks when there’s an application error and displays them in a task pane the next time you launch Excel
Chapter 1
I Putting Excel 2002 to Work for You
New Feature
4002c01.qxd 7/17/01 1:37 PM Page 6
6
CHAPTER 1 • Working with Excel 2002
New Feature
Where to Find Out about It
New Recovery Features
Safe Mode startup, used to continue work in Excel if the application detects problems on launch
Chapter 1
Application recovery, which attempts to save your Excel document when Excel is not responding
Chapter 1
A crash reporting tool that can be configured to send information either to Microsoft or to your organization’s help desk when Excel crashes1
Chapter 1
New Security and Workgroup Features
Support for digital signatures so you can sign your Excel workbooks
Chapter 24
Beefed-up password protection allows you to give permission to specific users to edit worksheet ranges
Chapter 14
Installation without VBA support, which will enhance security because eliminating VBA eliminates macro viruses2
Chapter 21
Support for SharePoint Team Services, the new web collaboration service included with Office XP
Chapter 20
New Send for Review by e-mail launches the Reviewing toolbar when reviewer opens your workbook
Chapter 20
1. In our opinion, Excel was the most stable of the Office XP applications, even in Beta 1. A beta is a beta, so beta testers know not to rely on the software that they’re testing. In Beta 1, PowerPoint was prone to choke when you imported or saved. Word crashed so often we had the text of its recovery task pane memorized. Excel was so reliable we had to close Excel from the Windows 2000 Task Manager to see how its recovery features worked! 2. It also means some of us will have new reasons to argue with our network administrators.
You’ll see this icon when a feature is new or has been changed, either drastically or in some subtle way, so that it behaves differently than it did in Excel 2000.
4002c01.qxd 7/17/01 1:37 PM Page 7
Launching Excel 2002 If the Office shortcut bar is displayed, simply click the Excel button on the shortcut bar to launch Microsoft Excel and open a new workbook, or choose New Office Document and select Blank Workbook from the New window. To open an existing workbook from the shortcut bar, click the Open Office Document button, then browse to locate the workbook. If you’re not using the shortcut bar, choose Start Programs Microsoft Excel 2002 from the Windows menu to launch Excel. Or locate the existing Excel workbook you’d like to open, then double-click to launch Excel and open the workbook.
New Features in the Excel Interface The first thing you’ll notice when you fire up Excel 2002 is a window called the task pane on the right side of the application window. Different task panes are displayed in this area; the panes support a range of features from opening documents to choosing clip art to accessing Excel Help. The task panes in Excel 2002 take up a large chunk of screen and seem a bit intrusive at first. But stick with them and you’ll discover just how much functionality the Excel 2002 team has been able to pack into the panes. In this section, we’ll show you how to use task panes effectively.
Using Task Panes You can display and hide the task pane from the View menu; the task pane will also display and hide automatically depending on your activity. The New Workbook task pane, shown in Figure 1.1, for example, appears whenever you start Excel. If you close the task pane, it reappears whenever you choose File New from the menu. To display the task pane when it is hidden, choose View Task Pane. You can then select the task pane to display: New Workbook, Clipboard, or Search, as shown in Figure 1.2. After you select a task pane from the list, you can return to previous task panes using the Back and Forward buttons at the top of the task pane. To close the task pane, click the Close button to the right of the task pane name.
7
PART
I Putting Excel 2002 to Work for You
New Features in the Excel Interface
4002c01.qxd 7/17/01 1:37 PM Page 8
8
CHAPTER 1 • Working with Excel 2002
FIGURE 1.1 Use the New Workbook task pane to open existing documents and create new ones.
FIGURE 1.2 Choose the task pane you want to use from the task pane menu.
4002c01.qxd 7/17/01 1:37 PM Page 9
New Workbook Task Pane The New Workbook task pane is immediately visible when you launch Excel. The task pane is divided into five sections: Open a Workbook Lists the most recently saved workbooks and has a Workbooks link that opens the Open dialog box. New
Allows you to open a blank workbook.
New From Existing Workbook Makes it easy to create a new workbook based on a previously saved workbook without running the risk of overwriting the saved workbook. New from Template Lists open templates, General templates, Templates on Network Places (websites) and templates available from Microsoft.com. Miscellaneous options Allow you to add a Network Place, access Excel Help, and disable the Show at Startup option that opens the New Workbook task pane when you launch Excel. As soon as you select a workbook to open, the New Workbook task pane closes automatically to leave more room for your workbook.
Working with the Office Clipboard Microsoft introduced the Office Clipboard in Office 2000, and it quickly became one of the most exciting new features for users who create documents that span the Office applications. With the Office 2000 Clipboard, you could cut or copy more than one thing and paste them individually or as a group. In Office XP, the Office Clipboard takes a giant leap forward in a number of significant ways: • The number of items you can collect on the Clipboard has increased from 12 to 24. • The Clipboard has been converted from a toolbar-based palette of icons to a task pane with larger previews of the individual items. • The Clipboard is nearly as handy as the system clock or volume control. While the Clipboard task pane is open in any Office application, an icon appears in the Windows system tray. Double-click the Clipboard icon, and the task pane opens so you can quickly and easily paste between applications—providing incredible support not only for copying and pasting, but for linking and embedding in Excel and with the other Office applications.
9
PART
I Putting Excel 2002 to Work for You
New Features in the Excel Interface
4002c01.qxd 7/17/01 1:37 PM Page 10
10
CHAPTER 1 • Working with Excel 2002
The Clipboard task pane, shown in Figure 1.3, activates automatically when you cut or copy more than one item. You can open it manually in one of three ways: • Select Clipboard from the open task pane menu. • Chose Edit Office Clipboard. • Hold the Ctrl key down and double-press (as you would double-click) the C key.
FIGURE 1.3 The Clipboard task pane opens when you cut or copy more than one item.
When the Office Clipboard is open, you can select and either paste or delete an individual item, or you can Paste All or Clear All of the items on the Clipboard.
Setting Office Clipboard Options The following four options control the Office Clipboard’s behavior. You can change the option settings by clicking the Options button at the bottom of the Clipboard task pane. Show Office Clipboard Automatically With this option set, the Office Clipboard task pane appears automatically after you cut or copy two items. Collect Without Showing Office Clipboard This option, turned off by default, allows you to collect items with the task pane closed. Show Office Clipboard Icon on Taskbar Windows system tray.
Displays the Office Clipboard icon in the
Show Status Near Taskbar When Copying Displays a screen tip above the Office Clipboard icon in the system tray to indicate that an item is being collected (copied) and how many items the clipboard currently is holding.
4002c01.qxd 7/17/01 1:37 PM Page 11
NOTE
The Office Clipboard is not limited to use within Excel and the other Office applications. As long as the clipboard is running in any Office application, you can copy items from other applications (such as Internet Explorer or a graphics application) to the Office Clipboard.
Searching in Excel Whether you’ve lost an important workbook or need to find every mention of a topic on your intranet, the new Basic Search and Advanced Search task panes could be just the ticket. In the Basic Search task pane, shown in Figure 1.4, enter text and search your local computer, your networks drives, and even in Outlook to find what you need.
FIGURE 1.4 Use the Basic Search task pane to search through all of your files for the documents you need.
Click the task pane selection menu and choose Search. To enter a search, follow these steps: 1. Enter text in the Search Text box. Office looks through the body of documents, document properties and keywords. Enter more words to narrow the search. Basic search finds all word forms (e.g., win, winning, and winner). 2. Select the Locations you would like to search from the Search In drop-down list. You can search Everywhere or limit your search to any combination of My Computer, My Network Places, and Outlook folders.
11
PART
I Putting Excel 2002 to Work for You
New Features in the Excel Interface
4002c01.qxd 7/17/01 1:37 PM Page 12
12
CHAPTER 1 • Working with Excel 2002
3. Select the type of results you would like from the Results Should Be drop-down list. You can choose different types of Microsoft Office files, Outlook items, and web pages. 4. Click the Search button. The results are returned in the Search Results task pane, shown in Figure 1.5.
FIGURE 1.5 The search results appear in the task pane
EXPERT TIP
When you use Office Search, you may find some surprising results. If you look closely at the results in Figure 1.5, you’ll see that two of the files it returned are image files. Microsoft Office Document Imaging, a new product included with Excel 2002, performs OCR (Optical Character Recognition) while it is generating TIFF image files. It then adds the text it recognizes to the Indexing Service, which Office also runs behinds the scenes, so that even image text can be identified through a search. You can access Microsoft Office Document Imaging directly by opening the Microsoft Office Tools menu on the Windows Programs menu.
When you want to start a new search or narrow the existing one, click the Modify button on the Search Results task pane to return to the Basic Search task pane.
Using Advanced Search
When you need to establish more exact conditions for a search, click the Advanced Search link on the Basic Search task pane. In the Advanced Search task pane, shown in Figure 1.6, you can choose from a long list of properties and set conditions for each one. For example, you can search for only documents that were modified after a certain date and contain a certain word.
4002c01.qxd 7/17/01 1:37 PM Page 13
New Features in the Excel Interface
FIGURE 1.6 Use the Advanced Search task pane to conduct a more precise search of your files.
13
PART
Putting Excel 2002 to Work for You
I
To use the Advanced Search tool, follow these steps: 1. Select a property of the files that you want to locate from the Property dropdown list (for example, Last Modified). 2. Select a condition that you want the property to meet from the Condition dropdown list (for example, On or Before). 3. Enter a value that you are looking for (for example, 6/1/01). 4. Click Add to save the search parameter. 5. Select the And or Or options to include another search parameter. 6. Repeat steps 1–4 until you have entered all the parameters for the search. 7. If you want to modify one of the search parameters, use the arrows to display the search parameter you want and click the Remove button. Make any changes to the Property, Condition, or Value and then click Add or click Remove to delete it. 8. Set Search In and Results Should Be search options. 9. Click Search.
Search for Clip Art The Microsoft Clip Organizer, formerly known as the Clip Art Gallery, has been totally revamped for Excel 2002. When you click the Insert Clip Art button on the Drawing toolbar, it opens the Insert Clip Art task pane and prompts you to add clips to the organizer if it’s your first time using the feature. In this task
4002c01.qxd 7/17/01 1:37 PM Page 14
14
CHAPTER 1 • Working with Excel 2002
pane, which is similar to the Basic Search task pane, you can search for clip art, photographs, movies, and sound files. To learn more about organizing and searching for clip art, refer to Chapter 11.
Personalized Menus and Toolbars Respond to the Way You Work In Microsoft Office 2000, Microsoft introduced the personalized menus and toolbars feature. Recognizing that most users only use a small percentage of menu and toolbar options, Microsoft redesigned them to bring the tools you use to the forefront. In personalized toolbars, the Standard and Formatting toolbars share one row and only the most frequently used tools appear on each portion of the toolbar. Personalized menus move frequently used menu items to the top of the list, and the menus themselves display only a portion of the available menu options. The personalized menus and toolbars feature has been unequivocally either loved or hated by Excel power users. Microsoft heard their users’ feedback and—for those in the latter category—made the feature a little easier to turn off. We consider this a blessing since we recommend that everyone turn it off before you start entering numbers and letters in a worksheet. After you have an application mastered, you might choose to make use of personalized menus and toolbars, but do not try it if you are learning an application. In our opinion, this is an invitation to indescribable aggravation. A less controversial change in Excel 2002 is the new look of the toolbars and menus. When selected, toolbar buttons and menu options in Excel 2002 turn blue with a darker blue border. Microsoft describes this as a streamlined, flatter look that is designed to take advantage of high-color displays and new Windows 2000 technologies. The biggest advantage is you can look at another user’s screen or a picture in a book and know at a glance which version of Excel you are looking at. Beyond that, the change won’t impact your use of Excel 2002.
NOTE
The new buttons and commands also provide a sharper contrast for the visually impaired. Excel 2002 includes more built-in accessibility options. Choose Help Microsoft Excel Help and enter accessibility in the Answer Wizard for a list of all the options.
Working With (or Without) Personalized Menus and Toolbars In Excel 2002, menu bars and toolbars adapt to your usage. By default, menus are collapsed and only display commonly used commands (see Figure 1.7) unless you
4002c01.qxd 7/17/01 1:37 PM Page 15
New Features in the Excel Interface
PART
I Putting Excel 2002 to Work for You
choose to expand them to see the full list of commands. To fully expand a collapsed menu, click the Expand arrow at the bottom of the menu or simply hover over the menu for a moment.
15
FIGURE 1.7 Menus are initially collapsed, but they can be expanded to show all of the available commands.
Some buttons that were traditionally located on the Standard and Formatting toolbars are hidden so that both toolbars can occupy a single row. Drag the toolbar handle at the left end of the Formatting toolbar to adjust the amount of space given to the Standard and Formatting toolbars. There’s a Toolbar Options button at the right end of every toolbar. If the toolbar includes other buttons that are currently hidden, the Toolbar Options button image includes a right-pointing double arrow. To display toolbars one per row or access a button that is not visible, click the Toolbar Options button to open the menu. Choose Show Buttons on Two Rows to display the Standard and Formatting toolbars on separate rows.
4002c01.qxd 7/17/01 1:37 PM Page 16
16
CHAPTER 1 • Working with Excel 2002
The menu contains buttons normally displayed on the toolbar but that are hidden due to the single-row toolbar arrangement. Click any button to display it on the toolbar. Unless you have unused space on your toolbar, the new button trades places with a button you haven’t used in a while (and hopefully you don’t want to use it next). The button that was kicked off the toolbar is placed on the Toolbar Options menu. As you continue to use Excel, most of the buttons you use regularly will be displayed on your toolbars. If you find that the personalized menus take more than a little getting used to and you would like to restore your application to a more predictable (Excel 97 style) interface, choose Add Or Remove Buttons Customize from the Toolbar Options menu or right-click any toolbar and choose Customize. On the Options tab, enable two check boxes: the Show Standard and Formatting Toolbars on Two Rows check box and the Always Show Full Menus check box.
Adding Toolbar Buttons Is a Snap If you’re looking for a button that isn’t available on either the toolbar or the More Buttons menu, click Toolbar Options Add or Remove Buttons, then select the toolbar to display the list of all buttons for the toolbar. A button that is selected is currently displayed on either the toolbar or the More Buttons menu. Check any button to move it to the toolbar. For more information about customizing toolbars and menu bars, refer to Chapter 21, “Automating Excel 2002 with Macros.”
Using the Open and Save As Dialog Boxes In Excel 2002 the Open and Save As dialog boxes have been modified so that they’re more flexible and functional. If you’re an experienced Office user who understands how Open and Save As dialogs behave, you might not notice a major change; you can resize these dialog boxes. Just drag an edge to make the dialog box large enough to display all of the files in a folder. The Places bar in the Open and Save As dialog boxes (see Figure 1.8) was introduced in Office 2000, but was not easily customizable. In Excel 2002 you can customize the Places bar so it includes your frequently used local, network, and web folders.
4002c01.qxd 7/17/01 1:38 PM Page 17
New Features in the Excel Interface
FIGURE 1.8 The Open dialog box features a customizable Places bar.
PART
Putting Excel 2002 to Work for You
I
Choose History in the Places bar to see the list of the most recently modified or created Office documents, folders, and drives on your system. The list is initially sorted in descending order based on modification date and time (see Figure 1.9), but you can sort by name, type, or size by clicking the column heading as you would in Windows Explorer or Outlook. To reset the history, choose History in the Places bar, then select Tools Clear History from the dialog box menu.
FIGURE 1.9 Choose History to open or save in a recently used folder or drive.
17
4002c01.qxd 7/17/01 1:38 PM Page 18
18
CHAPTER 1 • Working with Excel 2002
The Save As dialog box (which opens the first time you save a file as well as each time you choose File Save As) has an additional feature on its Tools menu: the ability to compress pictures while saving a workbook.
NOTE
You’ll find information on compressing pictures in Excel in Chapter 11, “Using Drawing and Graphics Tools.”
Customizing the Places Bar Customizing the Places bar is easy. Get in the habit of adding folders for current projects so that the Open and Save As dialog boxes give you quick access to the folders you need. When the projects are completed, delete the folders. To add a folder to the Places bar, select the folder in either the Open or Save As dialog box, then choose Tools Add to “My Places” from the dialog box menu. Icons for the five default places (History, My Documents, Desktop, Favorites, and Web Folders) take up most of the space, so the only sign that you’ve added a folder is the More Places arrow at the bottom of the Places bar. Click the arrow to see the icon for the folder you’ve added. To rearrange the icons on the Places bar, select the icon you wish to move up or down, right-click, and choose Move Up or Move Down from the shortcut menu. Choose Small Icons from the menu to have more space for folders. To delete an unused folder, right-click the icon on the Places bar and choose Remove from the shortcut menu.
4002c01.qxd 7/17/01 1:38 PM Page 19
TIP
There’s one set of Open and Save As dialog boxes shared by all the Office applications. Folders added to the Places bar in Excel appear in all the Office applications. When you clear the History for Excel, you’re clearing it for all Office applications.
Repairing Damaged Workbooks If Excel closes in the middle of a session—for example, because of a power loss or an application error—open workbooks may be corrupted. When you try to open a corrupt workbook file, Microsoft Excel 2002 automatically goes into recovery mode and attempts to open and, if necessary, repair the workbook. If the repair fails, Excel tries to open the file again but does not attempt to repair it. Instead, Excel settles for saving the data from the file without trying to recover formatting and formulas. If the file can be opened, either because no repair was needed or the repair was successful, a Document Recovery pane opens on the left side of the application window with the workbook icon, filename, and file information. Select the file in the Document Recovery pane and choose Show Repairs from the menu (see Figure 1.10) to review repairs to the file. FIGURE 1.10 View, save, or close recovered and repaired files in the Document Recovery pane
19
PART
I Putting Excel 2002 to Work for You
New Features in the Excel Interface
4002c01.qxd 7/17/01 1:38 PM Page 20
20
CHAPTER 1 • Working with Excel 2002
Review the repair information and the file information to decide what you want to do with the file. A file labeled Recovered is usually, but not always, newer than a file of the same name marked Original. Choose Save As to save the file or Close to discard the recovered workbook. If Excel doesn’t attempt to repair a corrupt workbook, you can force the repair attempt. Choose File Open from the menu. In the Open dialog box, select the file you wish to repair. On the Open button’s menu, select Open and Repair.
NOTE
For tips on recovering workbooks manually, see Appendix A, “Customizing Excel 2002.”
Getting Help Microsoft, like all the leading software companies, spends a great deal of effort designing help systems that will be useful for the people who use their software. This isn’t altruism; good online help results in lower costs for help desk functions both at Microsoft and at the large corporations who purchase and support software. In Office 97, Microsoft gave us a social help interface: Clippit and other office assistants. In Office 2000, Clippit was redesigned as an agent and removed from the small window used in Office 97 applications. In both versions, however, the first thing you saw when you started an application was Clippit or a Clippit understudy. Clippit became the Office feature we loved to hate.
NOTE
Do you miss Clippit? Visit www.microsoft.com/office/clippy/ for some quality time with the paper clip.
Office Assistant and Ask a Question With Excel 2002, Microsoft has taken a different approach. (The “XP” in Office XP stands for “eX Paperclip.”) Clippit doesn’t appear until its presence is requested by choosing Help Show the Office Assistant or clicking the Office Assistant button on
4002c01.qxd 7/17/01 1:38 PM Page 21
the Standard toolbar. In place of the social, overeager help agent, there’s an incredibly passive Ask a Question feature. To use Ask a Question, enter a question or phrase to replace the text Type a Question for Help in the Ask a Question box, which shares a row with the menu bar.
Type a question, press Enter, and suggested avenues of inquiry are presented, ending with an offer to continue your search online at the Microsoft website.
The Ask A Question box maintains a history, so you can search again on questions asked previously. The history is cleared at the end of the application session.
Interacting with Excel Smart tags are one of the amazing new features in Office XP. A smart tag is a contentbased, object-attached user interface—a fancy way of saying that Excel scans the content of a cell to see if it falls into a recognized category of content, such as a stock ticker symbol. If it does, Excel attaches a menu of content-specific options to the cell. Here’s the Smart Tag menu attached to a cell with a stock symbol.
If you select Insert Refreshable Stock Price from the menu, Excel creates and runs a query at MSN MoneyCentral to return the results shown in Figure 1.11.
21
PART
I Putting Excel 2002 to Work for You
Interacting with Excel
4002c01.qxd 7/17/01 1:38 PM Page 22
22
CHAPTER 1 • Working with Excel 2002
FIGURE 1.11 Use the smart tag to insert a refreshable online quote.
Smart tags are not enabled by default, but are easily turned on in the AutoCorrect Options dialog box (Tools AutoCorrect Options). For more information on smart tags, see Chapter 4, “Using Names and External References,” and Chapter 17, “Importing and Exporting from Excel 2002,” and Appendix D, “Creating Simple Smart Tags for Excel 2002.”
More Help Completing Tasks In Excel 2000, the command structure was rigid. If, for example, you needed to paste data as a link, you had to select Edit Paste Special from the menu. If you pressed Enter or chose Paste rather than Paste Special, you needed to undo the paste action and start again. The Go To Special dialog box needed to paste formula results as values was better hidden than the “spy hunter” Easter egg.
NOTE
Easter eggs are program features that are intentionally hidden (for example, the names of the programming team who worked on an application). Visit www.eeggs.com to view or report Easter eggs.
In Excel 2002, there’s far more flexibility. When you paste a selection, Excel automatically provides a list of options including linking, formatting, and options that were formerly located in disparate dialog boxes. Based on smart-tag technology, the options menus for Paste, Fill, and Insert may be the best new features in Excel 2002.
4002c01.qxd 7/17/01 1:38 PM Page 23
Smart tags are also used to provide friendlier, more specific error messages. The smart tag interface changes are detailed in Table 1.1.
TABLE 1.1
E x c e l 20 0 2 Wo r k s h e e t I n d i c a t o r s a n d B u t t o n s
Indicator/ Options Button
I
Description
Green triangle indicator in the upper left corner; formula contains an error. Select the cell to display the Error Checking Options button.
Purple triangle indicator in the lower right corner; cell contains a smart tag. Point to the cell to display the Smart Tag Actions button.
Blue underscore under cell; cell contains a hyperlink. Point to the blue underscore or press Alt+Shift+F10 to display the AutoCorrect Options button. The Paste Options button is displayed when you paste information in a worksheet. The AutoFill Options button is displayed when you fill (copy) cells.
The Insert Options button appears when you insert rows, columns, or cells into a range of formatted cells.
This new functionality is also based on smart tags technology. The two options buttons you will encounter most frequently are Paste Options and AutoCorrect Options. Other indicators and buttons are discussed in later chapters.
Paste Options Cut/Copy and Paste features have been around since Windows was in its infancy, but never before have they been so flexible and so powerful. In Excel 2002 you can make choices about pasting that save time or reduce multistep tasks to a single click. For
23
PART
I Putting Excel 2002 to Work for You
Interacting with Excel
4002c01.qxd 7/17/01 1:38 PM Page 24
24
CHAPTER 1 • Working with Excel 2002
example, you can choose whether you want to keep the original formatting of the copied cells or change them to the formatting used in the destination, as shown in Figure 1.12. When the selection is pasted using the Paste button or a Paste command, the Paste Options button appears. Click the button to open a menu of formatting choices.
FIGURE 1.12 Paste Options let you decide how pasted cells should be formatted.
NOTE
The Paste Options button does not appear when you paste a selection with the
Enter key.
If you paste data from Excel into Word, as shown in Figure 1.13, there are additional options including linking the pasted selection to the Excel worksheet as if you’d chosen Edit Paste Special and set up the link in the Paste Special dialog box. FIGURE 1.13 Pasting from Excel gives you the option of linking to the Excel worksheet.
NOTE
For more information on using Excel data in other Office applications, see Chapter 18, “Using Excel 2002 with the Web.”
4002c01.qxd 7/17/01 1:38 PM Page 25
Interacting with Excel
PART
I Putting Excel 2002 to Work for You
Excel includes paste options on the Paste command button. Click the drop-down arrow on the Paste button to paste formulas and values, paste with no borders, transpose the values, paste as a link, or open the Paste Special dialog box.
25
After you click the Paste button, click the Paste Options button in the worksheet to access other choices.
Reversing or Disabling AutoCorrect When you change an auto-correction by reentering the original text in the formula bar, Excel won’t attempt to auto-correct the entry again. For some types of auto-corrections, the AutoCorrect Options button lets you reverse the current auto-correction or change the AutoCorrect list so the auto-correction won’t happen in the future. When Excel makes a correction, a blue underscore appears under the cell when it is active. Point to the underscore to display the AutoCorrect Options button. Click the button to open an options menu where you can choose to change the cell back to the original entry, stop automatically correcting this type of entry, or open the AutoCorrect options dialog box. For example, Excel automatically formats URLs and e-mail addresses as hyperlinks. Clicking a cell with an e-mail hyperlink fires up Outlook and opens a preaddressed message form. This is either exactly what you would like Excel to do when you click the address or it is an incredible inconvenience. You can use the AutoCorrect options to instruct Excel to stop formatting hyperlinks.
4002c01.qxd 7/17/01 1:38 PM Page 26
26
CHAPTER 1 • Working with Excel 2002
Collaboration with Excel 2002 Excel 2002 is designed to support collaboration with ease. Building on the workgroup improvements in Excel 2000, Microsoft has made it both easier and safer to share workbooks with colleagues. On the File Send To submenu there’s a new option: Send to Mail Recipient for Review. When you send a workbook for review, you can send a copy of the workbook and merge changes back into the original when the reviewer returns it, or you can send a hyperlink to the workbook’s location in a shared folder or web folder. When the recipient opens the copy or the hyperlinked workbook, the Reviewing toolbar automatically opens so the reviewer can easily add comments and return the file by e-mail. Like the other Office XP applications, Excel 2002 works seamlessly with SharePoint Team Services, the group or departmental web service included with Office XP. Thanks to some creative naming in Redmond, SharePoint Team Services is often confused with SharePoint Portal Server, Microsoft’s new enterprise server. The Team Services let you create and maintain an intranet site (see Figure 1.14) which can include lists, discussions, calendars, and shared Office XP documents including Excel workbooks. It takes an entire IT department to run SharePoint Portal Server. But if you have appropriate permissions, you can set up your first SharePoint Team Services site and invite colleagues to participate in less than an hour. FIGURE 1.14 Use SharePoint Team Services to collaborate, discuss, and share Office documents.
4002c01.qxd 7/17/01 1:38 PM Page 27
NOTE
For more information on Excel’s collaboration features, see Chapter 20, “Using Excel’s Workgroup Tools.”
Moving Beyond the Standard Keyboard Excel 2002 supports two new input methods: speech and handwriting. Speech-recognition technology has seen recent major advances, due less to changes in software than to significant hardware improvements. The Microsoft Speech Recognition System uses Lernout & Hauspie’s speech-recognition engine for dictation and application command and control. Handwriting recognition is a relatively new method of for text input. Excel 2002’s handwriting tools let you draw text and numbers that are immediately recognized and converted to text. Although this feature almost works with a mouse (after a fashion), handwriting tablets designed for this purpose give this feature a much more natural feel. For both input technologies, getting the appropriate hardware is critical. With Excel 2002’s Typical installation, the Speech features are installed on first use. You must choose a Custom installation to install the Handwriting features. See Appendix A, “Customizing Excel 2002,” for more information on installation.
NOTE Some people think that if they can “talk to their computer,” they won’t have to learn as much. The problem with this logic is that you have to know enough about Excel to know what to say or write.
Speech Features There are three ways to use the Speech Recognition System in Excel 2002: • To dictate text and numbers to go into cells • To enter menu commands with your voice • To hear or play back text from a workbook Speech recognition requires an appropriate soundcard and microphone. If you want to use Excel’s text-to-speech features, you’ll either need headphones or good speakers and tolerant coworkers in adjacent offices.
27
PART
I Putting Excel 2002 to Work for You
Moving Beyond the Standard Keyboard
4002c01.qxd 7/17/01 1:38 PM Page 28
28
CHAPTER 1 • Working with Excel 2002
Speech Recognition Setup After you’ve selected and installed a soundcard, speakers or headphones, and microphone, you’re just two steps away from entering text and commands just like the crew of the starship Enterprise. 1. Set up your microphone with the Microphone Wizard (less than 5 minutes). 2. Create speech files with the Voice Recognition Wizard (less than 20 minutes).
Selecting Speech Hardware Before you even attempt to use the speech recognition tools, Microsoft recommends a minimum of 128MB of RAM. As with any recommended minimum, you will not see optimal performance at this level. You need 192MB–256MB to give you more stability and improve the software’s accuracy.
Setting Up Your Microphone
Locate the microphone and headphone jacks on your computer. Plug in your microphone. If you have a headset microphone, plug in the headset. You can run the Microphone Wizard from any Office application. Choose Tools Speech Speech Recognition from the menu. The Language Bar appears, floating somewhere over the Excel application window
NOTE
If there is no Speech command on Excel’s Tools menu, the feature is not installed. If there is no Speech Recognition command on the Speech menu, your hardware doesn’t meet the minimum requirements to use this feature.
You should be prompted to run the Microphone Wizard. If another user has previously set up the microphone for use with Excel 2002 or if you’ve set up the microphone for use with non-Office applications (or in another location), you’ll still want to run the Microphone Wizard. There are several speech recognition products on the
4002c01.qxd 7/17/01 1:38 PM Page 29
market, and each has different ideal microphone settings. This wizard adjusts the volume from your microphone so that it works with Excel and the other Microsoft Office XP applications. If you are not prompted to run the Microphone Wizard, choose Tools Options from the Language Bar. In the Speech Properties dialog box, click the Configure Microphone button to start the Microphone Wizard. Follow the instructions in the wizard to configure your microphone for optimal use with Microsoft Excel 2002.
TIP If you’re using your headset microphone and laptop in a new environment (like a hotel or conference room), it’s a good idea to invest a few minutes and run the wizard again to ensure the best possible speech recognition.
Training the Speech Recognition System After the microphone is configured, you will use the microphone to train the Speech Recognition System. Train the system in the environment where you intend to use it: if you’re going to use it in your office, train the system in your office with the normal level of office noise. Choose Tools Training on the Language Bar to create a user profile and begin training the system to recognize the way you pronounce words. You read the text that’s displayed in the dialog box and the Speech Recognition System highlights each word as it recognizes it, as shown in Figure 1.15. Your first training session will probably take around 20 minutes; you can pause at any point and continue later, but if you stop prior to the end of the session, you’ll need to start at the beginning the next time you wish to train. FIGURE 1.15 As you read the session text, each recognized word is highlighted by the Speech Recognition System.
29
PART
I Putting Excel 2002 to Work for You
Moving Beyond the Standard Keyboard
4002c01.qxd 7/17/01 1:38 PM Page 30
30
CHAPTER 1 • Working with Excel 2002
When you’ve completed the introductory training session, your speech settings will be saved in a speech profile. The system keeps a separate profile for each user. After you’ve worked with the Speech Recognition System in Excel 2002 and the other Office XP applications, you may want to provide more training using other materials to increase recognition. Just choose Tools Training on the Language Bar and choose one of the sessions from the list.
Dictating in Excel 2002 To use the dictation or voice command features, make sure the Speech feature is enabled. Look for a check mark in front of the Speech command on Excel’s Tools menu. Click the Microphone button on the Language Bar to turn the microphone on. Begin speaking to enter text in your document. Speak each word clearly, and speak the names of the punctuation marks (comma, period, question mark). You can turn the microphone on or off with voice commands Microphone On and Microphone Off. In Excel, cell navigation is part of dictation: precede the direction with the word Go to Go Up, Go Down, Go Left, or Go Right one cell.
Giving Voice Commands in Excel 2002 You can switch from dictating speech that you want recognized and giving voice commands to operate Excel by clicking the Voice Command button on the Language bar. Table 1.2 shows the voice commands that are available throughout Office.
TABLE 1.2
Vo i c e N a v i g a t i o n C o m m a n d s
Voice Commands
Keyboard or Mouse Equivalent
Return Enter
Enter
Backspace Delete
Backspace
Space Space Bar
Spacebar
Escape Cancel
Escape
4002c01.qxd 7/17/01 1:38 PM Page 31
TABLE 1.2
Vo i c e N a v i g a t i o n C o m m a n d s ( c o n t i n u e d )
Voice Commands
Keyboard or Mouse Equivalent
Right-Click Right-Click Menu Show Right-Click Menu Context Menu Show Context Menu
Right-click a menu
Tab
Tab
Control Tab
Ctrl+Tab
Shift Tab
Shift+Tab
End Go End
End
Home Go Home
Home
Up Go Up Up Arrow Arrow Up
Up Arrow
Down Go Down Down Arrow Arrow Down
Down Arrow
Left Go Left Left Arrow Arrow Left
Left Arrow
Right Go Right Right Arrow Arrow Right
Right Arrow
Previous Page Next Page Page Down
Page Down
Page Up
Page Up
31
PART
I Putting Excel 2002 to Work for You
Moving Beyond the Standard Keyboard
4002c01.qxd 7/17/01 1:38 PM Page 32
32
CHAPTER 1 • Working with Excel 2002
For a complete list of the voice commands that are available in Excel, click the Help button on the Language bar.
Tweaking the Speech Recognition System Speech a recognition is tradeoff between recognition and accuracy. Words are recognized in context; the more surrounding words the system has to examine, the more likely it is to determine which word you actually spoke. In Excel, this presents a particular problem because you’re often entering titles or labels rather than phrases or sentences. The more words the system examines, the longer it takes to display your dictated text on screen. If the lag between dictation and display is too long or if the percentage of incorrectly recognized words is too high, you can change the recognition/accuracy settings to improve recognition or speed. There is another setting (Rejection Rate) to adjust if the system frequently ignores menu commands in voice command mode. To access the Speech Recognition System settings, choose Tools Options from the Language Bar menu. In the Speech Properties dialog box, select your profile, then click the Settings button to open the Recognition Profile Settings dialog box, shown in Figure 1.16. FIGURE 1.16 Use the settings in the Recognition Profile Settings dialog box to tweak the performance of the Speech Recognition System.
4002c01.qxd 7/17/01 1:38 PM Page 33
Text to Speech Excel’s Text to Speech feature was designed to for accessibility, but it is incredibly handy for any user who needs to check a worksheet against a printed document for accuracy. To use Text to Speech, choose Tools Speech Show Text to Speech Toolbar to display the toolbar. Select the range of cells you want to have vocalized, as shown in Figure 1.17. Hold the Ctrl key to select noncontiguous ranges. Click the Speak Cells button to have Excel vocalize the contents of each cell. FIGURE 1.17 Use Text to Speech to proof text and numbers entered from a printed document.
If the selection includes more than one column or row, click the By Rows or By Columns button to have Excel speak the cells horizontally or vertically. To control the pace, click the Speak on Enter toggle button. With Speak on Enter enabled, Excel speaks the cell when you press Enter to leave the cell.
TIP
Text to Speech starts with the active cell. If you’re selecting noncontiguous cells, select the ranges in reverse order, ending with the range you want Excel to speak first.
Changing Voices Text to Speech has two voices, and undoubtedly you’ll soon be able to download other voices from the Microsoft site and third-party vendors. To change voices or modulate the speed and volume of the voices, choose Tools Options from the Language Bar to open the Speech Properties dialog box, shown in Figure 1.18.
33
PART
I Putting Excel 2002 to Work for You
Moving Beyond the Standard Keyboard
4002c01.qxd 7/17/01 1:38 PM Page 34
34
CHAPTER 1 • Working with Excel 2002
FIGURE 1.18 Change voice, speed, and volume in the Speech Properties dialog box.
You can do three things on the Text to Speech tab: • Choose a voice from the Voice Selection drop-down list. • Use the slider bar to change the voice speed. • Click Audio Output and then Volume to change the playback volume.
NOTE
To install keyboard and voice support for other languages, open the Options menu on the Language bar and choose Settings to open the Text Services dialog box.
Tips for Text to Speech Text to Speech works very well with worksheets formatted to take advantage of the speech playback feature. When you’re creating a worksheet that you plan to use Text to Speech with, observe these rules: • If the worksheet includes negative numbers, use a number format that includes a minus sign rather than parentheses.
4002c01.qxd 7/17/01 1:38 PM Page 35
• Format dates with a four-digit year and make sure the name of the month is fully or at least partially spelled out: Mar-8-1957 or March 8, 1957, rather than 3/8/57. Text to Speech reads Jan-4-2002 as January fourth two thousand two. It reads 1/4 as one-fourth. • Time formats should include the hour; a format that includes only minutes and seconds will be read as hours and minutes. • Text to Speech has difficulty with zip codes (which it reads as whole numbers) and telephone numbers. Format telephone numbers using the Special format for telephone numbers (Format Cells Number) and always include the area code, and Text to Speech will read the telephone number properly.
Handwriting Recognition Handwriting recognition creates opportunities for new types of computers. No longer tied to a keyboard, new computing devices are offering the same freedom and portability that legal pads and steno books have provided for years. Already, personal digital assistants (PDAs) and handheld computers such as Palms and Pocket PCs offer handwriting recognition as a primary input method. Including handwriting recognition in Excel 2002 brings us one step closer to throwing out our keyboards and giving users more natural and flexible computing options. The Handwriting tools in Excel 2002 include onscreen drawing and handwriting recognition.
NOTE
Our informal survey suggests that there’s a negative correlation between a user’s typing speed and their excitement about handwriting recognition.
Drawing Onscreen The Drawing Pad is designed to make it easy to insert a quick drawing into a workbook. Although there are many more tools on the Office Drawing toolbar, the Drawing Pad offers simplicity and flexibility for alternative computer devices. To activate the Drawing Pad, click Handwriting on the Language bar and choose Draw, and then click the Draw button on the Language bar. This opens the Drawing Pad shown in Figure 1.19.
NOTE
If the Draw button doesn’t appear on the Language bar, click the Language bar’s Option button and select Microsoft Handwriting Item from the list of button choices. If Handwriting Item doesn’t appear on the list, it is not installed.
35
PART
I Putting Excel 2002 to Work for You
Moving Beyond the Standard Keyboard
4002c01.qxd 7/17/01 1:38 PM Page 36
36
CHAPTER 1 • Working with Excel 2002
FIGURE 1.19 Use the Drawing Pad to create and insert simple drawings into a document
Using Handwriting to Input Text Handwriting recognition in Excel 2002 is amazingly accurate, particularly for numbers. Handwriting tablets will become more common as more people experience the ease with which Excel converts even the most illegible scrawl into typed text. Figure 1.20 shows how accurately Excel 2002 converts handwriting. FIGURE 1.20 Excel 2002 can accurately convert this scrawl into the cell entry “Total”!
To activate handwriting, choose Lined Paper from the Write menu on the Language bar, and then click the Lined Paper button. This opens the Lined Paper Writing Pad shown in Figure 1.20. If you print on the Lined Paper writing surface, your letters are immediate transcribed. If you write cursive style, your writing is automatically transcribed when you pause for more than a second or two. To navigate to another cell, click in the worksheet.
4002c01.qxd 7/17/01 1:38 PM Page 37
If you find the Lined Paper window too confining, you can click the Write Anywhere button, then write on your worksheet.
www
If your computer is equipped with a touchpad, get a PDA stylus and you have a handwriting input device. Hold the mouse button down to write; release it to move to the next word. (This probably won’t become your input method of choice.) If you have a graphics digitizing tablet for use with 3D or computer-aided drafting software, you will find handwriting a much more pleasant experience. We used Graphire tablets from Wacom for handwriting input for this chapter. To learn more about Wacom’s offerings, visit www.wacom.com.
Setting Handwriting Options Click the down arrow on the Write Anywhere or Lined Paper window title bar to open a shortcut menu. Choose Options to open the Handwriting Options dialog box, shown in Figure 1.21, to change the following options: • Pen color • Pen (line) width • Space following handwritten text • Automatic recognition and recognition delay • Toolbar layout and button size • Lined paper background and number of lines
FIGURE 1.21 Turn automatic recognition off or on in the Handwriting Options dialog box.
37
PART
I Putting Excel 2002 to Work for You
Moving Beyond the Standard Keyboard
4002c01.qxd 7/17/01 1:38 PM Page 38
38
CHAPTER 1 • Working with Excel 2002
Multilanguage Support
www
Excel 2002 supports editing and viewing workbooks in over 80 languages—very helpful if your organization’s work crosses national borders. Excel 2002 includes language tools for U.S. English, French, and Spanish. When Excel detects a cell entry in French or Spanish, it prompts you to install support for the language. This doesn’t work perfectly; English is a mongrel language that includes Spanish and French words, so you’re occasionally prompted to install the French language tools in a workbook that contains only English. You can install other languages and create databases with records in different languages or web pages that include English and one or more of the other supported languages. With the addition of the Microsoft Visual Keyboard, you can confidently type in languages other than the language used to label your keyboard’s keys. You can download the Microsoft Visual Keyboard at Microsoft’s Office website at office.microsoft.com.
NOTE
For information on setting up your computer so you can work in more than one language and on installing keyboards for additional languages, see Appendix A, “Customizing Excel 2002.”
Minimizing the Impact of Crashes Microsoft has gone all out in Excel 2002 to protect your documents when the unexpected happens. In addition to the traditional AutoRecovery features, Excel 2002 has a number of new options that save workbooks when Excel crashes, recovers corrupted workbooks, and lets you choose which version of a recovered or saved workbook you want to use. If you have a pretty stable network and operating system environment, you may get to use these features only on rare occasions. Others who are less fortunate may get to know the features intimately. Either way, it’s helpful to know what to expect and what choices to make when your software or hardware crashes and you are faced with those critical decisions about how to recover your work.
Recovering From an Application Error If Excel doesn’t respond, there’s a new feature you should try out before pressing Ctrl+Alt+Del. Microsoft Office Application Recovery attempts to revive Excel and
4002c01.qxd 7/17/01 1:38 PM Page 39
recover your workbooks. From the Windows Start menu choose Programs Microsoft Office Tools Microsoft Office Application Recovery. In the list of applications, choose Excel. Click Recover Application or Restart Application to try to retrieve your work. Choose End Application to close Excel without attempting to recover your workbooks.
Saving When You Crash The Document Recovery feature is new. After a crash occurs, Office opens a message box to notify you of the application crash, giving you the option to recover your open workbooks and restart Excel. (Clear the check box if you just want to forget it and go home.) With a simple click you can send an error report to Microsoft or your help desk to help them develop fixes that will avoid similar crashes in the future. Click the Send Error Report or Don’t Send button to save your data or close without saving. If you choose Send an Error report, Office sends the report. When Excel restarts, you’ll be able to restore the recovered version of the document (see “Using Document Recovery Task Pane” later in this section).
Setting Timed Recovery Save Options Timed Recovery Save is the traditional AutoRecover feature that has been around for a while. Document Recovery will probably result in a more current version of your document, but the Timed Recovery feature is still valuable when the power goes out and there is no time to save-on-crash. You can increase or decrease the frequency of AutoRecover on the Save tab of the Options dialog box in Word, Excel, PowerPoint, or an e-mail message form in Outlook. The setting affects all four applications.
Making Use of Office Safe Mode If Excel fails to start and you have to shut it down using the Task Manager (Ctrl+Alt+Del), the next time you attempt to open the application, Excel prompts you to start in Safe Mode. Safe Mode disables add-ins or code that may be causing the problem. If Excel starts smoothly, close, then reopen it in normal mode.
39
PART
I Putting Excel 2002 to Work for You
Minimizing the Impact of Crashes
4002c01.qxd 7/17/01 1:38 PM Page 40
40
CHAPTER 1 • Working with Excel 2002
Other Recovery Features In addition to the myriad features for users, Excel 2002 contains a number of new features to help system administrators, help desks, and Microsoft track persistent problems. These features (including Client Logging, Crash Reporting, Hang Reporting, Corporate Tracking and Setup Failure Reporting) make the future stability of Office even more promising. If you’d like to know about the reliability features of Excel 2002, refer to www.microsoft.com/office.
Closing Workbooks and Excel To close the active workbook window, click the window’s close button or choose File Close from the menu. To close all open windows of a workbook, choose File Close. Use this when you’re presenting the workbook in multiple windows to compare areas that aren’t right next to each other. To close all open workbooks, hold Shift, then choose File Close All. To close Excel, choose File Exit.
4002c02.qxd 7/17/01 1:33 PM Page 41
CHAPTER
2
CREATING EXCEL WORKSHEETS F E ATU R I NG
Entering data in Excel
Using Find and Replace
Working with numbers
Using AutoFill features
Formatting numbers
Creating custom formats
Printing and previewing
4002c02.qxd 7/17/01 1:33 PM Page 42
In this chapter, we’ll create an Excel worksheet with text, numbers, and formulas. If you’re already familiar with earlier versions of Excel, you’ll probably want to skim through this chapter to pick up new tricks that will help you work more efficiently. Look for the New icon in the margin to find out about the latest improvements in Excel 2002.
Entering and Editing Cell Entries Welcome to Excel 2002, the number cruncher! If you’ve used earlier versions of Excel, you’ll find many new features that are welcome additions. If you’re moving to Excel from another spreadsheet program, you’re in for a real treat. Simply put, Excel 2002 is the best spreadsheet program ever designed—a powerful program with plenty of features to help you work more effectively.
The Excel Application Window The Excel application window (see Figure 2.1) includes the standard title bar, menu bars, and toolbars. The task pane is displayed at the right side of the application window. Below the toolbars is a strip that contains the name box and the formula bar. The name box displays the name or cell address of the active cell; as you create a formula, it appears in the formula bar. The Excel status bar displays information about current selections, commands, or operations. The right end of the status bar displays NUM if the keyboard’s Num Lock is on. The Ask a Question box, used to get information from Excel Help, appears at the right end of the menu bar (with the default search text Type a Question for Help). Click the box’s down arrow to choose from a list of topics you’ve recently looked up. Excel 2002 uses personalized menus and toolbars, so the Standard and Formatting toolbars appear side by side and the menus expand after a slight delay to show less frequently used options. Buttons you use less frequently move to the end (or off the end) of the toolbar to make room for more frequently used buttons. See “New Features in the Excel 2002 Interface” in Chapter 1 for information on personalized toolbars and menus. When you launch Excel, the Excel application window opens with a new Excel workbook. A workbook is a multipage Excel document. Each page in the workbook is called a worksheet, and the active worksheet is displayed in the document window. By default, a new workbook has three sheets. You can add or remove sheets from a workbook as needed.
4002c02.qxd 7/17/01 1:33 PM Page 43
Entering and Editing Cell Entries
FIGURE 2.1 The Excel 2002 application window
43
PART
Putting Excel 2002 to Work for You
I
TIP If you typically need a different number of worksheets than the three offered by default, change the number of default sheets. Choose Tools Options to open the Options dialog box. On the General tab of the Options dialog box, change the Sheets in New Workbook setting to the desired number of worksheets. At the left end of the horizontal scroll bar are sheet tabs and navigation buttons. Click a sheet tab to move to another worksheet or use the navigation buttons to scroll through the sheet tabs (see Figure 2.1).
EXPERT TIP
To quickly move to any worksheet, right-click the navigation buttons and choose the sheet name from the shortcut menu.
4002c02.qxd 7/17/01 1:33 PM Page 44
44
CHAPTER 2 • Creating Excel Worksheets
Worksheet Components Each worksheet is divided into columns, rows, and cells, all separated by gridlines, as shown in the worksheet in Figure 2.2. Columns are vertical divisions. The first column is column A, and the letter A appears in the column heading. The horizontal rows are numbered. Each worksheet has 256 columns (A through IV) and 65,536 rows—plenty of room to enter all your data! FIGURE 2.2 A worksheet consists of cells organized into rows and columns.
A cell is the intersection of a row and a column. Each cell has a unique address composed of the cell’s column and row. For example, the cell in the upper-left corner of the worksheet (with the text Worksheet Title in Figure 2.2) is cell A1. Even though some of the text appears to run over into cell B1 in the next column, all of the text was entered in cell A1. The active cell, C2 in Figure 2.2, has a frame around it called the cell pointer, and the headings in the active cell’s column (C) and row (2) are highlighted. When you enter data, it is always placed in the active cell.
4002c02.qxd 7/17/01 1:33 PM Page 45
TIP
Right-click any cell or selected cells to display a shortcut menu of frequently used commands. You can, for example, change the cell’s format, as well as cut, copy, or paste its contents.
Moving the Cell Pointer To activate a cell with the mouse, simply click in the cell. To move the pointer one cell to the left, right, up, or down, use the keyboard arrow keys. Use the Ctrl (Control) key and the arrow keys to move to the edge of the current data region: an area of the worksheet with data entered in cells, bounded by the edges of the worksheet and empty rows and columns. Frequently used keyboard commands are shown in Table 2.1.
TABLE 2.1
Ke y s t r o k e s t o M o v e t h e C e l l Po i n t e r
Key(s)
Moves
Home
To column A in the current row
Ctrl+Home
To cell A1
PgDn
Down one screen
PgUp
Up one screen
Alt+PgDn
Right one screen
Alt+PgUp
Left one screen
Ctrl+_
Right edge of current data region
Ctrl+_
Left edge of current data region
Ctrl+_
Top of current data region
Ctrl+_
Bottom of current data region
Ctrl+PgDn
Next worksheet
Ctrl+PgUp
Previous worksheet
Ctrl+Tab or Ctrl+F6
Next workbook or window
Ctrl+Shift+Tab or Ctrl+Shift+F6
Previous workbook or window
To quickly view other areas of the worksheet, use the scroll bars. Drag the scroll bar’s scroll box to scroll more than a couple of rows or columns. Note that scrolling doesn’t change the active cell—scrolling lets you view other parts of the worksheet, but the active cell is wherever you left the cell pointer. To scroll long distances, hold
45
PART
I Putting Excel 2002 to Work for You
Entering and Editing Cell Entries
4002c02.qxd 7/17/01 1:33 PM Page 46
46
CHAPTER 2 • Creating Excel Worksheets
the Shift key while dragging the scroll box, and Excel will scroll farther for each movement of the mouse.
NOTE
A Microsoft Intellimouse or other pointing device with a wheel or speed scroll feature is a great tool for Excel worksheets.
To use Excel efficiently, get comfortable moving the cell pointer using both the keyboard and the mouse. It’s easier to use the keyboard when you are entering data (so your hands don’t have to leave the keyboard) and the mouse when you need to scroll a long way or you already have your hand on the mouse for another task.
Entering Text and Numbers Two types of data can be entered directly in cells in a worksheet: Numbers Values you may want to use in calculations, including dates and the conditions TRUE and FALSE, also stored as 0 and 1. Dates are often used in calculations to determine, for example, how many days to charge for an overdue video or how many months of interest you have earned on a deposit. Formulas, which are calculations, are a specific kind of number entry. Text
Any entry that isn’t a number.
You can also insert other data into worksheets, including maps, graphics, hyperlinks, text copied from Word documents, and more, but the process differs from entering numbers or text directly in a cell. To enter data in a cell, first activate the cell by clicking it. When you begin typing data in a cell, several things occur: • An insertion point appears in the cell. • The text you are entering appears in the cell and the formula bar. • The formula bar buttons are activated. If you make a mistake while entering data, click the Cancel Formula button (the red X to the left of the formula bar) to discard the entry you were making and turn off the formula bar buttons. You can also cancel an entry by pressing the Escape key on the keyboard. Clicking the Enter button (the green check mark) on the formula bar finishes the entry and turns off the formula bar buttons. Pressing the Enter key on the keyboard does the same thing but also moves the cell pointer down one cell. Tab finishes the
4002c02.qxd 7/17/01 1:33 PM Page 47
entry and moves one cell to the right. So if you are entering columns of data, the Enter key is more efficient than the Enter button.
NOTE
Some Excel features don’t work while you are entering data in a cell, even if they look like they’re enabled. You should always finish an entry by entering or canceling it before moving on to other tasks.
There is another way to finish an entry: simply move to another cell by clicking the cell or using the arrow keys. Before Excel switches the focus to the new cell, it finishes the entry in the current cell.
Saving Time with AutoComplete Excel has an AutoComplete feature, which keeps track of text entered in a column and can complete other entries in the same column. For example, if you have already typed Jones in cell A1 and then enter the letter J in uppercase or lowercase in A2, Excel automatically fills in ones to make Jones. If Jones is the correct text, simply finish the entry by pressing Enter, moving to another cell, or clicking the Enter button. If the AutoComplete entry is not correct, just continue entering the correct text to overwrite the AutoComplete entry. AutoComplete only works for text, not numbers.
AutoComplete is turned on by default. To turn it off or on, select Tools Options, choose the Edit tab, and select or clear the last check box on the tab: Enable AutoComplete For Cell Values.
NOTE
AutoComplete resets each time you leave a blank cell in a column. AutoComplete may seem annoying at first, but it’s worth getting used to, particularly when you’re entering columns of data with a lot of repetition: repeated department names, cities, states, or other such information. If your data doesn’t have many repeats, simply ignore AutoComplete and fully type each entry.
TIP
If you type the same entry many times in Excel or other Office applications, consider adding the entry to Office’s AutoCorrect list (Tools AutoCorrect Options). See “Using AutoCorrect” in Chapter 3 for more information.
47
PART
I Putting Excel 2002 to Work for You
Entering and Editing Cell Entries
4002c02.qxd 7/17/01 1:33 PM Page 48
48
CHAPTER 2 • Creating Excel Worksheets
Using Pick from List AutoComplete doesn’t kick in until you’ve entered text that’s unique. If, for example, you’re entering a list of state universities, you will need to type University of and at least one more character before Excel will automatically complete “University of Minnesota” or “University of Hawaii.” When entering similar entries in a column, use the Pick from List feature. Right-click in the cell, then choose Pick from List from the shortcut menu to expose the entire list of existing entries in the column. Select an entry from the list. The Pick From List list is only as wide as the column; if you have long entries, point to the right edge of the column header (the button with the column letter) and doubleclick to widen the column and the list. For more on column widths, see Chapter 3.
Revising Text and Numbers There are two ways to edit a cell: Type Over If you activate the cell and type a new entry, the old entry is replaced. This is the easiest way to change a number (for example, 15 to 17) or to replace text with a short word. Edit Portion If the original entry is long and requires only minor adjustment, you might prefer to edit it. Click the cell and edit the entry in the formula bar, or doubleclick the cell or press F2 to open the cell for editing and edit directly in the cell. When you are finished, press Enter or click the Enter button to complete the entry.
NOTE
If double-clicking a cell doesn’t open it for editing, the Edit Directly in Cell option is turned off. Choose Tools Options and select the Edit tab in the Options dialog box to view or change the current setting.
Deleting Cell Contents To delete the contents of a cell completely, activate the cell and then either press the Delete or Backspace key on the keyboard or right-click and choose Clear Contents from the shortcut menu. Don’t choose Delete from the shortcut menu—that command is used to delete the active cell, row, or column, not just the entry in the cell. If you’ve used other spreadsheet programs, you may be in the habit of deleting cell contents by pressing the spacebar to overwrite the contents. In Excel, cells with contents you can’t see (like a space) can cause problems later. For example, Excel’s default
4002c02.qxd 7/17/01 1:33 PM Page 49
print settings print all occupied cells–even those occupied with only a space. When you mean to delete the contents of a cell, don’t use the spacebar. If the cell is formatted, deleting the contents does not remove the formatting. To remove contents, formatting, or both, choose Edit Clear and select Contents, Formats, Comments, or All from the menu.
Selecting Multiple Cells In Excel, at least one cell is always selected with the cell pointer: the active cell. To select a range (a group of one or more cells), move the mouse pointer to the center of the first cell in the range. The mouse pointer shape should be the large plus symbol used for selecting. Hold down the mouse button, and drag to the last cell you want to select before releasing the mouse button.
NOTE
The first cell selected is included in the selection. It has a white fill because it’s the active cell.
To select all the cells in a column or row, click the column heading or row heading. To select multiple columns or rows, select one heading and drag to select the others. When you point to row or column heading to select them, the mouse pointer changes to a row or column selection arrow. To select the entire worksheet, click the Select All button, the gray rectangle at the upper-left corner of the worksheet above the row headings or press Ctrl+A (for All). If the cells, columns, or rows you want to select are noncontiguous (not next to each other), select one of the ranges you want to select, and then hold down the Ctrl key while selecting the others.
EXPERT TIP
To select all the cells until Excel hits a blank row and column, select any cell in the range, then press Ctrl+Shift+8.
A Word about Pointers You need to frequently examine the mouse pointer while working in Excel. A mouse movement of 1/32 inch is the difference between selecting, moving, and copying a cell, as shown in Table 2.2.
49
PART
I Putting Excel 2002 to Work for You
Entering and Editing Cell Entries
4002c02.qxd 7/17/01 1:33 PM Page 50
50
CHAPTER 2 • Creating Excel Worksheets
TABLE 2.2 Pointer
]
E x c e l Po i n t e r S h a p e s Point To
Use
Any inactive cell; the center of the active cell or range
Selecting cells
Any row heading
Selecting rows
Any column heading
Selecting columns
The right edge of any column heading
Adjusting column width
The lower edge of any row heading
Adjusting row height
The edge of the selected cell, range, or object
Moving the contents of selected cells, cell ranges, or objects such as clip art and charts
The fill handle in the lower right corner of the cell pointer
Filling (copying) cell entries
Using Find and Replace Find and Replace has been substantially improved in Excel 2002. You can find and replace across worksheets and specify formatting options in the search. To use Find or Replace in a range, select a range before you start the search to limit the search area. Otherwise, select any cell in a worksheet to search the entire worksheet. Choose Edit Find or Edit Replace to open the Find and Replace dialog box. Click the Options button to display additional options. We’ll look at the Replace tab in detail. With only one exception (which we’ll discuss shortly) the Find tab is a stripped down version of the Replace tab. The Replace tab, including options, is shown here:
4002c02.qxd 7/17/01 1:33 PM Page 51
In the Find What box, enter the string (text or numbers) that you want to search for. Recent searches are available from the drop-down list. You can use wildcards: the question mark (?) for a single character, or an asterisk (*) for one or more characters. Click the Options button to display advanced search options. To search for a specific format, click the Format button to open the Find Format dialog box and select format options or click the Format down arrow and select Choose Format from Cell:
Click on any cell that is formatted exactly like the cell you want to find. Or click a similarly formatted cell, then click the Format button and make adjustments in the Find Format dialog box. Use the drop-down lists and check boxes to set other Find options: • Set the search range in the Within control (Sheet or Workbook). • Set the search direction (By Rows or By Columns). By columns, which searches from top to bottom in column A before proceeding to column B, is usually faster than By Rows. • Set the Look In drop-down list to search in Formulas, Values (formula results), or Comments.
TIP
While you can find text in formulas, values, or comments, you can only replace in formulas. Formulas is the only choice in the Look In drop-down list on the Replace tab.
51
PART
I Putting Excel 2002 to Work for You
Entering and Editing Cell Entries
4002c02.qxd 7/17/01 1:33 PM Page 52
52
CHAPTER 2 • Creating Excel Worksheets
In the Replace With text box, enter replacement text or numbers. Click the Format button to apply formatting to the replacement characters. To replace an unformatted string with a formatted string, enter the same characters in the Find What and Replace With text boxes, and add Replace With formatting. To delete characters, enter the characters in the Find What text box and leave the Replace With text box blank. Excel begins searching at the active cell. To find the next occurrence of the Find What characters following the active cell, click Find Next. To find all occurrences, click Find All. Click Replace to replace the Find What text with the Replace With Text. Click Replace All to globally replace all occurrences of the Find What string with the Replace With string.
Working with Numbers You use a formula when you want to perform a calculation in Excel, so you’ll appreciate some of the new formula features built into Excel 2002. Formulas make a spreadsheet a spreadsheet—the driving force behind the magic of Excel. You don’t have to be a math major to use formulas, because Excel does the math correctly every time. Even if your checkbook never balances, you can use Excel’s formulas and your data to calculate totals, averages, and other results accurately, quickly, and easily. Excel uses standard computer operator symbols for mathematical and logical operators, as shown in Table 2.3.
TABLE 2.3
Mathematical and Logical Operators
Operation
Symbol
Addition
+
Subtraction
–
Multiplication
*
Division
/
Exponentiation (to the power of)
^
Precedence (do this operation first)
enclose in ( )
Equal to
=
Not equal to
(typed as two symbols)
Greater than
>
Less than
99999] will be true for nine-digit zip codes, so the format [>99999]00000-0000;00000 will format both ninedigit and five-digit zip codes correctly, including leading zeros.
NOTE
You can apply conditional formatting without creating a custom format. See the “Conditional Formatting” section in Chapter 12.
Codes for Dates and Times Use the format codes shown in Table 2.6 to create date and time formats. The m code is used for both months and minutes. Excel treats
71
PART
I Putting Excel 2002 to Work for You
Formatting Numbers
4002c02.qxd 7/17/01 1:33 PM Page 72
72
CHAPTER 2 • Creating Excel Worksheets
the m as a month code unless it appears directly after a code for hours or before a code for seconds.
TABLE 2.6
D a t e a n d Ti m e Fo r m a t C o d e s
Code
Use
Examples
m
Months as ##
Formats January as 1 and December as 12
mm
Months as 00
Formats January as 01 and December as 12
mmm
Months as three-letter abbreviation
Formats January as Jan
mmmm
Month name spelled out
Formats Jan as January
mmmmm
Month’s first letter
Formats January as J and December as D
d
Days as ##
Formats 1 as 1 and 31 as 31
dd
Days as 00
Formats 1 as 01 and 31 as 31
ddd
Days as weekday abbreviation
Formats 1/1/99 as Fri
dddd
Days as weekday
Formats 1/1/99 as Friday
yy
Years as 00
Formats 1999 as 99
yyyy
Years as 0000
Formats 1/1/99 as 1999
h, m, s
Hours, minutes, and seconds as ##
Formats 3 as 3
hh, mm, ss
Hours, minutes, and seconds as 00
Formats 3 as 03
AM/PM
12-hour clock, uppercase
h AM/PM formats 3:00 AM as 3 AM; h:mm AM/PM format 3 AM as 3:00 AM
am/pm
12-hour clock, lowercase
hh am/pm formats 3 as 03 am; h am/pm formats 3:00 AM as 3 am
a/p
12-hour clock, short form
hh:mm a/p formats 3:00 AM as 3:00 a
If you don’t include one of the versions of am/pm, Excel bases time on the 24-hour clock. The Gregorian calendar, the calendar used in the western hemisphere, replaced the Julian calendar in the fourteenth century. There are other calendars: Buddhist, used in Thailand, and Hijri, used in the Middle East. To format a date as a Gregorian date regardless of Locale selected in the Regional Options dialog box, type B1 at the beginning of the custom date format. If Arabic editing is enabled, type B2 before the format code to display the date as a Hijri date. For Buddhist dates, create the custom format d/m/bbbb.
4002c02.qxd 7/17/01 1:33 PM Page 73
TIP
There isn’t a “Julian date” format, probably because Julian dates aren’t really dates. If you need to convert Gregorian dates to what are commonly referred to as Julian dates, see “Creating Day of the Year (Julian) Dates” in Chapter 6.
Codes for Text To include text along with a number in a cell, put quotes around the text string or precede the text with a backslash (\). If you want to include a format for text entered in a cell, make it the final section in your format. The @ symbol stands for any text typed in the cell, so [BLUE]@ or simply [BLUE]formats text in the cell in blue. If you don’t include a text format, text entered in the cell is formatted according to the defaults or the formatting applied with the toolbar and Format Cells dialog box. Spacing Codes
You’ll use spacing codes for two reasons: alignment and filling. In some formats, negative numbers are surrounded by parentheses. If you use parentheses in a custom format, you need to add a space to the end of the positive format that will line up with the right parenthesis in a negative value. (This keeps the decimal points lined up.) To create a one-character space in a format, include an underscore: ##,##0.00_. You can fill any empty space in a cell by entering an asterisk (*) and then a fill character in the number format. For example, the accounting format begins with an underscore and a dollar sign, followed by an asterisk and a space before the digit placeholders: _$* #,##0.00. This ensures that the dollar sign is one space from the left edge of the cell, and that all the room between the dollar sign and digits is filled with spaces.
Previewing and Printing In Excel, Print Preview, Page Setup, Page Break Preview, and Print are all interrelated. Print Preview, Print, and Page Setup function much as they do in the other Office XP applications. Page Break Preview, a view available only in Excel, displays the current page breaks and allows you to adjust them.
Printing Your Worksheet When you click the Print button on the Standard toolbar, Excel prints one copy of the selected worksheet(s) using the current settings from the Print and Print Setup dialog boxes. To adjust print settings, choose File Print to open the Print dialog box, shown in Figure 2.10.
73
PART
I Putting Excel 2002 to Work for You
Previewing and Printing
4002c02.qxd 7/17/01 1:33 PM Page 74
74
CHAPTER 2 • Creating Excel Worksheets
FIGURE 2.10 Set print options in the Print dialog box
Use the Print Range controls to print some, but not all, of the pages of a multiplepage print job. In Excel, you cannot specify noncontiguous pages as you can in Word, so if you want to print pages 1–4 and 6–8, you either have to print twice or choose the cells on those pages and specify them as your print area. In the Print What control, specify which part of the worksheet or workbook you want to print. The Selection option provides another way to override the default print area; select the cells you want to print, and then print the selection. Choose Workbook to print every worksheet that has content in the active workbook. To print some, but not all, worksheets in a workbook, select the sheets before opening the Print dialog box. The Active Sheets option is selected in the Print What control. If your page header or footer includes page numbers, the worksheets are numbered consecutively in the order in which you selected them.
Using Print Preview Choose File Print Preview or click the Print Preview button on the Standard toolbar to preview the selected worksheets, as shown in Figure 2.11. Click the Zoom button or click in the previewed document to zoom in or out.
4002c02.qxd 7/17/01 1:33 PM Page 75
Previewing and Printing
FIGURE 2.11 Select Print Preview to examine the print job before sending it to the printer.
75
PART
Putting Excel 2002 to Work for You
I
Adjusting Margins in Print Preview Excel’s default margins are 0.75″ on each side and 1″ on the top and bottom, with a 0.5″ header and footer margin. Headers and footers print in 0.5″ of space between the header/footer margin and the regular margin. The top and bottom margins define the limits of the printed worksheet, and the header and footer margins define the areas where the header and footer print. If you use headers and footers, the top and bottom margin values need to be greater than the header and footer margin values, or part of the worksheet may print on top of the header and footer. Clicking the Margins button in Print Preview (File Print Preview) displays the current margin settings. Point to any of the margin lines, and the pointer changes to an adjustment tool, as shown in Figure 2.12. Press the mouse button to display the name and current setting for the margin on the Excel status bar. Drag a margin to adjust it.
4002c02.qxd 7/17/01 1:33 PM Page 76
76
CHAPTER 2 • Creating Excel Worksheets
FIGURE 2.12 Adjusting margins in Print Preview
Changing Page Setup To change page setup, choose File Page Setup from the menu bar to open the Page Setup dialog box. (If you’re already in Print Preview, click the Setup button; from Page Break Preview, right-click and choose Page Setup from the shortcut menu.) The Page Setup features are divided into four tabbed pages: Page, Margins, Header/ Footer, and Sheet.
Page Settings Use the Page options of the Page Setup dialog box, shown in Figure 2.13, to set page orientation, scaling, paper size, and print quality: 1. Open the Page Setup dialog box by choosing File Page Setup or by clicking the Setup button in the Print Preview window. Click the Page tab. 2. Change settings for Orientation, Scaling, Paper Size, Print Quality, or First Page Number. 3. Click OK to apply the settings.
FIGURE 2.13 Change page settings in the Page Setup dialog box
4002c02.qxd 7/17/01 1:33 PM Page 77
Orientation The direction of print in relation to the paper it is printed on. Portrait, the default setting, places the short edges of the paper at the top and bottom. If your worksheet is wider than it is long, consider using Landscape orientation. Scaling Used to reduce or enlarge the print. If you simply need to make the print larger, use the Adjust To control and choose a size greater than 100%. The Fit To control instructs Excel to reduce a worksheet that exceeds a specific number of pages so it will fit. Paper Size paper).
Lets you choose a paper size other than the default (for example, legal
Print Quality Measured in dots per inch (dpi). Higher dpi means clearer print quality, but slower printing. First Page Number
Used to start printing from a page number other than 1.
The Options button appears on every tab of the Page Setup dialog box. The button opens the Windows property sheet (or the manufacturer’s property sheet) for the printer that’s currently selected.
Setting Margins in the Page Setup Dialog Box The preview in the Margins page of the Page Setup dialog box (see Figure 2.14) displays the margins as light gray lines. You can change the margins by selecting the width or length in the appropriate box for each margin. FIGURE 2.14 Set margins, including space for headers and footers, on the Margins tab of the Page Setup dialog box
77
PART
I Putting Excel 2002 to Work for You
Previewing and Printing
4002c02.qxd 7/17/01 1:33 PM Page 78
78
CHAPTER 2 • Creating Excel Worksheets
Use the Center On Page controls to center the printed worksheet horizontally between the side margins or vertically between the top and bottom margins. As you change settings on the Margins tab, the Preview changes to reflect the new margin settings. Here are the steps for using the Margins tab to adjust page setup factors: 1. In the Page Setup dialog box, select the Margins tab. 2. Set the top, bottom, left, and right margins. 3. If you are using a header or footer, use the Header and Footer controls to set the distance from the edge of the page for the header and footer margins. 4. Use the Center On Page check boxes to center the printed worksheet. 5. Click the OK button to apply the changes.
Headers and Footers A header appears at the top of each page of a document. Footers are printed at the bottom of the page. The default setting is no header or footer. If you want a header or footer, choose or create it in the Header/Footer tab in the Page Setup dialog box, shown in Figure 2.15. FIGURE 2.15 Create page headers and footers on the Header/Footer tab of the Print Setup dialog box.
The current header and footer settings are displayed in the two preview panes. There are no default headers or footers in Excel 2002. To choose a header, click the Header drop-down list and select one of the listed headers. Select a footer the same way, using the Footer drop-down control. When you select a header (or footer) the preview pane reflects the change.
4002c02.qxd 7/17/01 1:33 PM Page 79
The headers and footers in the lists use information from Excel and Windows. The information is retrieved when you print, so if you select a header that says “Sheet 1” and then change the name of the worksheet, the new sheet name is printed in the header. The date and time are retrieved from Windows when you print the worksheet. Add or change headers and footers by the following these steps: 1. Choose File Page Setup from the menu bar, or click the Setup button in Print Preview. 2. In the Page Setup dialog box, select the Header/Footer tab. 3. Click the Header drop-down list and select a header, or click Custom Header to create a header. Click the Footer drop-down list and select a footer, or click Custom Footer to create a footer. 4. Press Enter (or click OK) to return to the Page Setup dialog box. Headers and footers are saved with a worksheet, so you can create different headers and footers for each worksheet in a workbook.
TIP
To assign the same header or footer to more than one worksheet, hold Shift and select the worksheets to group them before opening the Page Setup dialog box. After creating the header and footer, right-click any of the grouped worksheets and choose Ungroup from the shortcut menu.
To create a new header or footer, click the Custom Header or Custom Footer button to open a dialog box. The Header dialog box is shown in Figure 2.16. Both headers and footers have three sections that display information left justified, centered, or right justified on the page. FIGURE 2.16 Enter text and placeholders to create a header or footer.
79
PART
I Putting Excel 2002 to Work for You
Previewing and Printing
4002c02.qxd 7/17/01 1:33 PM Page 80
80
CHAPTER 2 • Creating Excel Worksheets
Click in one of the three sections then enter text and use the buttons (see Table 2.7) to add placeholders to create your header or footer.
TABLE 2.7 Button
E x c e l H e a d e r a n d Fo o t e r b u t t o n s Description
Font: used to format selected text and placeholders Page Number: inserts the page number Total Pages: inserts the number of pages in the printed document Date: inserts the system date Time: inserts the system time Path and File: inserts the path and filename for the workbook Filename: inserts the workbook’s filename Sheetname: inserts the name of the worksheet Picture: opens the Insert Picture dialog box Format Picture: opens the Format Picture dialog box for the picture in the active section
Here’s one of the subtle new features in Excel 2002: you can add graphics (for example, your company logo) to an Excel header or footer. You can place up to three graphics in a header or footer: one in each section. If you attempt to insert a picture in a section that already has a picture, you’re prompted to either keep or replace the existing picture. A placeholder &[Picture] is used to show the position of the picture in the header or footer. To see the picture, close the Page Setup dialog box and go to Print Preview.
Changing Sheet Settings The Sheet settings (see Figure 2.17) dictate the appearance of the printed worksheet, including the print area, repeating rows and columns, and gridlines.
4002c02.qxd 7/17/01 1:33 PM Page 81
Previewing and Printing
FIGURE 2.17 Use the Sheet settings to repeat rows or columns on each printed page.
81
PART
Putting Excel 2002 to Work for You
I
TIP
The Print Area, Rows to Repeat, and Columns to Repeat controls are only enabled when you open the Page Setup dialog box from the menu (File Page Setup or View Header and Footer). If you go to Page Setup from Print Preview or the Print dialog box, you won’t be able to change these three settings.
Print Area By default, Excel prints from the home cell A1 to the last occupied cell in a worksheet. To specify a different range, click the Collapse button in the Print Area text box to collapse the dialog box, select the area you want to print, then click the Expand button to expand the dialog box. If the Print Area includes noncontiguous cells, each contiguous range prints on a separate page.
NOTE
There’s a more direct way to set the print area. Select the range you want to print, then choose File Print Area Set Print Area. Choose File Print Area Clear Print Area to reset the print area.
Print Titles Repeats columns or rows on each page of the printout so that, for example, the worksheet title and column headings appear on every printed page. Specify these rows or columns in the Rows to Repeat at Top and Columns to Repeat at Left text boxes.
4002c02.qxd 7/17/01 1:33 PM Page 82
82
CHAPTER 2 • Creating Excel Worksheets
TIP Excel requires a range for these entries (such as 1:1 to print row 1 on the top of each page) even if you’re only using a single row or column. If you select the column or row in the worksheet, Excel enters it as a range.
Print or Hide Gridlines Indicates whether gridlines will be printed, but does not affect their display in the worksheet. Turning off the print gridlines gives your worksheet a cleaner appearance and can make it easier to read. To turn off screen gridlines, choose Tools Options and clear the check mark in the Gridlines option on the View page of the Options dialog box. Draft Quality
Prints the worksheet without gridlines or graphics.
Black and White Excel prints colors, including grays, in gray tones when you print on a black and white printer. If you won’t be printing in color, click this control to print colors and grays in black to speed up the print process. Row and Column Headings Prints the row numbers and column letters. This is a useful feature when you are editing or trying to locate an error in a worksheet. Page Order
Establishes the order in which multipage worksheets are printed.
Comments If the print area contains comments, you can choose to print them as they appear or on a separate page at the end of the print job. By default, comments are not displayed, so if you wish to print them as they appear, you’ll also need to show them. See Chapter 20, “Using Excel’s Workgroup Tools,” for more information on comments. Cell Errors As Used to hide error messages (for example #NAME and ####) in the printed version of the worksheet.
NOTE
For information on handling errors rather than just hiding them, see Chapter 19, “Solving Business Problems Using the Analysis Tools.”
It’s hard to select cells, rows, or columns with the Page Setup dialog box in the way. Any of the controls that require you to enter cell or range addresses have a Collapse Dialog button to minimize the dialog box while you select cells. This button is located on the Sheet tab in the Page Setup dialog box to the right of the Print Area, Rows to Repeat at Top, and Columns to Repeat at Left text boxes. Click the button to shrink the dialog box while you select cells, rows, or columns. Click the Expand Dialog button in the shrunken dialog box to return to the Print Setup dialog box.
4002c02.qxd 7/17/01 1:33 PM Page 83
Previewing and Printing
83
PART
Tips and Tricks for Printing When you are ready to print your worksheet, here are some tips that will help you print exactly what you want to see. To select the default print area of a worksheet so you can tell what will be printed without changing views, press Ctrl+Home to move to cell A1, then press Ctrl+Shift+End. If your printed copy includes extra pages that appear to have no content, you have a cell “out there” with something in it—a character, a space, or formatting (such as a fill). To quickly move to the last occupied cell in a worksheet, press Ctrl+End. To completely clear the contents of a cell, choose Edit Clear All. You’ve completely cleared all the cells you don’t want to print and Excel still prints blank pages. What gives? Try this trick to force Excel to reexamine the boundaries of the worksheet. Choose File Save As (not Save) from the menu, and save the file using the same name (or another name—it works either way). The easiest way to set the Print Area is from the worksheet, not from Print Setup. Select the cells to be printed and choose File Print Area Set Print Area from the menu bar. When you want to print the entire worksheet again, choose File Print Area Clear Print Area. You can set Page Setup options for multiple worksheets by selecting the worksheets before opening the Page Setup dialog box. Click on the sheet tab of the first worksheet you want to print. Hold down Shift and click the last sheet’s tab to select contiguous worksheets, or hold down the Ctrl key and click on the tabs of each of the worksheets you want to print. When worksheets are grouped, entries made on one worksheet are transferred to all the grouped worksheets. To ungroup the sheets, right-click on any of the grouped sheets’ tabs and choose Ungroup from the shortcut menu or click any sheet not included in the group. Remember to ungroup the worksheets after you’ve changed the Page Setup to avoid accidentally overwriting data on grouped sheets. For more on worksheet grouping, see Chapter 18, “Using Names and External References.” The Page Order setting on the Sheet tab of the Page Setup dialog box isn’t as useless as it initially appears to be. If your print area is at least two pages wide and two pages long, the Page Order determines which page will be numbered Page 2—the page below Page 1 or the page to the right of the Page 1.
Putting Excel 2002 to Work for You
I
4002c02.qxd 7/17/01 1:33 PM Page 84
84
CHAPTER 2 • Creating Excel Worksheets
Setting Print Options Excel offers flexible page breaks and print areas so you can manage the often-difficult task of printing unwieldy spreadsheets on standard-size paper. The Page Break Preview feature is a good tool for managing the printable areas of a spreadsheet, while the Print dialog box delivers complete control over which pages actually print.
Page Break Preview Page Break Preview is a view of the worksheet window that shows the print area, by page, and the page order. To turn on Page Break Preview, click the Page Break Preview button in Print Preview, or choose View Page Break Preview from the menu bar. A dialog box provides a brief explanation of Page Break Preview. In Page Break Preview, areas that will be printed are white; cells that won’t be printed are gray. Each printed page is numbered. You can quickly change the range to be printed by dragging the edge of the page break with your mouse to include or exclude cells. To view and adjust page breaks, follow these steps: 1. From the Print Preview window, click the Page Break Preview button; or choose View Page Break Preview from the worksheet window. 2. Using the mouse, drag the page break to print a larger or smaller number of rows or columns on the page. 3. Choose View Normal to close Page Break Preview. When you switch to Page Break Preview, you see how each page will print based on the current settings in the Print Setup dialog box. If you haven’t change the page setup, the print job is shown as it will appear if printed at 100 percent. If you extend the page break for any page (making it wider or longer than the default setting), Excel changes the scaling on all pages, reducing the print type so the page still fits on the paper specified in Page Setup.
Inserting Manual Page Breaks To add a manual page break, switch to Page Break Preview and select the first column or row that you want to appear in the page after the break. Right-click and choose Insert Page Break from the bottom section of the shortcut menu.
4002c02.qxd 7/17/01 1:33 PM Page 85
Previewing and Printing
85
PART
Putting Excel 2002 to Work for You
I
Removing Manual Page Breaks To remove a manual page break, right-click in the row below a horizontal page break or in the column to the right of a vertical page break and choose Remove Page Break from the shortcut menu. To remove all manual page breaks, right-click any cell and choose Reset All Page Breaks from the shortcut menu. In Page Break Preview, you can also remove a page break by dragging it outside the print area. To return to Normal view, choose View Normal from the menu bar.
4002c02.qxd 7/17/01 1:33 PM Page 86
This page intentionally left blank
4002c03.qxd 7/18/01 11:36 AM Page 87
CHAPTER
FORMATTING TEXT AND WORKSHEETS F E ATU R I NG
Formatting text
Aligning text
Applying borders and color
Creating and applying styles
Inserting and deleting rows, columns, and cells
Freezing and splitting
Hiding rows and columns
Checking spelling
Using AutoCorrect
3
4002c03.qxd 7/18/01 11:36 AM Page 88
his chapter starts with common Office formatting features, such as fonts and font styles, and moves quickly to Excel-specific features, including new features for Excel 2002, like Paste Options. If you’re an experienced Word or PowerPoint user, you’ll find much here that is familiar. Watch for the New icon that identifies features that are added or significantly enhanced in this version of Excel.
t
Formatting Text Even if you’ve never used Excel previously, you already have most of the skills you need to format text in Excel if you’ve worked in any Windows application. Before you can format cells, you must select them. To change font attributes, select the cells you want to format, then choose a formatting option from the Formatting toolbar. As you’ll see in this section, fonts, font styles (bold, italic, underline), font size, font colors, and the Format Painter work the same way in Excel as they do in Word and PowerPoint. If you want to format part of the text entry in a cell, it’s a bit trickier. As in Word, if you change a formatting option (for example, turn on bold) while entering text, the new format applies from that point forward. So if you want to bold the second word in a cell, type the first word, then turn on bold, then type the second word. To format the second word in an existing entry, open the cell for editing (double-click the cell) and select the word in the cell, or simply select the cell and select the text in the formula bar. Use buttons on the formatting toolbar, or choose Format Cells from the menu to display the Font page of the Format Cells dialog box. The formatting does not appear in the formula bar, which always shows the unformatted contents of a cell, but does appear in the active cell:
Changing Fonts To change fonts, select the cells or text you wish to format, then select a font from the Font list on the Formatting toolbar, or use the Font page of the Format Cells dialog box, shown in Figure 3.1. To reset cells to the default format, select the cells, open the Format Cells dialog box, and enable the Normal Font check box.
4002c03.qxd 7/18/01 11:36 AM Page 89
Formatting Text
FIGURE 3.1 Select a font, font size, color, and effects in the Format Cells dialog box.
89
PART
Putting Excel 2002 to Work for You
I
Aligning Text By default, Excel left-aligns text and right-aligns numbers. The default settings reflect common sense rules about worksheet construction: • Columns of text, including numeric text (such as item numbers and social security numbers), should be left-aligned because we’re used to reading left-aligned text. Columns with uniformly short text entries that don’t present much of a challenge to readers (for example, seat assignments: 4F, 3A, 20C) can be centered. • Columns of numbers should be kept in the default (right) alignment and formatted so that the decimal points align and numbers can be visually compared easily. • Column labels should appear over the contents of the column. If the column is filled with numbers, the label should be right-aligned or centered. Labels for text columns should be left-aligned or centered. Use the buttons on the Formatting toolbar to override the default alignments and align text and numbers at the left, center, or right within cells. Excel’s fourth alignment, called Merge and Center, merges selected cells into one cell and centers the contents of the top-left selected cell across the new merged cell. Worksheet titles are often merged and centered over the worksheet columns, but you can use this feature to label a group of rows with rotated text, as shown in Figure 3.2.
4002c03.qxd 7/18/01 11:36 AM Page 90
90
CHAPTER 3 • Formatting Text and Worksheets
FIGURE 3.2 Merge and center worksheet titles. Merge, center, and rotate labels for groups of rows.
To merge and center, select the cell that contains the text you want to center and the cells in the same row or column you want to merge across. Click the Merge and Center button. Excel only centers the text in the top-left cell of a selection, so if your worksheet’s title is in more than one row, merge and center each title row separately. In prior versions of Excel, merged cells were problematic. When you tried to select rows or columns that included one of the merged cells, the entire merged range was selected. In Excel 2002, merged cells are excluded from row and column selections, and must be explicitly selected. There are alignment options that don’t appear on the Formatting toolbar. To see all the alignment options, select the cells you want to format and choose Format Cells, or right-click and choose Format Cells from the shortcut menu to open the Format Cells dialog box. The Alignment tab of the Format Cells dialog box is shown in Figure 3.3. FIGURE 3.3 The Alignment tab of the Format Cells dialog box
4002c03.qxd 7/18/01 11:36 AM Page 91
Setting Horizontal and Vertical Alignment In addition to the left, center, and right alignments available on the Formatting toolbar, the Horizontal Alignment drop-down list includes Fill, Justify, and Distributed. • General is the default setting: text left, numbers right. • Fill copies the cell’s contents to fill the cell. This was often used in earlier versions of Excel to create underlines (by filling the minus or equals symbols), and is included for backward compatibility. • Use Justify to dynamically wrap the contents within the current column width and line up the right margin of text so that it looks like a newspaper column. When the column width changes, Excel wraps the text again. • Distributed adds spacing between words to spread a cell’s contents over the width of the cell and applies the Indent specified in the Indent box to both the left and right of the cell. Click the Justify Distributed check box to horizontally justify the distributed text. Changing the Vertical Alignment setting also alters how the text appears in the cell. The Distributed and Justify options are most often used for cells with rotated text. Top
Positions cell contents near the top of the cell.
Bottom Center
The default, positions text and numbers at the bottom of the cell. Floats the contents in the vertical middle of the cell.
Distributed Adds spacing to spread a cell’s contents over the width or height of the cell. If text requires more than one line, the final line is centered. Justify Vertically wraps the contents within the row height. If the text requires more than one line, the final line is aligned with the bottom of the cell.
Rotating Text Use the rotation tools to orient text vertically or to a specific orientation. Consider rotating column labels when you have wordy column headings for columns with relatively small values: for example, an attendance worksheet that uses dates to label columns, but has only single characters like P, A, or T in the columns.
91
PART
I Putting Excel 2002 to Work for You
Formatting Text
4002c03.qxd 7/18/01 11:36 AM Page 92
92
CHAPTER 3 • Formatting Text and Worksheets
These steps will guide you through the process: 1. Select the cell containing the words to be rotated, and then select Format Cells and click the Alignment tab in the Format Cells dialog box. Choose one of the following options: • To turn text vertically 180° so text reads from top to bottom, click the pane with the vertical word Text in it. • To rotate text to another orientation, either use the Degrees box or drag the Text indicator in the rotation tool. 2. Click OK to apply the rotation. Rotating text lets you create splashy column or row labels. Rotate and merge text to label a group of row labels like those shown previously in Figure 3.2.
Indenting Text Use the Indent box on the Alignment tab of the Format Cells dialog box, or the Increase Indent and Decrease Indent buttons on the Formatting toolbar to indent the text in selected cells. The indent is measured in characters. Each time you click a button it increases or decrease the indent one character.
NOTE
In other spreadsheet programs (and in Excel before Excel 2000) there were two workarounds used to “indent” cell contents in a table: entering headings in two columns and making the empty left column very narrow, or typing spaces before an entry to create a visual indent. Both workarounds create problems if you want to use Excel’s database features with the table.
Merge, Shrink to Fit, and Wrap Text If you want a vertical title to cross several rows, use these steps: 1. Select the title and the cells you want to merge it across. 2. Select Format Cells from the menu or right-click the selection and choose Format Cells from the shortcut menu to open the Format Cells dialog box. 3. Enable the Merge Cells check box in the Text Control section of the Alignment page. 4. Click OK to apply the changes.
4002c03.qxd 7/18/01 11:36 AM Page 93
Or you can span a vertical title over several rows by following these steps: 1. Select the title and the cells you wish to merge it across. 2. Click the Merge and Center button on the Formatting toolbar. 3. Optionally, click the Align Left or Align Right button to change the alignment in the merged cells. Shrink to Fit reduces the font size for selected cells so the contents fit. Wrap Text wraps the contents of a cell if it would exceed the cell’s boundaries. Both Shrink to Fit and Wrap Text use the current column width (see “Adjusting Column Width and Row Height” later in this chapter) to determine how much to shrink and where to where to wrap the selection. Follow these steps to apply shrink or wrap text control: 1. Adjust the column width. 2. Select the cell(s) you wish to format. 3. Choose Format Cells or right-click in the selection and choose Format Cells from the shortcut menu. 4. On the Alignment tab, enable either Shrink to Fit or Wrap Text. 5. Click OK. If you narrow or widen a column after you shrink or wrap a label, you may need to reshrink or rewrap the formatted cells.
EXPERT TIP
If you want the contents of a cell to wrap at a specific point regardless of the column width, force the text to wrap to the next line by pressing Alt+Enter when you enter the text. Alt+Enter inserts an invisible line break character and enables the Wrap Text check box, so if you edit the text to remove the line break, the text will wrap to the width of the column. There’s a minor disadvantage to this method: the entry occupies more height in the formula bar, so you can’t access the column headings when the cell is selected.
Setting Text Direction The text direction setting affects three different things: field alignment, reading order, and keyboard language. Left-to-right is the text direction for most languages. Rightto-left is the text direction for Hebrew, Arabic, Farsi, and a few other languages. Choose left-to-right or right-to-left to set the direction, or Context to have Excel determine the text direction based on the characters entered in the cell.
To set the global text direction for new entries, choose Tools Options and set the Text Direction on the International tab.
NOTE
93
PART
I Putting Excel 2002 to Work for You
Formatting Text
4002c03.qxd 7/18/01 11:36 AM Page 94
94
CHAPTER 3 • Formatting Text and Worksheets
Applying Borders and Color Effective use of borders and color makes worksheets easier to understand. A border is a line drawn around a cell or group of cells. Fill color is used to color the background of part of a worksheet; font color is the color applied to text. Simply bordering or applying a fill color to totals or other summary cells provides visual cues that users appreciate. If you don’t have access to a color printer, you might still want to use color in frequently used worksheets that you or other users work with on-screen or that you wish to publish to the Web. Color distinguishes worksheets that would otherwise look similar; for example, the background for the final budget could be pale yellow to distinguish it from the various preliminary versions. The Borders, Fill Color, and Font Color buttons are on the Formatting toolbar. All three buttons are combination buttons that include menus opened by clicking the down arrows attached to the buttons. Select an item from the menu to apply it to the selected cells and make it the default item for the button.
Borders can completely surround a group of cells, surround each cell individually, or provide an underline or double-underline of the selected range. (The double underline is often used to highlight grand totals in worksheets.) To apply a border, select the cells to be formatted, then click the Borders button down arrow and select a border to apply it to the cells and assign it as the default border. To apply the same border to other cells, select the cells, then click the Borders button. To change the border color for selected cells, choose Format Cells to open the Format Cells dialog box. On the Border tab, select a color from the Color drop-down list, then click the Preview window buttons to apply the border color to the selection. The Fill Color and Font Color buttons also have attached menus and are used the same way. Use these steps to add colors or borders to your work: 1. To apply a Font Color, Fill Color, or Border, select the cells to be formatted. 2. Click the down arrow on the Font Color, Fill Color, or Borders button. 3. Choose a color or border from the menu.
4002c03.qxd 7/18/01 11:36 AM Page 95
Formatting Text
95
PART
Working with the Border and Color Menus If you have a lot of borders, colors, or font colors to apply, you can display any or all of the button menus as palettes that float on your worksheet: 1. Click the arrow on the Borders, Fill Color, or Font Color button to open the menu. Point to the dark gray bar at the top of the menu. 2. Drag the menu into the worksheet and release the mouse button. 3. When you are finished with the menu, click its Close button. To add borders or color to noncontiguous ranges, select one range, then hold the Ctrl key and select the other ranges you want to apply the format to before clicking the Border, Fill Color, or Font Color button.
If you’re already formatting other cell properties or want to access the more scintillating options, set borders and colors in the Format Cells dialog box. Set font color on the Font tab, borders on the Border tab, and fill on the Pattern tab. The Borders tab of the Format Cells dialog box is shown in Figure 3.4. FIGURE 3.4 Set border properties including color on the Border tab of the Format Cells dialog box.
Putting Excel 2002 to Work for You
I
4002c03.qxd 7/18/01 11:36 AM Page 96
96
CHAPTER 3 • Formatting Text and Worksheets
The Border tab is a very flexible formatting tool. Choose a Style and Color in the Line section, then click one or more of the Presets buttons or Border buttons that frame the preview. Continue selecting and applying borders until the preview looks right. The borders are applied when you click OK. Patterns are one-color or two-color geometric fills. For a one-color fill, select a color from the palette, shown in Figure 3.5. FIGURE 3.5 Set fill colors and patterns on the Patterns tab.
For a two-color fill, click the Pattern drop-down list to open the menu.
Choose a pattern in the top half of the menu. To create a two-color fill, open the Pattern menu again and choose a color in the bottom half of the menu. The pattern is applied when you click OK to close the Format Cells dialog box.
4002c03.qxd 7/18/01 11:36 AM Page 97
NOTE
Only simple fills and patterns are available for cells. More complex fills, including textures and pictures, are available for charts.
Using the Format Painter The Format Painter copies all the formatting—font attributes, borders, colors, and conditional formatting—from a source cell to one or more target ranges. Follow these steps to use the Format Painter: 1. Select a cell or a range with formatting you wish to copy. 2. Click the Format Painter button. 3. Click on or drag over the cells you want to copy the formatting to. To copy formatting to several destination ranges, double-click the Format Painter button in step 2. The Format Painter stays on until you click it again to turn it off or until you start another task, such as entering text or formatting.
TIP
To simply repeat the last format applied, remember the shortcut keys. Press F4 or Ctrl+Y to repeat your last action.
Painting Formats from Ranges If you select more than one cell in step 1, the Format Painter copies the formatting from each of the selected cells. You can, for example, select cells A5:E5, click the Format Painter, and copy the formats to a multi-row range such as A6:E25. The formatting of cell A5 will be applied to the cells in column A; the formatting of B5 will be applied to the cells in column B, and so on.
Painting Column Widths To copy a column width, select the column heading then click the Format Painter button. Click another column’s heading to paste the column width setting.
97
PART
I Putting Excel 2002 to Work for You
Formatting Text
4002c03.qxd 7/18/01 11:36 AM Page 98
98
CHAPTER 3 • Formatting Text and Worksheets
Applying AutoFormats and Styles Excel 2002 comes with a set of canned worksheet designs that include designs for formal business, lists, and 3-D AutoFormats. The general AutoFormats are the format sets that have been around since Excel 97. A second set of AutoFormats is supplied for PivotTable reports and is only displayed when one or more cells of a pivot table are selected.
NOTE
See “Creating PivotTables and PivotCharts” in Chapter 14 for more information.
AutoFormats offer a quick way to apply a standard format to all or part of a worksheet. Before you AutoFormat, select the cells to be formatted. This usually includes all the text and numbers in the worksheet, but you may wish to apply an AutoFormat to titles or data only. Follow these steps to AutoFormat a worksheet: 1. Select the range of cells you wish to format. 2. Choose Format AutoFormat from the menu to open the AutoFormat dialog box, shown in Figure 3.6. 3. Click the Options button to expand the dialog box to display all the formatting elements you can apply. 4. Choose a format from the list of AutoFormats. 5. Deselect any formatting options you don’t want to include. 6. Click OK to apply the selected format.
Creating Styles AutoFormats are composed of styles: specifications about one or more formatting options. To save a style from formatted cells follow these steps: 1. Select a range of cells that includes the formatting you want to include in the style. 2. Choose Format Style from the menu bar to open the Style dialog box, shown in Figure 3.7. 3. Enter a name for the style. Deselect any formatting elements you wish to exclude.
4002c03.qxd 7/18/01 11:36 AM Page 99
Applying AutoFormats and Styles
FIGURE 3.6 Select an AutoFormat and set options.
99
PART
Putting Excel 2002 to Work for You
I
4. Click the Modify button to change format options in the Format Cells dialog box. Click OK to close the Format Cells dialog box. 5. Click Add to add the style. Click OK to close the Style dialog box.
FIGURE 3.7 Specify the style’s options in the Style dialog box.
Many users think styles are just for Word, and overlook their importance in Excel. Styles are particularly useful if you’re creating workbooks that others will use. Styles allow users to apply consistent, one-step formatting and can be applied programmatically with VBA (see Part VII, “Automating Excel 2002 with Macros and VBA,” and Appendix B, “VBA Quick Reference,” for more information on using Visual Basic).
4002c03.qxd 7/18/01 11:36 AM Page 100
100
CHAPTER 3 • Formatting Text and Worksheets
Applying Styles To apply a style, select the range you wish to format. Choose Format Style to open the Style dialog box. Select the style from the Style Name drop-down list and click OK to apply the style to the selected cells.
Modifying and Deleting Styles To modify a style, open the Style dialog box (Format Style) and choose the style in the Style Name drop-down list. Change any formatting options you wish, then click the Add button to update the style. Styles hang around forever unless you delete them. To delete a style, open the Style dialog box, select the style from the drop-down list, then click Delete.
Copying Styles between Workbooks If a style exists in any workbook, you don’t need to re-create it in other workbooks. All you need to do is open the workbook that includes the style, and in the workbook where you want to use the style, choose Format Style to open the Style dialog box. Click the Merge button to open the Merge Styles dialog box. Select the workbook that contains the styles you want to copy and click OK. All the styles from the source workbook are added to the current workbook. If the source workbook includes usercreated styles with the same name as user-created styles in the current workbook, you’ll be prompted to overwrite the current workbook’s styles during the merge.
TIP
The more you use and merge styles, the more you’ll value descriptive style names:
Budget Titles and Expense SubHeading instead of Titles or Headings.
To take advantage of merged styles, create a series of workbooks that contain your organization’s styles for worksheets. When you (or another user) are formatting a worksheet—for example, a budget—you begin by merging the budget styles into the budget you’re working with to get the appropriate style set. You could, of course,
4002c03.qxd 7/18/01 11:36 AM Page 101
begin creating the budget with a template that contains the correct formatting (see “Creating and Using Templates” in Chapter 14), but styles save the day if you forget to use the template or are working with documents originally created by another person who didn’t have access to the template.
NOTE
Merging styles has one drawback. You can’t select one or two styles from a workbook: you get at least all of the user-defined styles with names that aren’t already used in the current workbook.
Adjusting Worksheet Layout As your workbook grows, you’ll want to modify its layout so that it’s easier to use on screen as well as on paper or the Web. Excel’s column and row structure make it easy to radically change the appearance of a worksheet in a few simple steps.
Changing the Zoom If the size of your printed output is right but you need to see more or less of a worksheet on screen, use Zoom. Use the Zoom box on the Standard toolbar to change the worksheet display size. Click the drop-down arrow and select from the list, or enter another number to change the display (for example, enter 85 to zoom to 85%).
TIP
If you have an Intellimouse, hold the Ctrl key and rotate the wheel to zoom in or out in Excel.
Adjusting Column Width and Row Height By default, Excel columns are slightly more than eight characters wide. If the data in a worksheet is wider or much narrower than the column, you’ll want to adjust the column width so it is wide enough to contain the data, but not so wide that data seems lost. Some users simply leave blank columns rather than adjusting column widths: for example, skipping column B because the entries in column A are too wide for column A.
101
PART
I Putting Excel 2002 to Work for You
Adjusting Worksheet Layout
4002c03.qxd 7/18/01 11:36 AM Page 102
102
CHAPTER 3 • Formatting Text and Worksheets
TIP Don’t leave blank columns within a data table if you or anyone else may ever want to sort the data or use it as a data source with Word Mail Merge or import or link it from Access. In other words, if you want to take advantage of the functionality of Excel and Office XP, don’t leave blank columns in the middle of a data set. Blank columns and rows identify the limits of a database, so data on the “other side” of the blank column will not be sorted by Excel, mixing up the data. For more information on this, see “Sorting in Excel” in Chapter 15. You can adjust column width either manually, by dragging the column heading border, or by double-clicking to AutoFit the column width to the existing data. You can also select several columns and either adjust them manually to a uniform width or AutoFit each one to its contents. Here are the general steps: 1. Select the column(s) you want to adjust. 2. Position the mouse pointer at the right edge of one of the selected columns’ headings. The pointer changes shape to a double-headed column adjustment pointer. 3. Double-click to have Excel adjust the widths of the selected columns to fit their contents. Or, to adjust the columns manually to the same width, drag the right border of a column’s heading to make the column wider or narrower. If you prefer using the menu to set column widths, follow these steps: 1. Select the column(s) you want to adjust. 2. Choose Format Column AutoFit Selection to set all columns widths to fit the contents. Or Choose Format Column Width to open the Column Width dialog box. Enter a value from 0 to 255 to indicate how many characters can be displayed in the column width. Click OK. If the default column width doesn’t work for the worksheets in a workbook, change the default. Choose Format Column Standard Width and type a new value in the Standard Width dialog box. To copy a column width from one column to another, use the Format Painter, or click a cell in the column with the desired width and copy it. Select the destination column, right-click, and choose Paste Special from the shortcut menu or choose Paste Special from the Paste button menu to open the Paste Special dialog box. Choose the Column Widths option, then click OK.
4002c03.qxd 7/18/01 11:36 AM Page 103
Changing Row Height You can adjust row height the same way you adjust column width. If you move the pointer to the lower edge of a row heading, the pointer changes to an adjustment tool. Double-click to adjust the row height to fit the font size; drag to manually increase or decrease size. While it’s easy to adjust row height, it can add to your future work. By default, Excel changes a row’s height when you increase or decrease the font size used in the row. If you change the font size in a row you’ve previously adjusted, Excel will not adjust the row height—you’ll need to adjust it manually. Choose Format Row AutoFit to return responsibility for managing row height to Excel.
Inserting and Deleting Rows and Columns To insert a column between the current columns—for example, A and B—begin by selecting column B. Right-click and select Insert from the shortcut menu, or choose Insert Columns from the menu bar to insert a column. To insert multiple columns, select more than one column before inserting. For example, you can insert three columns to the right of column A by first selecting B, C, and D. Insert rows in the same fashion.
TIP
Hold Shift and press the spacebar to select the current cell’s row. Use Ctrl+Spacebar to select the column.
Deleting rows and columns is much like inserting. Begin by selecting one or more rows or columns. When you delete a row or column, all information in the row or column is deleted including cells in the column or row that are outside of the current display. To delete rows or columns, first select the rows or columns then choose Edit Delete from the menu bar, or right-click in the selection and choose Delete from the shortcut menu.
TIP Before deleting a presumably empty row or column, there’s a quick way to check to make sure it’s truly empty. Select any cell in a row, then hold the Ctrl key and press the right arrow key. If the row is empty, you’ll end up in column IV. Hold the Ctrl key and press the down arrow in an empty column, and the pointer will move to the cell in row 65536. Ctrl + Home takes you back to A1.
103
PART
I Putting Excel 2002 to Work for You
Adjusting Worksheet Layout
4002c03.qxd 7/18/01 11:36 AM Page 104
104
CHAPTER 3 • Formatting Text and Worksheets
To quickly insert or delete a single row or column, select the row or column heading by right-clicking and then select Insert or Delete from the shortcut menu. To clear the contents of a selected row but leave the emptied row in place, press the Delete key on your keyboard.
Freezing, Splitting, and Hiding At first glance, a worksheet is monolithic: cell after cell packed into wall-to-wall columns and floor-to-ceiling rows. The very size of a worksheet makes it difficult to compare values in cells unless they’re relatively close by or you’re a scrolling maniac. In Excel 2002, there are three tools to tackle this monolith and break it into smaller, even byte-sized pieces: Freezing Panes, Splitting Windows, and Hiding Rows and Columns.
Freezing Rows and Columns Freeze rows or columns so their contents are displayed no matter how far down or right you scroll in your worksheet. Locking down the titles that support the underlying data allows you to surf the worksheet while keeping the titles and data synchronized. You can freeze rows, columns, or both. To freeze rows or columns, but not both, follow these steps: 1. Select the first row or column that should not be frozen. Excel freezes above the selected row and to the left of the selected column. 2. Choose Window Freeze Panes from the menu. Follow these steps to freeze both rows and columns: 1. Select the first cell in the first column and row that should not be frozen. Excel freezes cells in rows above the selected cell and cells in columns to the left of the selected cell. 2. Choose Window Freeze Panes from the menu. You can navigate freely between the panes using the keyboard or mouse. To thaw things back out, choose Window Unfreeze Panes.
Splitting the Worksheet Window If you need to visually compare, for example, numbers in J100:J125 with numbers in AF16000:AF16025, freezing is useless because frozen panes are synchronized. Instead of freezing, use Split to separate the worksheet window into two windows, each with its own scroll bars and navigation so you can see two separate parts of the worksheet
4002c03.qxd 7/18/01 11:36 AM Page 105
next to each other and scroll one or the other, or both. Follow these steps to split the worksheet into two horizontal or vertical windows using the menu: 1. Select the first row or column that will appear below (or to the right of) the split. 2. Choose Window Split from the menu. To split the worksheet into four windows, follow these steps: 1. Select the cell that should be uppermost in the bottom-right window. 2. Choose Window Split from the menu. You can navigate freely between the panes using the mouse. Use the keyboard arrows to move within a window. Use F6 to jump back and forth between two windows or jump clockwise among four windows. To split windows using the mouse, point to the split box at the top of the vertical scroll bar or the right end of the horizontal scroll bar. When the pointer changes to the split pointer shape, drag the split bar to the left or down to split the window. To remove the split, choose Window Remove Split or drag the split bar from the middle of the worksheet window back to the top or right edge of the window.
Hiding Rows and Columns There are two reasons to hide rows or columns: the rows or columns have contents that you don’t want users to see or you simply want to help the user focus on the cells that have content. A knowledgeable user can unhide hidden rows and columns unless you protect the worksheet with a password (see “Hiding and Protecting Worksheets and Workbooks” in Chapter 14). To hide rows or columns, select the rows or columns and then do one of the following: • Right-click and choose Hide from the shortcut menu. • Choose Format Row Hide or Format Column Hide. • Press Ctrl+9 to hide rows or Ctrl+0 to hide columns. When Excel hides a row or column, the remaining rows and columns retain their original numbers. If, for example, the worksheet columns displayed are A, B, D, E, you can assume that column C is hidden. To unhide rows or columns, select the rows or columns below or to the right of the hidden row or column and then do one of the following: • Right-click and choose Unhide. • Choose Format Row Unhide or Format Column Unhide. • Press Ctrl+Shift+9 to unhide rows or Ctrl+Shift+0 to unhide columns.
105
PART
I Putting Excel 2002 to Work for You
Adjusting Worksheet Layout
4002c03.qxd 7/18/01 11:36 AM Page 106
106
CHAPTER 3 • Formatting Text and Worksheets
Inserting and Deleting Cells Sometimes you’ll need to add or delete cells in part of a worksheet without inserting or deleting entire rows or columns. Follow these steps to insert cells: 1. Select the range or the first cell where new cells should be inserted. 2. Right-click and choose Insert from the shortcut menu or press Ctrl+Shift+= to open the Insert dialog box.
3. If you choose Shift Cells Down, the cells in the selection and all cells below them in the same columns are shifted. If you choose Shift Cells Right, cells in the same rows are moved to the right. 4. Click OK to apply the selected action. To delete cells, select the range of cells you wish to delete, then right-click and choose Delete from the shortcut menu. Choose to shift cells up or to the left, then click OK. Notice that you can also use the Insert or Delete dialog boxes to insert or delete rows or columns.
TIP
The keyboard shortcut to insert cells is “Ctrl Plus”: Ctrl+Shift+= . “Ctrl Minus” (Ctrl+- ) deletes cells. If a cell or range of cells is selected, the Insert or Delete dialog box opens. If rows or columns are selected, Excel will insert or delete rows or columns.
Moving and Copying Cell Contents We assume that you’re comfortable moving and copying in Word or other Windows applications. There are a few differences you’ll notice when copying and moving cells and cell ranges in Excel. If you paste cells on top of existing data, the existing data will be overwritten. Before pasting, make sure that there are enough blank cells to accommodate the selection you want to paste. For example, if you want to move the contents of column E to the right of column A without overwriting column B, begin by inserting a blank column between A and B.
4002c03.qxd 7/18/01 11:36 AM Page 107
NOTE
To insert cells, see the preceding “Inserting and Deleting Cells” section.
Cut, Copy, and Paste Using the Clipboard Cut-and-paste and copy-and-paste now operate the same in Excel as in other Office applications. Thanks to the Office Clipboard, you can copy or cut a selection, perform other operations (such as inserting rows or columns), and paste later. Enhanced in Office XP, the Clipboard now saves the contents of up to 24 copy operations from any Office application, so you can copy or cut several selections, and then begin pasting. The Clipboard task pane opens automatically when you cut or copy more than one item without pasting. You can also choose Edit Office Clipboard to display the Clipboard. When you cut a cell in Excel, it is copied to the Clipboard but is not removed from the worksheet until you paste it in its new location by pressing Enter or clicking the Paste button.
TIP You can paste with Enter immediately after you copy, while the copied cells are highlighted and Select Destination and Press Enter or Choose Paste appears in the status bar. If you start another operation or press the Esc key, you can still paste the selection from the Clipboard task pane. When you get ready to paste, just click the first cell, row, or column where you want pasted cells, rows, or columns to appear. If you select more than one cell to paste into, the selected range must be exactly the same size as the range you want to paste. When you copy a selection, you can paste it more than once. Use the Paste button to paste all but the last copy. Press Enter to place the final pasted copy or press Escape to clear the copy selection if you’ve used Paste for the final operation. Follow these steps for simple cut, copy, and paste operations: 1. If you’re pasting into the middle of existing data, insert blank cells, rows, or columns for the data you want to move or copy. 2. Select the data you want to move or copy. To move, click the Cut button, choose Edit Cut, press Ctrl+X, or right-click the selection and choose Cut from the shortcut menu. To copy, click the Copy button, choose Edit Copy, press Ctrl+C, or select Copy from the shortcut menu.
107
PART
I Putting Excel 2002 to Work for You
Adjusting Worksheet Layout
4002c03.qxd 7/18/01 11:36 AM Page 108
108
CHAPTER 3 • Formatting Text and Worksheets
3. Select the first cell, row, or column where you want to place the moved or copied data. 4. Press Enter to move or copy the data to its new location. Even if you plan to paste only once, there’s a good reason to use Paste rather than simply pressing Enter. When you Paste, Excel displays a Paste Options button at the bottom of the pasted selection. Click the button to choose to copy Formatting Only, to retain column widths and formatting, or to match the pasted cells’ format to the format of the surrounding cells. To paste a specific item from the Clipboard task pane, click the item or point to the item, click the item’s down arrow to open the options menu, then choose Paste. To delete an item from the Clipboard, point to the item, open the item’s options menu, and choose Delete. To clear the entire Clipboard, click the Delete All button at the top of the task pane.
Keystrokes for Cut, Copy, and Paste
If you’ve browsed the Edit menu you know about the Office keyboard shortcuts: Ctrl+X to cut, Ctrl+C to copy, and Ctrl+V to paste. Here are some other useful keyboard shortcuts: Shift+Del to cut and Shift+Ins to paste; these shortcuts are recognized by Windows, so they often work in other applications that don’t support the Office shortcut keys. Ctrl+ ; to enter the current date. Ctrl+’ to exactly copy the contents from the cell directly above the active cell; if the copied contents is a formula, the formula references are not changed to reflect the formula’s new location. Ctrl+Shift+’ to copy the results of the formula from the cell directly above the active cell.
Data Transfers Between Worksheets
To move or copy data from one worksheet to another, cut or copy the selection and then click the sheet tab for the sheet that you want to paste into. Click in the cell in the upper-left corner of the destination range and press Enter to paste.
Data Transfers Between Workbooks
To move or copy data from one workbook to another, make sure both workbooks are open. Select and cut or copy the data, choose Window from the menu bar, and pick the destination workbook from the list of open workbooks. Click in the destination cell and press Enter. To paste previously copied contents from the Office Clipboard, select Edit Office Clipboard or hold the Ctrl key and press C twice. The Clipboard task pane opens, showing the items currently held on the Clipboard. Select an item then choose Paste from the item’s options menu or just click the item to paste it into the worksheet beginning at the active cell.
4002c03.qxd 7/18/01 11:36 AM Page 109
NOTE
For information on moving or copying worksheets from one workbook to another, see Chapter 4, “Using Names and External References.”
Using Drag-and-Drop When you’re moving or copying cells between worksheets or workbooks, it’s easiest to rely on the Clipboard or to use the Cut, Copy, and Paste buttons on the Standard toolbar. When you can see both the cells to be moved or copied and the destination on-screen without scrolling too far, the drag-and-drop method is even quicker and more efficient: 1. Select the cells and move the mouse so that it points to any part of the cell pointer except the fill handle. The mouse pointer will change to a four-headed move arrow. 2. Hold down the mouse button and drag the cells to their new location. To copy the cells, hold the Control button while you release the mouse button. In Excel 2002, drag and drop has been greatly enhanced to support some features previously reserved for Paste Special operations. You can access these advanced features by doing the following: 1. Select the cells to be moved or copied. Point to any part of the cell pointer except the fill handle. 2. Hold down the right mouse button and drag the cells to their new location. 3. Release the mouse button. A shortcut menu opens so you can select whether you want to move or copy the cells, copy formats only, copy values only, insert hyperlinks or links to the cells, shift the current cells and move, or shift the current cells and copy.
4. Choose the desired option from the menu.
109
PART
I Putting Excel 2002 to Work for You
Adjusting Worksheet Layout
4002c03.qxd 7/18/01 11:36 AM Page 110
110
CHAPTER 3 • Formatting Text and Worksheets
Using Paste Special With Paste Special, you can do the following: • Paste formats including or omitting borders • Paste comments • Quickly update a range of values by adding, subtracting, dividing or multiplying them by another number • Transpose columns of data to rows of data and vice versa • Convert a formula to a value • Paste a column of data while omitting blank cells While you can paste any of the items from the Office Clipboard by choosing Paste from the item’s menu in the task pane, Paste Special only pastes the last item cut or copied. Even if you delete newer items from the clipboard, Paste Special retains and pastes the last item cut or copied. If the last item was cut or copied from Excel, choosing Edit Paste Special or right-clicking and choosing Paste Special opens the Paste Special dialog box as shown in Figure 3.8. There are two sets of options buttons and two check boxes in the Paste Special dialog box. You can set both a Paste Option and an Operation option and enable either or both check boxes before clicking OK or Paste Link to paste. FIGURE 3.8 Use the Paste Special dialog box to paste and transform cell contents.
If the item was cut or copied from Word, PowerPoint, or any application other than Excel, you’ll see a different Paste Special dialog box, used for pasting non-Excel objects. This Paste Special dialog box is shown in Figure 3.9. See “Working with Objects” in Chapter 17 for information on using Paste Special with other applications.
4002c03.qxd 7/18/01 11:36 AM Page 111
Adjusting Worksheet Layout
FIGURE 3.9 This Paste Special dialog box appears when the data to be pasted is not native Excel data.
111
PART
Putting Excel 2002 to Work for You
I
Paste Special Paste Use the Paste options in the Paste Special dialog box (see Figure 3.8) to paste all or part of the information from or about a cell, as shown in Table 3.1.
TABLE3.1
Pa s t e O p t i o n s i n t h e Pa s t e S p e c i a l D i a l o g B o x
Option
Result
All
The same results as Paste
Formulas
Pastes the formula, but retains the destination formatting
Values
Pastes the result of a calculation rather than the formula
Formats
Pastes the format only; like using the Format Painter
Comments
Pastes comments from the cut or copied cells for worksheet documentation
Validation
Pastes data validation settings, input messages, and error alerts
All Except Borders
Pastes the contents and formatting other than borders so you can reuse a bordered formula (for example, a grand total) elsewhere in the row or column
Column Widths
Sets the column widths to match those of the copied columns; you can also do this using the Format Painter
Formulas and Number Formats
Pastes formulas and number formats only; does not paste borders, fonts, fills, comments, or validation
Values and Number Formats
Converts formulas to values and pastes values and number formats only
4002c03.qxd 7/18/01 11:36 AM Page 112
112
CHAPTER 3 • Formatting Text and Worksheets
The two values options, Values and Values and Number Formats, are used to convert formulas to values so you can delete the cells used in the formula and retain the results.
Calculating Without Formulas with Paste Special Use the Operations options to perform a calculation on a range of data. For example, you can multiply numbers by -1 to convert negative numbers to positive numbers, decrease every expense line in a budget by 20 percent, or multiply the ticket quantities 1 through 10 by the single-ticket price to calculate the total price for tickets at each quantity. To perform an operation follow these steps: 1. Copy the value (single cell) that you want to add, subtract, multiply, or divide a range of cells by. 2. Select the range of cells you want to perform the operation on. 3. Choose Edit Paste Special or right-click and choose Paste Special from the shortcut menu. 4. Choose the Values option and the math operation. 5. Click OK to apply the operation to the selected cells.
Transposing Data with Paste Special Transposition rotates the pasted data 90 degrees, turning rows into columns and columns into rows. Transposition is frequently used to convert a table of data entered in columns into row-based data so it can be sorted, filtered, and subtotaled using Excel’s database tools. In Figure 3.10, we received an employee worksheet with one employee per column (cells A3:J7). We selected the data and used the Paste Special transpose option to paste the data as shown in the figure. FIGURE 3.10 Use the Paste Special transpose option to rotate a data table.
4002c03.qxd 7/18/01 11:36 AM Page 113
Skipping Blanks Paste Special, like Paste, overwrites the contents of cells in the paste area. Enable the Skip Blanks check box to only overwrite the contents of destination cells if the source cell also has contents. You can use this feature to flatten out worksheets created in other applications or earlier versions of Excel, when users often placed data in two columns to provide a visual indent. Figure 3.11 shows a range of row labels before and after a Paste Special operation with the Skip Blanks check box enabled. FIGURE 3.11 Skip blanks to integrate two columns of data.
Correcting Worksheet Spelling Misspelled words automatically cast doubt on the accuracy of an entire worksheet. Excel includes two tools to help you correct spelling errors. AutoCorrect automatically fixes common typos and Spelling checks all the text in a worksheet to ensure that it is error-free.
Checking Spelling You can check spelling for a single cell, a range of cells, or an entire worksheet. To check a single cell, double-click the cell to open it for editing, then use Spelling. Excel will check the contents of the formula bar. To check spelling for a range, select the range before starting Spelling. To check the worksheet, select only one cell. If you are not in the home cell, A1, when you begin the spelling check for the entire worksheet, Excel will check from the active cell to the end of the worksheet, and then ask if it should return to the top of the worksheet and finish checking. When Spelling is complete, Excel will notify you that it has finished checking the entire sheet. Excel checks most, but not all, spelling in a worksheet. Spelling does not check: • Protected worksheets • Formulas • Text created with or resulting from a formula (such as a text string entered in a cell as the result of an IF formula)
113
PART
I Putting Excel 2002 to Work for You
Correcting Worksheet Spelling
4002c03.qxd 7/18/01 11:36 AM Page 114
114
CHAPTER 3 • Formatting Text and Worksheets
To start Spelling, click the Spelling button on the Standard toolbar, choose Tools Spelling, or press F7. The Spelling dialog box only appears if Excel locates a string that does not appear in the dictionary, so if the text in cells, comments, and charts is correct, you’ll be notified that the spelling check is complete.
TIP If the Office Assistant is displayed, the Spelling dialog boxes are displayed as Office Assistant alerts. To use Spelling without Clippit, either hide the Office Assistant or rightclick the Assistant, choose Options, and disable the Display Alerts check box on the Options tab of the Office Assistant dialog box. If Spelling finds a potentially misspelled word, the Spelling dialog box, shown in Figure 3.12, opens. FIGURE 3.12 Use Spelling to check spelling for a cell, range, or worksheet.
You have a number of ways of dealing with a word that isn’t in the Office dictionary: Ignore Once Ignore All
This option ignores the selected occurrence of the word. This option ignores all occurrences of the word in this worksheet.
4002c03.qxd 7/18/01 11:36 AM Page 115
Add to Dictionary This option adds the word to the Custom dictionary so Office will recognize it in the future. Change This option changes the word after choosing one of the suggested corrections or editing the word manually. Change All This option changes all occurrences of the word in this document after choosing one of the suggested corrections or editing the word manually. AutoCorrect This option corrects the word (after choosing or entering a correction) and adds it to the AutoCorrect dictionary. Spelling is a shared feature of all the Office XP applications, so words you add to the dictionary are added to the common custom dictionary you use with Excel, Word, PowerPoint, and Access. Spelling and AutoCorrect use separate dictionaries, so words added to AutoCorrect are not added to the custom dictionary.
Modifying Custom Dictionaries When you choose Add to Dictionary from the list of Spelling choices, the identified word is added to the default custom dictionary. The next time you type the word, Excel recognizes it and ignores it. Ever accidentally added a word that was misspelled? You can’t edit the dictionary in Excel, but you can do so in Word 2002. If you work in a field with lots of specialized terminology, you can save time and trouble by editing the custom dictionary directly in Word to make the specialty terms available in Excel as well as Word and PowerPoint. To access the dictionary and add new words or edit existing words, follow these steps: 1. Open Word. 2. Choose Tools Options and click the Spelling and Grammar tab. 3. Click Custom Dictionaries to open the Custom Dictionaries dialog box. 4. Select the dictionary you want to open and choose Modify. This opens a dialog box that contains a list of words already added to the dictionary. If none have been added, the list is blank. 5. To add a word, enter it in the Word field and click the Add button. 6. Remove words from the dictionary by selecting them from the list and clicking the Delete button. If there are misspelled words in the dictionary, delete them, then add them back in with the correct spelling. 7. Select another language from the Language drop-down list and add words in that language, if you wish. 8. When you have finished adding or editing words, click OK three times to close all dialog boxes.
115
PART
I Putting Excel 2002 to Work for You
Correcting Worksheet Spelling
4002c03.qxd 7/18/01 11:36 AM Page 116
116
CHAPTER 3 • Formatting Text and Worksheets
Using AutoCorrect AutoCorrect is the feature that changes “teh” into “the” and “adn” into “and” as you type. AutoCorrect maintains a dictionary of commonly mistyped words and when you mistype one, AutoCorrect fixes it automatically. AutoCorrect also handles keyboard shortcuts; for example, changing the keystrokes :) into a smiley face ☺ and (c) into the copyright symbol ©. AutoCorrect interacts with Automatic Language Detection so that corrections are appropriate to the language you’re typing in—or more accurately, the language Excel thinks you’re typing in. We have a worksheet where every word is in English, but Excel thinks part of it is in French, so we’re occasionally prompted to install additional support for French. Because some of the AutoCorrect changes can be less than unhelpful, you can turn these individual AutoCorrect options on and off as desired. Choose Tools AutoCorrect Options to open the AutoCorrect Options dialog box, shown in Figure 3.13.
FIGURE 3.13 AutoCorrect automatically corrects common typing mistakes and expands shortcut keystrokes.
4002c03.qxd 7/18/01 11:36 AM Page 117
NOTE
AutoCorrect is case sensitive. If text appears in the Replace column in uppercase, it must be entered in uppercase in Excel for AutoCorrect to replace it.
Although AutoCorrect is typically used to correct single words, you can use it to insert entire paragraphs or even longer segments of text. If, for example, you routinely label rows with difficult-to-spell technical terms or long alphanumeric account numbers, you could enter the terms into AutoCorrect and let Excel spell them for you. Just be careful to use a “Replace” word that you don’t typically type. Every time you type this word, Excel replaces the text with the AutoCorrect entry. AutoCorrect is designed to prevent typing and spelling errors, but it is also valuable as a shortcut tool. You can enter words that you type regularly into your AutoCorrect list to save yourself time and keystrokes—long company names, for example, or legal or medical terminology. Just enter a code that you will recognize, such as MI, and AutoCorrect expands it for you into Michigan. The AutoCorrect dictionary is used throughout Office XP, so items you add in Excel are also available in Word and PowerPoint. To add a word or phrase to the AutoCorrect dictionary, enter the text in the Replace and With text boxes in the AutoCorrect dialog box. In Figure 3.13, we’re creating an AutoCorrect entry so Excel will replace /toe with the words Total Expense. We’re starting the entry with a slash because the string /toe isn’t something we normally type, while toes are common—most of us have 10. You’ll also want to include a prefix if you think you will ever want to use the abbreviation without expanding it. For example, enter a hyphen or some other character in front of the abbreviation (-MI) when you create the AutoCorrect entry. Then you can choose whether to have AutoCorrect supply the long form (by typing -MI) or use the abbreviation by typing MI without the hyphen.
TIP
We use the slash symbol (/) as a prefix, but this requires changing an Excel transition option. By default, the slash symbol is used to open the Excel application menu so Lotus 1-2-3 users feel right at home. If you want to use the slash symbol at the beginning of AutoCorrect entries or any other entry, choose Tools Options to open the Options dialog box. On the Transition tab, delete the slash in the Microsoft Excel Menu or Help Key text box.
117
PART
I Putting Excel 2002 to Work for You
Correcting Worksheet Spelling
4002c03.qxd 7/18/01 11:36 AM Page 118
118
CHAPTER 3 • Formatting Text and Worksheets
Mastering Multilingual Editing As more businesses find themselves interacting on a global scale, it’s important to provide desktop applications with language tools for different languages. Excel 2002 supports editing in over 60 different languages or language variations. (All languages may not be available in your copy of Office XP. Information about Language Pack updates is available on the Microsoft website.) Excel will let you check the spelling and use AutoCorrect and display Help files, menus, and dialog boxes in a set of core languages. The Language Pack has its own setup files that are separate from the Office XP setup. To install and enable the multilingual features of Excel 2002, follow these steps: 1. Go to Add/Remove Programs in the Control Panel and choose Install. 2. Click Start Programs Microsoft Office Tools Microsoft Office Language Settings. You may be prompted to insert one of the Office XP CDs. 3. Select languages for menus, dialog boxes, and Help. 4. Click the Enabled Languages tab and select the languages you would like to be able to edit. Enable as many languages as you would like. 5. When you click OK or Apply, you are prompted to close and restart all open Office applications. If Excel recognizes text as being from a non-installed language, you’re prompted to install the appropriate language tools. With the appropriate dictionaries installed, you can run Spelling on a worksheet with text entries from multiple languages, and Excel will switch automatically to the correct language when it gets to that section.
4002c04.qxd 7/19/01 3:27 PM Page 119
CHAPTER
4
USING NAMES AND EXTERNAL REFERENCES F E ATU R I NG
Naming worksheets
Grouping worksheets to manage projects
Creating and naming ranges
Creating local names
Using names as constants
Linking workbooks
Inserting hyperlinks
Using smart tags
4002c04.qxd 7/19/01 3:27 PM Page 120
xcel is designed to help you manage complex projects with finesse. You can name cells or ranges and use the names both for navigation and in place of cell addresses in formulas, making your worksheets far more understandable and easier to update. But Excel 2002 doesn’t stop at the edges of a worksheet or workbook. With external file references, hyperlinks, and smart tags, Excel’s universe encompasses other workbooks, data sources, and the World Wide Web.
e
Working with Worksheets If you’ve moved to Excel from another spreadsheet program, you may not have realized what a powerful organizational tool an Excel workbook is. Some spreadsheet programs save each worksheet independently as a separate file, requiring you to open five or six files when you work on a large project. With Excel, you can cluster worksheets for similar projects in a single workbook so you can see and work with the entire project at one time. You can move through the various worksheets (Sheet1, Sheet2, and so on) associated with the project as easily as you flip through pages in this book. Simply click the worksheet’s sheet tab. To change a worksheet’s name to something more descriptive, double-click the sheet tab or right-click and choose Rename from the shortcut menu, type a new name of up to 32 characters, and press Enter.
You can change a sheet’s tab color to make it easier to differentiate sheets by consistently using, for example, specific colors for different departments or different quarters of the fiscal year. Right-click a sheet tab and choose Tab Color from the shortcut menu, or select the sheet and choose Format Sheet Tab Color from the menu to open the Format Tab Color dialog box. Select a color from the palette and click OK to apply the color to the tab.
TIP If you do not see any sheet tabs at the bottom of the application window, choose Tools Options and click the View tab. Enable the Sheet Tabs check box in the Window Options area. If the tabs are enabled, maximize the application window or scroll down to see the tabs.
4002c04.qxd 7/19/01 3:27 PM Page 121
Selecting Worksheets To select one worksheet, click its sheet tab. If you want to print more than one sheet or copy a couple of sheets into another workbook, you can easily select multiple worksheets: hold the Ctrl key while clicking the sheet tabs you want to select. To select several consecutive worksheets, click the first worksheet tab you want to select, hold Shift, and click the last tab. To select all worksheets in a workbook, right-click any tab and choose Select All Sheets from the shortcut menu.
Entering Common Data in Multiple Worksheets When more than one worksheet is selected, the worksheets are grouped. Data entered into one sheet is entered into all sheets in the group, making it possible to enter the title in cell A1 of a worksheet and have it appear in all worksheets in the workbook. It’s not unusual to need a number of worksheets with common formatting and data. For example, if you work with quarterly budgets, you might want to create a workbook with worksheets that contain the same column headings, row headings, and formulas. With Excel, there are two ways to do this: by grouping the worksheets and then entering the data and formulas common to all four sheets or by creating one worksheet and then copying it three times. Generally, it’s easier to create and copy the worksheets, as you’ll soon see. Grouping is most useful when the worksheets already exist and you need to enter the same information in the same cell on each sheet. Rather than enter a number in cell B16 on all four sheets, group them and enter the value on any one of the four sheets. You can use fill to copy cell contents across several sheets. Enter the data on the first sheet. Select the range you wish to fill, and then select the sheets you wish to copy the data to. Choose Edit Fill Across Worksheets. In the dialog box, choose All, Formats, or Contents and then click OK. Grouping is useful for more than data entry. You can format individual cells or ranges; set column widths and row heights; change print setup options including headers, footers, and print areas; and print grouped worksheets.
WARNING
Remember to ungroup worksheets immediately when you are finished entering, moving, or formatting common data. Otherwise, entries you make on one worksheet will be made on all worksheets, overwriting the existing entries on the other sheets in the group.
121
PART
I Putting Excel 2002 to Work for You
Working with Worksheets
4002c04.qxd 7/19/01 3:27 PM Page 122
122
CHAPTER 4 • Using Names and External References
Ungrouping Worksheets To ungroup worksheets, right-click any grouped worksheet and choose Ungroup Sheets from the shortcut menu, or click any worksheet in the workbook that is not included in the group.
TIP
To remove one or more sheets from the group while maintaining the rest of the group, hold Ctrl and click the tabs of the sheets to be ungrouped.
Copying and Moving Worksheets You can copy or move worksheets within and between workbooks. To move a worksheet (or worksheets) within a workbook, select the sheet tab (or tabs), drag the tab (or tabs) to the new location, marked by a small triangle just above the tab, and drop:
To copy a worksheet in the same workbook, hold the Ctrl key while dragging. The copy will have the same name as the original sheet, followed by the copy number.
Moving or copying between workbooks is a bit more complicated: 1. Open the workbook you want to move or copy to. You can switch between open workbooks by using the Excel’s Window menu or the Windows taskbar buttons. 2. Select the worksheet you want to copy, and then either choose Edit Move or Copy Sheet from the menu bar or right-click the sheet tab and choose Move or Copy from the shortcut menu. This opens the Move or Copy dialog box, shown in Figure 4.1. 3. In the To Book drop-down list, select the name of the open workbook to which you want to move or copy the sheet or choose New Book. 4. Select a Before Sheet option to determine where this sheet should appear in the other workbook. 5. To copy the worksheet, select the Create a Copy check box at the bottom of the dialog box before clicking OK.
4002c04.qxd 7/19/01 3:27 PM Page 123
Working with Worksheets
FIGURE 4.1 Use the Move or Copy dialog box to move sheets within and between workbooks.
123
PART
Putting Excel 2002 to Work for You
I
You can use this dialog box to move and copy worksheets within the same workbook if you prefer the dialog box to the drag-and-drop method.
Inserting and Deleting Worksheets To insert a new worksheet, right-click any sheet tab and choose Insert from the shortcut menu or choose Insert Worksheet from the menu bar. If you want to insert the default blank worksheet, it’s faster to use the menu bar. If you use the sheet tab shortcut menu, you’re prompted to choose from four sheet types: Worksheet Chart
The default type.
Used for a full-size chart object.
MS Excel 4.0 Macro Included for backward compatibility with macros written in the XLM macro language MS Excel 5.0 Dialog
Also included for compatibility with earlier versions.
When you insert a sheet from the shortcut menu, the Insert dialog box, shown in Figure 4.2, opens and prompts you to select the type of worksheet to add. If you select an uninstalled template from the Spreadsheet Solutions tab, you’ll be prompted to insert your Microsoft Office XP CD so the template can be installed. To delete one or more selected sheets, choose Edit Delete Sheet from the menu bar or right-click the sheet(s) and choose Delete from the shortcut menu. You’ll be prompted to confirm the deletion. Be careful here: you can’t use Undo to restore an accidentally deleted sheet.
4002c04.qxd 7/19/01 3:27 PM Page 124
124
CHAPTER 4 • Using Names and External References
FIGURE 4.2 To insert a specific type of worksheet, right-click a sheet tab and choose Insert. Select the worksheet from the dialog box.
TIP
If you frequently find yourself adding sheets to workbooks, increase the default number of sheets in a new book. Select Tools Options from the menu bar, and change the Sheets in New Workbook setting on the General page of the Options dialog box.
Naming Ranges A name is an alias for a cell or range of cells (or a constant or calculation, which we’ll discuss later in this chapter). Names provide multiple benefits, which become more important as you create increasingly complex workbooks: • Names can be used in formulas and are easier to remember than cell addresses. • When a range moves within the sheet, the name moves with it. • You can use a name in place of a cell or range address in a formula or function argument. • Names identify the cell’s contents: PayRate, TotalSales, and Quantity are more descriptive formula references than cell addresses. • When you copy a formula that uses a name, the effect is the same as using an absolute cell reference (see Chapter 5, “Calculating with Functions”).
4002c04.qxd 7/19/01 3:27 PM Page 125
The rules for using range names include the following: • Names can be up to 255 characters long and can include letters, numbers, underscores, or periods. • The name must begin with either a letter or the underscore character. • You cannot use spaces, commas, exclamation points, or other special characters. • Names cannot be valid cell addresses: FY2001 cannot be used as a name, but FYr2001 can be. • Names are not case sensitive: INTERESTRATE and InterestRate are the same name. • A name must be unique within a workbook; you can’t use the same name on two different sheets. (See “Creating the Same Name in Multiple Worksheets” for a creative way to stretch this rule.) The tradition is to mix uppercase and lowercase letters, beginning each word within the name with an uppercase letter: InterestRate. Excel lets you assign names that might be disallowed in many programs. For example, you can assign the names of program features like cell, column, and row to cells or cell ranges. You’re also allowed to assign names that are the names of functions: SUM, COUNT, and so on. To avoid confusion, you probably shouldn’t do this, even though Excel allows it. There are three ways to name a range: • Use the Name box to the left of the formula bar. • Use the Define Name dialog box. • Create names from a row or column of labels.
Naming a Range Using the Name Box Using the Name box at the left end of the formula bar is the easiest way to name ranges: 1. Select the range to be named; hold the Ctrl key if you need to select noncontiguous cells. 2. Click in the Name box. 3. Type a valid name for the range and press Enter. You must press Enter to create the name; you can’t simply click in another cell. Click the drop-down arrow in the Name box to open a list of the named ranges in your workbook.
125
PART
I Putting Excel 2002 to Work for You
Naming Ranges
4002c04.qxd 7/19/01 3:27 PM Page 126
126
CHAPTER 4 • Using Names and External References
Using the Define Name Dialog Box The Define Name dialog box, shown in Figure 4.3, provides another way to name ranges, and it is the only place you can change or delete existing range names. The dialog box displays a list of the names already defined in the active workbook. Here are the steps for defining a range name using the dialog box: 1. Select the range of cells you want to name. 2. Choose Insert Name Define from the menu bar. 3. Type a name for the range in the Names in Workbook text box and click Add. 4. Click OK to close the dialog box.
FIGURE 4.3 In the Define Name dialog box, you can define, delete, or edit a range name.
Editing a name or the range referred to by a name is equally easy. First, choose Insert Name Define to open the Define Name dialog box. • To change the name used to refer to a range of cells, select the name from the list of named ranges. Then select the name in the Names in Workbook text box, overtype the old name with the new name, and click Add. Select and delete the old name. • To change the cells referred to by a name, select the name from the list of names. Select the range in the Refers To text box. Select the correct range of cells in the worksheet (you can click the Collapse button in the Refers To text box to hide the dialog box), and then click Add. To delete a name, select the name from the Names in Workbook list and click the Delete button.
TIP Names are very persistent. When you delete a sheet that contains named ranges, Excel does not delete the names. They won’t appear on the Name box drop-down list, but they’re still hanging around. Open the Define Names dialog box to delete the names.
4002c04.qxd 7/19/01 3:27 PM Page 127
In Chapter 2, “Creating Excel Worksheets,” we discussed using row and column labels in formulas. You can enable and use natural language formulas, but names are just as convenient and more reliable. If you need to know what cells are included in a name, you can find out in the Define Name dialog box. With row or column label references, however, there is no direct way to determine which cells are included in the reference. Excel takes its best guess as to what cells to include, and it is sometimes incorrect.
Creating Names from a Row or Column You can define a group of labels in a row or a column at one time using the Create Names dialog box, shown in Figure 4.4. FIGURE 4.4 Create names from labels in the Create Names dialog box.
1. Select the range to be named. Include the cells you want to use as names as either the top or bottom row, or the first or last column selected. 2. Choose Insert Name Create from the menu bar to open the Create Names dialog box. 3. In the Create Names In area, select the row(s), Top or Bottom, or column(s), Left or Right, that contains the labels you want to use to name the selected range. 4. Click OK to apply the names and close the dialog box.
How Excel Creates Range Names from Labels Excel edits text as needed to make valid names. Excel uses these standards to generate names from labels or other text: • If the label for a column or row contains spaces, Excel will replace the space with an underscore: Interest_Rate. • If the cell contents begin with a number, like 8-Mar or 4 bags, Excel will add an underscore to the beginning of the name: _8-Mar or _4_bags.
127
PART
I Putting Excel 2002 to Work for You
Naming Ranges
4002c04.qxd 7/19/01 3:27 PM Page 128
128
CHAPTER 4 • Using Names and External References
• Excel will not create a name for a cell that contains only a number (like 1998, 78, or 1254.50). Excel will let you go through the motions, but it won’t create the names.
TIP
After creating names, open the Define Names dialog box and create new names that do not include underscores within the name.
Using Names After you’ve defined a range, you can enter the range name anywhere a regular cell reference is valid. For example, you can enter the name of a range as an argument for a function: =SUM(Totals) to add the cells in the range named Totals. To insert a name in a formula, type the name or choose Insert Name Paste from the menu to open the Paste Names dialog box.
Select the name from the list and click OK to paste the name into the formula. If you select the named cells or range, Excel will change the cell reference to the range name. If you fill or copy the formula that contains a name, the name is not changed in the pasted or filled cells. In Excel, range names are always absolute.
TIP
If you don’t want Excel to convert the cell or range address to a name, type the cell address rather than selecting the cells for the formula.
Names also serve a valuable navigation function in large workbooks and complex worksheets. To move to and select a named range anywhere in a workbook, click the drop-down arrow in the Name box and select the name from the list.
4002c04.qxd 7/19/01 3:27 PM Page 129
Names created from column and row labels can be used to refer to specific cells at the intersection of the named row and column. In the Undiscovered Country worksheet shown in Figure 4.5, the range A6:E6 is named LasVegas. June refers to D6:D10. The formula =LasVegas June will return the value (41) at the intersection of the two ranges: cell D6. FIGURE 4.5 A formula in this worksheet uses names to return the value at the intersection of row 6 (LasVegas) and column D (June).
TIP
To list all the names in the active workbook and the cells they refer to, go to an empty area of a worksheet and open the Paste Name dialog box. Click the Paste List button.
Stretching Names to the Max Names are incredibly versatile. In this section, we’ll create less traditional names: External Names 3D Range Names Local Names
Names that refer to ranges in other workbooks. Names that cross multiple sheets.
Names that repeat within a book.
Constant Names
Names that refer to values rather than ranges.
Creating Names That Refer to Other Workbooks You can use the Define Name dialog box to create names that refer to cells in any open workbook. For example, you may want to refer to a workbook that includes sales and expense totals for the third quarter. Rather than copy or link to these figures
129
PART
I Putting Excel 2002 to Work for You
Using Names
4002c04.qxd 7/19/01 3:27 PM Page 130
130
CHAPTER 4 • Using Names and External References
in your annual sales workbook, you can create names (Total3rdSales, Total3rdExpenses) that refer to them. When you refer to a cell in another workbook, the reference is an external reference. You name external ranges as you would name ranges in the current workbook, then use the names as external references in formulas. To name a range in another workbook for use in the current workbook, follow these steps: 1. Open both workbooks. 2. Switch to the workbook where you want to create the name. 3. Open the Define Names dialog box (Insert Name Define). 4. Type a name for the reference in the Names in Workbook text box. 5. Click in the Refers To text box. Click the Collapse button. 6. Use the Window menu to switch to the workbook that contains the range you want to name. 7. Select the range you want to name. 8. Click the Expand button to expand the Define Names dialog box. 9. Click Add to create the range name. External ranges don’t appear on the Names drop-down list in the active workbook, but you can use them in formulas as you would internal named ranges. Type the range name or choose Insert Name Paste to paste the named range into a formula. There is a potential downside—if the other workbook is deleted, moved, or renamed, Excel won’t be able to find the named range.
Creating Names That Span Worksheets A 3D name refers to the same cell in more than one worksheet in a book. For example, in a budget workbook the total sales figure is always in cell D87 of each worksheet. You can create a 3D name that refers to D87 across multiple worksheets. Follow these steps to define a 3D range name: 1. Choose Insert Name Define from the menu bar. 2. In the Names in Workbook text box, type the range name. 3. Delete any reference in the Refers To text box, and type =. 4. Click the tab for the first worksheet you want to reference, hold Shift, and select the tab for the last worksheet to be referenced. 5. Select the cell or range to be named. 6. Click Add to add the name, and click OK to close the dialog box.
4002c04.qxd 7/19/01 3:27 PM Page 131
While 3D range names have a limited navigation use, they’re very useful in summary formulas for workbooks that contain a series of periodic worksheets.
Creating the Same Name in Multiple Worksheets By default, names have workbook scope: they’re available anywhere in the workbook. If, for example, you create the name LasVegas on Sheet1, you can refer to LasVegas in a formula on Sheet2. Therefore, you can’t also name a range of cells on Sheet2 LasVegas. It takes only a bit more effort to create names with worksheet scope, allowing you to use, for example, the name LasVegas to describe a similar range of cells that appears on all four sheets in a workbook. Names with worksheet (local) scope are called local names or worksheet names. Follow these steps to define a name with local scope: 1. Select the worksheet that you want to create the name in. 2. Select the cells you want to name. 3. Choose Insert Name Define to open the Define Name dialog box. 4. In the Names in Workbook text box, enter the sheet name, an exclamation point, and the range name. For example, to name a range LasVegas on Sheet1, enter =Sheet1!LasVegas. If the sheet name includes a space, put single quote marks around the sheet name: =’Jan Sales’!LasVegas. 5. Click Add. 6. Close the Define Name dialog box. You can have global and local names that are the same. In our workbook (see Figure 4.5), we have three similarly named ranges: • A range in the Summary worksheet named LasVegas • A range in the 1st Qtr Sales worksheet named ‘1st Qtr Sales’!LasVegas • A range in the 2nd Qtr Sales worksheet named ‘2nd Qtr Sales’!LasVegas The range name LasVegas appears on the drop-down list in the Name box only once. That single reference always refers to the appropriate named range: the local name if there is one or the global name if there is no local name. For example, when the 1st Qtr Sales or 2nd Qtr Sales sheets are active, LasVegas refers to the local name. Select LasVegas from the Names list, and the locally named range is selected. When any other worksheet is selected, choose LasVegas from the Names list and Excel switches to the Summary worksheet and selects the global LasVegas range.
131
PART
I Putting Excel 2002 to Work for You
Using Names
4002c04.qxd 7/19/01 3:27 PM Page 132
132
CHAPTER 4 • Using Names and External References
TIP If you copy a sheet that includes a named range, Excel creates a local version of the same name, resulting in extra local names. The extra names can create problems in formulas later. Switch to the copied worksheet and open the Define Names dialog box to delete the extra names. Local names allow you to create brief names that still work in formulas. In our workbook, we have three choices: use names only on one sheet, use local names, or get creative with the names we create (using names like LasVegasQ1, LasVegasQ2, and so on). Local names are much easier to work with. If you type a range name into a formula or use the Paste Name dialog box, the same rules apply. However, you can use a local name in a formula in other worksheets if you enter the entire name, including the sheet name. For example, Sheet1!LasVegas always refers to the LasVegas-named range on worksheet Sheet1.
NOTE
When you list range names by clicking Paste List in the Paste Name dialog box, the list excludes local names except those on the active sheet.
Using Names to Store Constants Most users know about naming cells, but don’t realize that you can use the Define Name box to name constants as well as cell ranges. Why is this useful? Rather than entering values for fixed items like markups, interest rates, or hourly rates in worksheet cells where they’re visible and accessible, you can enter them as named items where they’re accessible but less visible. To create a named constant, choose Insert Name Define to open the Define Names dialog box. Enter a name in the Named in Workbook text box. In the Refers To text box, type an = and then the constant. Click Add. In Figure 4.6, we’re creating a constant named Markup that’s 15%. Named constants can include calculations. For example, =10% * 45 is a valid Refers To entry, which makes names a great way to embed business logic and rules in a worksheet. One more advantage to named constants: if we need to change the markup used throughout a workbook, we only need to change it in one place.
4002c04.qxd 7/19/01 3:27 PM Page 133
Linking to Other Data
FIGURE 4.6 Use the Define Name dialog box to create constants that can be used throughout a workbook.
133
PART
Putting Excel 2002 to Work for You
I
Using Names to Store User-Defined Functions
Let’s take names one step further. You can include functions in named ranges. For example, the following formula takes the year entered by a user in cell B3 on Sheet2 and returns the date for the first day of the year: =DATE(Sheet2!$B$3,1,1). You can enter this formula in the Refers To text box and name it YearStart or something similar, then use it in a formula wherever you need to in the workbook instead of performing the calculation each time you need it. The date and text functions are discussed in Chapter 6, “Manipulating Text and Dates.”
EXPERT TIP
There’s an easy trick you can use to view the named ranges in a worksheet: change the zoom to 25%, or any zoom less than 40%, and Excel displays the range names in the worksheet like watermarks.
Linking to Other Data A link is a reference to a cell or range in another workbook. Links are commonly used to avoid double-entering workbook information. For example, say you work in a company where departments are responsible for their own budgets. As the time to finalize the coming year’s budget approaches, each manager is working furiously on his or her budget. The vice president for finance has a master budget that summarizes the department budgets. It’s not practical to put all the department worksheets and the master budget in one large workbook if a few dozen people need to use the workbook at the same time.
4002c04.qxd 7/19/01 3:27 PM Page 134
134
CHAPTER 4 • Using Names and External References
If the managers link the workbooks together, they won’t have to fight with each other or with the vice president over whose turn it is to work with the budget. (Experience indicates that the vice president almost always wins.) The vice president’s workbook will include links to cells in the departmental budget workbooks. As the department managers change their numbers, the changes can be automatically reflected in the vice president’s master budget workbook so the managers and the VP are all working with the most current data. Each link establishes a relationship between two workbooks. The vice president’s workbook is called the dependent workbook, because each value there depends on a value in another workbook, which is called the source workbook. There are two ways to create a link: by using an open workbook as a source or by referring to the path to the workbook’s location. The first method is much easier to use. It’s the same as creating any other reference in a formula, but you need to switch to the source workbook before selecting the cell to reference in the formula. Before creating the formula that includes a link, open the source workbook. Then, in the dependent workbook, begin entering the formula with an equal sign (=). At the point in the formula where you want to include a cell reference from the source workbook, choose Window on the menu bar and select the source workbook. Click on the cell that you want to reference, and it will be included. Notice that the cell reference includes the workbook and worksheet names as well as the cell address:
You may prefer to arrange the source and dependent workbooks so that you can see the “result” cell and the cell to be referenced at the same time. With both workbooks open, choose Window Arrange to open the Arrange Windows dialog box. Choose how you want the open workbooks arranged, and then use each workbook window’s sizing tool to further size and arrange the windows.
TIP
You can arrange copies of a single workbook so you can work in different parts of the workbook in separate windows. Choose Window New Window and then open the Arrange Windows dialog box and arrange the windows using the Windows of Active Workbook check box.
If the workbook is not open, you must provide all the information that Excel needs to find the source workbook, including the full path. For example, if you want to refer to cell D4 in the Sales sheet of the Proposed Dept. Budget workbook, which is stored
4002c04.qxd 7/19/01 3:27 PM Page 135
in the Sales Management folder on the C drive, the reference would be ‘C:\Sales Management\[Proposed Dept. Budget.xls]Sales’!D4. There are many places to make a mistake when typing an entry like this. Try to create links with open source workbooks whenever possible.
Linking with Paste Link If you simply want to include a cell from another workbook (as opposed to using it in a formula), create a link by copying and paste-linking. Open both workbooks, then select and copy the cell(s) from the source workbook. Then you can do any of the following: • Activate the destination workbook, and choose Edit Paste Special from the menu bar, or right-click and choose Paste Special from the shortcut menu to open the Paste Special dialog box. Click the Paste Link button to create the link. • Choose Paste Link from the Paste button’s drop-down menu. • Right-click and choose Paste from the shortcut menu. After Excel pastes the selection, click the Paste Options drop-down list and choose Link Cells to create the link.
Working with Links When you open the dependent workbook and the source workbook is not open, Excel will ask if you want to update the links. If both workbooks are open, changes in the source workbook are automatically updated in the dependent workbook. If the source workbook can be opened by other users, however, they can be making changes to that workbook while you are working with the dependent workbook. In this case, the links will not be updated automatically; you have to instruct Excel to update the links.
135
PART
I Putting Excel 2002 to Work for You
Linking to Other Data
4002c04.qxd 7/19/01 3:27 PM Page 136
136
CHAPTER 4 • Using Names and External References
TIP For information on linking from other Office XP applications, see Chapter 16, “Using Excel 2002 with Other Databases.” See Chapter 18, “Using Excel 2002 With the Web,” for information on linking to web data sources.
Checking on Your Links With the dependent workbook open, choose Edit Links to open the Edit Links dialog box, shown in Figure 4.7. Scroll the Source list to see the attributes of each link in the workbook: Source
The file that the link points to.
Type The source type (for example, a worksheet, Word document, or PowerPoint slide). Update
A for Automatic update, M for Manual update.
Status Unknown or Open for Excel workbooks; not applicable for non-Excel sources. From the Source list, choose the source workbook that you want to check. Click the Check Status button to verify links. FIGURE 4.7 Use the Edit Links dialog box to monitor and update links.
NOTE
Two very specific types of links are not listed in the dialog box: links in web queries that contain parameters and links in names that are not used in any workbook formula.
4002c04.qxd 7/19/01 3:27 PM Page 137
Updating Links To update links in open workbooks, select the workbooks you want to update. Click the Update Values button to update the dependent workbook with information from the latest saved version of the source.
Viewing Link Sources To open the source for a link, select the source you want to open then click the Open Source button. If the source is already open, you’ll be advised that opening the source may result in the loss of data.
Changing the Source for a Link If you move or rename a data source, click the Change Source button to locate the data source and repair broken links.
Breaking Links Click the Break Links button to replace the link with the last known value for the linked cells.
Setting the Startup Prompt By default, users who open a workbook with links are asked whether they want to refresh the links. Click the Startup Prompt button to open the Startup Prompt dialog box and override the default to force or disallow the automatic refresh.
Linking with Hyperlinks Links to cells or ranges include the content of those cells in the link destination. To open the source, you need to open the Edit Links dialog box and click View Source—a long process to view a file. Hyperlinks are designed for interdocument navigation. A hyperlink is an active link that switches focus to a target in a document or application. Hyperlinks typically point to web pages, but you can create hyperlinks to other
137
PART
I Putting Excel 2002 to Work for You
Linking with Hyperlinks
4002c04.qxd 7/19/01 3:27 PM Page 138
138
CHAPTER 4 • Using Names and External References
documents, graphics, or applications, including application links that open a preaddressed e-mail message or download files using file transfer protocol (FTP). When you click a hyperlink, Excel launches the application used to view the link’s target. For example, if the link is a web page, clicking the hyperlink launches your default browser. The wide variety of link targets means you can do a lot with hyperlinks: • Display a page on the World Wide Web • Display a page on your organization’s intranet • Open an e-mail message form • Open a Word document and navigate to specific text or a table • Open another Excel workbook and display a chart or worksheet You can quickly link to a web page or file by simply entering the full URL path to the file or page in a cell. Excel automatically formats the URL as a hyperlink. Use the Insert Hyperlinks dialog box to provide alternate text, screen tips, or navigation within a page or document.
TIP
Use the built-in functionality of hyperlinks instead of command buttons or menu items that fire navigational macros.
Creating Hyperlinks To create a hyperlink in Excel, select the cell where you want to create the hyperlink. Then do one of the following to open the Insert Hyperlink dialog box, shown in Figure 4.8: • Click the Insert Hyperlink button on the Standard toolbar. • Press Ctrl+K. • Right-click and choose Hyperlink from the shortcut menu. • Choose Insert Hyperlink from the menu. If there’s text in the active cell, it’s placed in the Text to Display text box. Be careful here: replacing the Text to Display text replaces the text in the cell. If the Text to Display text box is empty, enter the text you want to display as a hyperlink in the active cell.
4002c04.qxd 7/19/01 3:27 PM Page 139
Linking with Hyperlinks
FIGURE 4.8 Use the Insert Hyperlinks dialog box to create instant links to resources in your worksheet.
139
PART
Putting Excel 2002 to Work for You
I
To provide more information without changing the displayed text, add a Screen Tip that appears when the user points to the hyperlink. Click the Screen Tip button to open the Set Hyperlink Screen Tip dialog box. Enter screen tip text, then click OK to return to the Insert Hyperlink dialog box.
Select the type of hyperlink you want to create in the Link To bar on the left side of the dialog box. Following is an explanation of the five link types.
TIP
To launch a hyperlink from a graphic, select the graphic, then open the Insert Hyperlink dialog box.
Linking to a Web Page When you say the word “hyperlink,” most users think “Web.” To create a link to a web page, choose Existing File or Web Page Type in the Link To bar, and type the URL or locate the page using your browser. If your display text and screen tip are already entered, click OK to create the hyperlink and return to Excel. Use the Look In bar buttons to look for the hyperlink target in the Current Folder, Browsed Pages, or Recent Files. Click the Browse the Web button to launch your default browser; in the browser, navigate to the page you want to link to.
4002c04.qxd 7/19/01 3:27 PM Page 140
140
CHAPTER 4 • Using Names and External References
There are a couple of ways you can place the user precisely on the hyperlinked page. • If the target is also a bookmark, you can select it by clicking the Bookmarks button in the Insert Hyperlink dialog box. The Select Place in Document dialog box opens with a list of the document’s bookmarks. Choose the bookmark and click OK to return to the Insert Hyperlink dialog box. • If there is no bookmark, select the target image, text, or link in the browser, then copy the target URL. In Internet Explorer, this is as easy as right-clicking the target and choosing Copy Target from the shortcut menu. Close the Select Place in Document dialog box. In the Insert Hyperlink dialog box, select the URL in the Address text box and paste the target copied from the web page.
NOTE
Excel saves hyperlink targets as URLs. A full or absolute URL begins with the target type (for example, http, file, or ftp) and continues with the path to the document: http://www.triadconsulting.com/gisd.html. If you leave out any of the pieces, you have a relative URL: gisd.html. By default, Excel searches for the document in relationship to the the directory that the active document is stored in. If gisd.html is stored in the same folder as the workbook that contains the hyperlink, this relative URL works quite well.
Linking to an Existing File Linking to an existing file is a lot like linking to a web page. Enter the file path and name, use the Look In bar or drop-down list or click the Browse for File button in the Insert Hyperlink dialog box to navigate to the file. Select the file and click OK to insert the hyperlink.
Linking to This Workbook and Other Workbooks If the target is an Excel workbook, you can specify a more precise target: a specific sheet, named range, or cell address in the workbook. In the Insert Hyperlink dialog box, select Place in This Document or Existing File or Web Page and locate the workbook. Click the Bookmark button to open the Select Place in Document dialog box. Enter a cell address in the textbox (including the the sheet name followed by an exclamation mark [!]). Or if you’re linking to a place in the current document, choose one of the sheets or named ranges from the tree control. Click OK to close the dialog box and return to the Insert Hyperlink dialog box.
NOTE
You’ll find more about named ranges at the beginning of this chapter.
4002c04.qxd 7/19/01 3:27 PM Page 141
Creating a New Document The Create a New Document hyperlink only creates a new document once. If the document being created already exists, Excel opens the existing document. There are two reasons to create a link to a new document: • The document you want to link to doesn’t exist; you will create it now or the first time the link is clicked. • The hyperlink allows users to create a new document; the document will be renamed, moved, or deleted by another application so users are really creating new documents each time they click the link. To create a new document hyperlink, follow these steps: 1. In the Insert Hyperlink dialog box, choose Create New Document from the Link To bar. 2. Enter a name for the new document in the Name of New Document text box. Enter the correct file extension for the type of new document you want to create: .doc for Word, .xls for Excel, .txt for Notepad text. 3. Click Change, and select a location for the document. Click OK to return to the Insert Hyperlink dialog box. 4. In the When to Edit options, choose Edit the New Document Now to launch the appropriate application and create the document. Choose Edit the Document Later to create the new document the first time the link is activated.
Linking to an E-mail Message Form A hyperlink to an e-mail address launches your e-mail client and opens a message form with the recipient’s address in the To box. For the rest of this section, we’ll assume you use Outlook 2002 or the Outlook web client as your e-mail client.
NOTE
If you have a different e-mail client, you are undoubtedly already used to translating instructions for Office applications’ interaction with your mail client. When you get tired of translating, switch to Outlook 2002. It is the best e-mail client out there. Outlook’s strengths are also its weaknesses, so make sure you install and run a good anti-virus application.
The quick way to add an e-mail hyperlink is to simply enter the e-mail address in a worksheet cell. Excel will format the address as a hyperlink; clicking the address launches Outlook and opens a message form.
141
PART
I Putting Excel 2002 to Work for You
Linking with Hyperlinks
4002c04.qxd 7/19/01 3:27 PM Page 142
142
CHAPTER 4 • Using Names and External References
You’ll use Insert Hyperlink to create an e-mail hyperlink when you don’t want to display the mailto address in the worksheet. You might, for example, want to display Click here to request our catalog and open an e-mail message addressed to the catalog department when someone clicks the text. 1. In the Insert Hyperlink dialog box, choose E-mail Address on the Link To bar. 2. In the E-mail Address text box, enter the e-mail address. 3. In the Subject box, type the subject. Click OK to close the dialog box. If you don’t want Excel to automatically convert an e-mail address to a hyperlink, select the cell with the address and click the AutoCorrect Options button. Choose Undo Hyperlink to reformat the current entry or Stop Automatically Creating Hyperlinks to prevent further formatting:
To have Excel resume automatic formatting of hyperlinks, choose Tools AutoCorrect options. On the AutoFormat as You Type tab, enable the Internet and Network Paths with Hyperlinks check box.
Editing Hyperlinks When you click or double-click a hyperlink, Excel takes you to the hyperlink target, so double-clicking isn’t a good way to switch into edit mode for hyperlinks. To edit a hyperlink, right-click and choose Edit Hyperlink. To edit the hyperlink text, use the arrow keys to active the cell and press F2 to open the cell for editing.
Using Hyperlinks In Excel 2002, as on the Internet, the mouse pointer changes to the hand shape when you point to text or an image that has a hyperlink. Click the hyperlink, and Excel will launch the necessary application, load the target document, and switch focus to that target document. Close the target document to return to the active Excel workbook.
Enabling and Using Smart Tags Smart tags are a new user interface object in Office XP. Smart tags are data that Excel recognizes as a specific type—for example, contact names and addresses or stock ticker symbols—that has specific associated actions. Clicking a smart tag opens a
4002c04.qxd 7/19/01 3:27 PM Page 143
menu of options. The AutoCorrect Options and Paste Options menus are based on smart tag technology, but you can do much more with this new feature.
NOTE
In Excel, smart tags are turned off by default. See “Enabling Smart Tag Support” in the next section to find out how to turn them on.
For example, if you enable smart tags that recognize financial symbols, a purple indicator appears in the lower-right corner of a cell that contains a stock symbol. (The symbol must be entered in all uppercase letters.) Select the cell and a Smart Tag Options button appears. Click the button to open the options menu.
Choose Stock Quote on MSN MoneyCentral to launch your browser and see the current price for the stock. Or select Insert Refreshable Stock Price, and the following real-time, refreshable information is downloaded from MSN MoneyCentral and placed at the location you specify in the workbook.
With a few simple clicks, you’ve used a smart tag to create a Web query that returns a lot of real-time information.
143
PART
I Putting Excel 2002 to Work for You
Enabling and Using Smart Tags
4002c04.qxd 7/19/01 3:27 PM Page 144
144
CHAPTER 4 • Using Names and External References
Enabling Smart Tag Support Smart tags (other than those used with Paste and other Excel operations) are not enabled by default, so before you can use them you need to enable them. Use the following steps to enable smart tags: 1. Choose Tools AutoCorrect Options Smart Tags to open the Smart Tags tab of the AutoCorrect Options dialog box, shown in Figure 4.9.
FIGURE 4.9 Enable smart tags and select recognizers in the AutoCorrect options dialog box.
2. Enable the Label Data with Smart Tags check box. 3. In the Recognizers list, enable the smart tag recognizers you want to use. 4. Click More Smart Tags to launch your browser and search for other smart tag recognizers on the Microsoft website. 5. To use smart tags in the current workbook, enable the Embed Smart Tags in This Workbook check box. 6. Click Check Workbook to add smart tags to cells in the current workbook. 7. Choose a style to Show Smart Tags As in the current workbook. 8. Click OK to save your options and apply smart tags.
TIP
You’ll find more information about smart tags in Chapter 17, “Importing and Exporting from Excel 2002” and Appendix D, “Creating Simple Smart Tags for Excel 2002”.
4002c05.qxd 7/27/01 3:01 PM Page 145
PA R T
II
USING EXCEL’S FUNCTIONS ◗
Using functions and references
◗
Calculating with common statistical functions
◗
Finding and fixing formula errors
◗
Parsing data
◗
Concatenating strings
◗
Creating formulas to manipulate dates
◗
Using IF and other logical functions
◗
Trapping formula errors with logical functions
◗
Using lookups to retrieve data from a table
◗
Using financial functions for loans and annuities
◗
Calculating depreciation
4002c05.qxd 7/18/01 12:52 PM Page 146
This page intentionally left blank
4002c05.qxd 7/18/01 12:52 PM Page 147
CHAPTER
5
CALCULATING WITH FUNCTIONS F E ATU R I NG
Using functions and references
Using absolute, relative, and mixed references
Calculating with common statistical functions
Finding and fixing formula errors
Using the Formula Auditing toolbar
Using manual calculation
4002c05.qxd 7/18/01 12:52 PM Page 148
his is the first of four chapters on Excel’s built-in functions. A function is prebuilt code that you use as part of a worksheet formula. The user interface for functions has been greatly improved in Excel 2002.
t
Excel has over 300 built-in functions that are included in the typical installation and additional functions that can be included in a custom installation of Excel or Office. This book does not cover all the functions, but focuses on functions commonly or creatively used in business. Excel power users are comfortable using at least a few dozen of these worksheet functions. Not all functions are provided from Microsoft. You can purchase additional functions from third-party providers or write functions yourself so that you and your colleagues can easily express your organization’s business rules in Excel worksheets.
NOTE The Analysis Toolpack, home of a few dozen specialized financial and general analysis functions, is discussed in Chapter 18, “Using Excel 2002 with the Web.” For more information on writing functions, see “Creating User Defined Functions” in Chapter 23, “Do-It-Yourself Functions.”
Using Functions Functions (such as the summarization functions SUM, COUNT, AVERAGE, MIN, and MAX discussed in Chapter 2) are used to calculate results used in statistics, finance, engineering, math, and other fields. Functions are structured programs that calculate a specific result: a total, an average, the amount of a monthly loan payment, or the statistical mean of a group of numbers. Each function has a specific order, or syntax, that must be used for the function to work properly. Functions are formulas, so all functions begin with the equal sign (=). The equal symbol is followed by the function name, followed by zero, one, or more arguments separated by commas and enclosed in parentheses:
Excel’s functions are grouped into the 10 categories listed in Table 5.1.
4002c05.qxd 7/18/01 12:52 PM Page 149
Using Functions
E x c e l Fu n c t i o n C a t e g o r i e s
Category
Examples
Financial
Calculate interest rates, loan payments, depreciation amounts, and so on; additional financial functions are included in the Analysis ToolPak add-in for Excel.
Date & Time
Return the current hour, day of week or year, time, or date from the system clock; convert text dates or strings to dates
Math & Trig
Calculate absolute values, cosines, logarithms
Statistical
Calculate totals, averages, and high and low numbers in a range; advanced functions for t-tests, Chi tests, and deviations
Lookup & Reference
Search for and return values from a range; create hyperlinks to network or Internet documents
Database
Calculate values in an Excel database table
Text
Convert text to uppercase or lowercase, trim characters from the right or left end of a text string, concatenate text strings
Logical
Evaluate an expression and returns a value of TRUE or FALSE, used to trigger other actions or formatting
Information
Return information from Excel or Windows about the current status of a cell, object, or the environment
Engineering
Convert numbers from binary to hexadecimal to octal to decimal; work with complex numbers and Bessel functions, Included with Excel, but must be installed separately from the Analysis ToolPak.
You don’t have to learn all the functions—but you should know the common functions thoroughly and know enough about other functions that you can find them as you need them. The AutoSum functions (SUM, COUNT, AVERAGE, MIN, and MAX) are the only functions included on the Standard toolbar. You can access all the functions (including the AutoSum functions) using the Insert Function button on the formula bar or by selecting More Functions on the drop-down menu attached to the AutoSum button While there are methods and shortcuts for entering functions in formulas, you’ll always follow these general steps: 1. Decide which function to use. 2. Type or select the function. 3. Enter required and optional arguments for the function.
PART
II Using Excel’s Functions
TABLE 5.1
149
4002c05.qxd 7/18/01 12:52 PM Page 150
150
CHAPTER 5 • Calculating with Functions
Entering Functions Before entering a function, click in the cell where you want the results to be displayed. When you are comfortable with the syntax of a function, you can simply type the function in the cell. For functions that you rarely use or for complex functions, use the function tools supplied by Excel. Click the Insert Function (ƒx) button in the formula bar to open the Insert Function dialog box shown in Figure 5.1.
FIGURE 5.1 Locate and choose functions in the Insert Function dialog box.
Selecting and Finding Functions If you know the category of the function you need to use, select it from the Category drop-down list. If you know the function’s name, but not the category, choose the All option in the Or Select a Category drop-down list. Choose the function in the Select A Function pane, and then click OK to begin entering arguments. If you’re not sure which function to use, enter some information about what you’re attempting to do in the Search for a Function text box. Click Go to search for functions, as shown in Figure 5.2. Click on the function name in the Select a Function list to display the function’s syntax and description below the pane. If you need help, click the Help on This Function hyperlink to display the Excel Help page on the selected function. When you’ve located the function you want to use, click the OK button.
4002c05.qxd 7/18/01 12:52 PM Page 151
Using Functions
151
FIGURE 5.2 Enter a description of what the function needs to do, then click Go to search for functions.
PART
If you’ve recently used the function you want, type = to start the formula. The Name box will change to a Function box, displaying the name of the last function that was entered from the list of functions. In Figure 5.3, IF was the last function used. Click the Function drop-down arrow to open the list of recently used functions. FIGURE 5.3 Click the Function drop-down arrow to display the most recently used functions.
If the function you want is on the list, select it. If the function you want is not listed in the Function box, choose More Functions at the bottom of the list to open the Insert Function dialog box (refer to Figure 5.2).
II Using Excel’s Functions
Choosing a Function from the Formula Bar
4002c05.qxd 7/18/01 12:52 PM Page 152
152
CHAPTER 5 • Calculating with Functions
Entering Function Arguments When you select a function, Excel moves that function to the formula bar and opens the Function Arguments dialog box. The dialog box displays a description of the function and one or more text boxes for the function’s arguments, as shown in Figure 5.4. For common functions that use a single range of cells as an argument, Excel will “guess” which numbers you might want to use and place the range in the argument text box. Required arguments are bold, like Number 1 in Figure 5.4. These text boxes must be filled in to successfully use the function.
FIGURE 5.4 In the Function Arguments dialog box, the required argument for the AVERAGE function is shown in bold.
An argument for a function can be a cell range or address, another function, or a constant. To enter a constant, simply type it in the argument text box. To enter another function, click in the argument box, then choose the function from the Function drop-down list.
NOTE
When you use a function as a function argument, you create a nested function. You’ll find out more about nested functions in Chapter 6, “Manipulating Text and Dates,” and Chapter 7, “Using Logical Functions.”
To enter ranges as arguments, click in the argument text box and either type the range or select it in the worksheet. In Figure 5.4, you can’t tell whether the range in the Number 1 text box is correct, because the Function Arguments dialog box covers the cells. Click the Collapse Dialog button to shrink the Function Arguments dialog box.
4002c05.qxd 7/18/01 12:52 PM Page 153
Using Functions
153
Confirm that the correct cells are selected or use the mouse to select the correct cells before expanding the palette with the Expand Dialog button. After you have selected all the required arguments, click OK to finish the entry and close the Function Arguments dialog box. As you enter arguments, the current value for the argument is displayed to the right of the text box. The formula result appears below the text boxes. As with any formula, the result of the function is displayed in the active cell. The function itself is displayed in the formula bar when the cell is active. These steps summarize how to use Excel functions: 1. Click in the cell where you want the result of the function to appear.
3. Choose a category from the drop-down list and a function from the Select A Function pane. Click OK to open the Function Arguments dialog box. 4. In the Function Arguments dialog box, select the text box for the first argument. To enter cell ranges, click the Collapse Dialog button if necessary, and then select the cells you want to include in the argument. Click the Expand Dialog button to return to the Function Arguments dialog box. Type constants or open the Function box and select another function. Repeat this step for all required arguments and any optional arguments you need to use. 5. Click OK to complete the entry and close the Function Arguments dialog box.
TIP
Sometimes it’s easiest to refer to an entire column or row in an argument if any entry in the column or row should be included in the formula. If, for example, you want to add every entry in column G, you don’t need to specify G1:G65536. To include all cells in column G, use the range reference G:G. Likewise, use 1:1 to refer to every cell in row 1.
Relative and Absolute Cell References When you copy a formula from one cell to another, Excel automatically adjusts each cell reference in the formula. If, for example, the formula in cell J15 is =H15+I15 and you copy the formula to J16, it is automatically adjusted to =H16+I16. In this example,
PART
II Using Excel’s Functions
2. Type an = symbol. Choose a function from the Recently Used Functions list. If the function does not appear on the list, choose More Functions or Click the Insert Function button on the formula bar or Choose More Functions from the AutoSum drop-down menu to open the Insert Function dialog box.
4002c05.qxd 7/18/01 12:52 PM Page 154
154
CHAPTER 5 • Calculating with Functions
H15 and I15 are relative cell references—references made by simply clicking in the cell or typing a cell address when creating a formula. The relative change from one row (15) to another (16) is reflected in the formula when the formula copies: The rows in the cells are increased by one.
NOTE
When copying cells in Excel, it doesn’t matter if you copy and paste, drag-anddrop, or drag the fill handle. Excel treats formulas the same way, regardless of the copy method you employ. You will, however, see different choices on the AutoFill Options button menu for the fill operation.
Most of the time, this is exactly what you want Excel to do. When you copy a formula from one column to another, you want Excel to adjust the column references. A copy from one row to another should result in a change in the row numbers used in the formula. However, there are exceptions. For example, in the Undiscovered Country worksheet originally shown in Chapter 3, “Formatting Text and Worksheets,” we would like to know the percentage of tickets sold for each destination city. We calculate a city’s percentage by dividing the city’s total into the grand total for all cities. In Figure 5.5, a formula was entered to divide the total Las Vegas package sales (217) into the grand total (633). The formula for Las Vegas is fine—but it’s obviously wrong when copied to the other cities. FIGURE 5.5 The formula in cell F6 was correct, but yielded wrong results when copied down the column.
So what happened? The formula in F6 was =E6/E12. When the formula was filled from F6 to F7, Excel changed each cell reference, just as it did when we filled the totals in Column E.
4002c05.qxd 7/18/01 12:52 PM Page 155
Using Functions
155
NOTE
Excel 2002 makes it easy to see what went wrong in a formula. See “Finding and Fixing Formula Errors” later in this chapter.
The formula in F7 was changed to =E7/E13, and the change from E12 to E13 created the problem. Rather than dividing the Luxor Cruise total into the total for all destinations, it divided it into the non-value in cell E13. The formulas for the other destinations have a similar problem. When you fill this formula, you want E6 to change to E7 relative to the formula’s new location, but you don’t want E12 to change at all. The reference to E12 should be absolute—not changeable.
EXPERT TIP
Absolute Cell References You can instruct Excel not to change the reference to E12 by making it an absolute cell reference. Absolute cell references are preceded with dollar signs: $E$12. The dollar signs “lock in” the cell reference so Excel doesn’t change it if you fill or copy the formula to another cell. The dollar sign in front of the E instructs Excel not to change the column; the dollar sign in front of the 12 locks in the row. So as you fill the formula to the other cities, E6 will change to E7, E8, and E9, but E12 will always be E12. You create the absolute cell reference in the original formula. If you never intend to fill or copy a formula, you don’t need to use absolute references, and they won’t fix a formula that doesn’t work correctly to begin with. (The original formula for Las Vegas in F6 worked just fine.) If you are typing the formula, just precede the column and row addresses with a $. You can also create the absolute cell reference using the F4 key, as you will see in the following steps.
TIP
Another way to handle this situation is by naming cell E12 (QtrTotal would be a good name) and using the name in the formula in F6. Names are always absolute, so when the formula is filled, the name will always refer to E12. See Chapter 4, “Using Names and External References,” for more on naming ranges.
PART
II Using Excel’s Functions
An Excel worksheet has two layers: a value layer, which is displayed in the worksheet window, and an underlying formula layer. When you select a worksheet cell, the cell’s formula layer is displayed in the formula bar. You can toggle between the two layers by holding the Control button and pressing the accent key (`) to the left of the number 1.
4002c05.qxd 7/18/01 12:52 PM Page 156
156
CHAPTER 5 • Calculating with Functions
Follow these steps to create a formula that includes an absolute cell reference: 1. Place the cell pointer where you want the results of the formula to appear. 2. Begin entering the formula. After you click on the cell that should not change when the formula is copied, press the F4 key once to add $ to the row and column of the cell reference. 3. When the formula is complete, press Enter or click the green check mark in the formula bar. When you fill the formula to the appropriate cells, the absolute cell reference will not change.
Mixed Cell References You can also create a mixed reference, making part of a cell address absolute and part relative, by locking in either the column or the row. Use mixed references when you want to copy a formula down and across to have a reference change relatively in one direction but not in the other. For example, E$5 will remain E$5 when copied down because the row reference is absolute, but it can change to F$5, G$5, and so on when copied across because the column reference is relative.
TIP
The Absolute key (F4) is a four-way toggle. The first time you press it, it locks both the column and row: $E$12. Press it again, and only the row is locked: E$12. The third time you press the Absolute key, the column is locked: $E12. Press it a fourth time, and both row and column are relative: E12.
Using Everyday Statistical Functions Excel includes a fistful of complex statistical functions. Everyday functions that you may not think of as statistical functions are also included in the list, including all the functions on the AutoSum button: COUNT COUNTA
Returns the number of numbers in a range. Returns the number of entries, including text entries, in a range.
AVERAGE numbers.
Sums the numbers in a range and divides the total by the number of
MEDIAN
Another kind of average, returns the middle value in a range of numbers.
4002c05.qxd 7/18/01 12:52 PM Page 157
Using Functions
MODE MAX
157
Returns the value that occurs most frequently. Returns the largest value in a range.
MIN Returns the smallest value in a range. COUNT is used to calculate the number of cells that have values, including dates, in the specified range. If you want to count the number of entries including text entries in a range, use the COUNTA function rather than COUNT.
TIP
Subtract COUNT from COUNTA for the same range to find out how many cells are occupied with text rather than numbers.
NOTE The AVERAGE function is SUM/COUNT on a range. The AVERAGEA function is SUM/COUNTA for a range, so each text value adds 1 to the divisor, but does not increase the SUM used as the dividend. In Figure 5.6, we’ve used the SUM, COUNT, COUNTA, AVERAGE, AVERAGEA, MEDIAN, and MODE functions on the range of cells in D4:D18 to quickly report information about pledges for a company fundraiser: SUM
The total in cell D20.
COUNTA COUNT
The number of employees in G7. The number of pledges in G8.
PART
II Using Excel’s Functions
AVERAGE returns a value called the arithmetic mean—the total of all the values in a range divided by the number of values in the range. When we talk about averages— bowling scores, test grades, speed on several typing tests—it’s the arithmetic mean we’re referring to. However, there are two other types of averages: MEDIAN and MODE. MEDIAN tells you which value is the middle value in a range, and MODE tells you which value occurs most frequently. You can routinely use MEDIAN to test the usefulness of an AVERAGE. In a perfect bell curve, mean (AVERAGE), MEDIAN, and MODE are the same value. If MEDIAN and AVERAGE values are close to each other, then there either aren’t too many incredibly high or incredibly low values in the range, or they offset each other. If the MEDIAN is much lower than the AVERAGE, there are some very high values that “pull up” the AVERAGE. A higher than average MEDIAN means that there are quite a few extremely low values.
4002c05.qxd 7/18/01 12:52 PM Page 158
158
CHAPTER 5 • Calculating with Functions
AVERAGE
The average pledge in G9.
AVERAGEA
The per employee pledge in G10.
MEDIAN and MODE
For the results in G11 and G12.
FIGURE 5.6 The statistical functions can be used to quickly summarize results for reporting.
Nonpledges are recorded as None in the worksheet, so the AVERAGE function returns the average of those who pledged to the fundraising effort. If nonpledges had been recorded as zero, then the AVERAGE would include the nonpledges, dropping the average of the per employee figure in G10, as there would be no text entries.
NOTE
The COUNTBLANK function returns the number of empty cells in a range.
Finding and Fixing Formula Errors Excel makes numbers look believable—even when results are so incorrect that no one should believe them. You can make two kinds of errors when creating a worksheet. One is a data entry error: typing the wrong number, misspelling a word or name, or forgetting to type both parentheses in a pair. Excel will let you know when you miss a parenthesis, but there is no software tool that can check to be sure you enter all your numbers correctly. You can ensure that a number is in an acceptable range (see “Validating Data Entry” in Chapter 14), but your experience and knowledge of historic values is the best guide.
4002c05.qxd 7/18/01 12:52 PM Page 159
Finding and Fixing Formula Errors
159
Resolving Logical Errors The other kind of error is a logical error: adding rather than subtracting or multiplying the wrong numbers. Some logical errors violate Excel’s rules about how formulas are constructed and result in an error message in the cell or an interruption from the Office Assistant. Those errors are the easy ones to catch and correct and are discussed in the following section. But errors that don’t violate Excel’s internal logic are the really nasty ones, because nothing jumps out and says, “This is wrong!” If you are familiar with the data, you can check the logic yourself to make sure the results make sense. If you are not conversant with the data, find someone who is and review the worksheet with them.
Working with Error Codes
TABLE 5.2
Excel Error Codes
Error Code/Error Name
Causes
#####
1. Data is too wide for the cell. 2. You subtracted one date from another, and the result is a negative number. Double-check your formula.
#DIV/0 Divide by Zero
The number or cell reference you divided by is either zero or blank. If you see this in cells you just filled, you needed an absolute cell reference in the original formula.
#N/A Not Available
1. You omitted a required argument in a function. 2. The cell that contains the argument is blank or doesn’t have the kind of entry the function requires.
#NAME 1. You misspelled the name of a range or function. 2. You referred to a name that doesn’t exist. 3. You used text in a formula or format without putting it in quotes. 4. You left out the colon in a range (B3:D7).
PART
II Using Excel’s Functions
Excel has eight error codes that pop up in cells to let you know that a formula requires your attention. The first is the ###### error, which may be telling you that the data is too wide for the column or too tall for the row. This is easy to fix (hardly an error, but you get the idea). The codes, listed in Table 5.2, give you information about what caused the error.
4002c05.qxd 7/18/01 12:52 PM Page 160
160
CHAPTER 5 • Calculating with Functions
TABLE 5.2
Excel Error Codes (continued)
Error Code/Error Name
Causes
#NULL
You referred to an intersection that doesn’t exist by using a space between two ranges in an argument.
#NUM
1. You used text or a blank cell in an argument that requires a number. 2. You entered a formula that creates a number too large or too small for Excel to handle.
#REF Invalid Reference
You deleted some cells that this formula requires, so the formula can’t find the cell that it refers to. You may have deleted some cells by pasting other cells over them.
#VALUE
You entered text when a formula requires a number or a Boolean value (TRUE or FALSE).
Excel 2002 includes new tools to help you diagnose and fix errors. Let’s return for a moment to the divide-by-zero error created by copying a relative formula (refer back to Figure 5.5). Each of the four cells with errors has a green error indicator in the upper left corner. Click any cell with an error indicator and an Error Options button appears. Select the button and open the button’s menu to see the type of error, help on the error, and tools for further diagnosis:
Choose Help on This Error to open the Excel Help page covering divide-by-zero errors. Choose Show Calculation Steps to open the Evaluate Formula dialog box, shown in Figure 5.7. The dialog box displays the next calculation to be performed: in Figure 5.7, dividing 42 by 0. Click the Evaluate button, and Excel will perform the calculation and show the result: #DIV/0!
4002c05.qxd 7/18/01 12:52 PM Page 161
Finding and Fixing Formula Errors
161
FIGURE 5.7 Use the Evaluate Formula dialog box to monitor the values as Excel steps through a calculation.
PART
II Using Excel’s Functions
Choose Edit in Formula Bar from the Error Options button menu to open the formula for editing. In the case of a divide-by-zero error, use the Range Finder’s color coding to locate the empty or zero-value cell that’s used as a divisor, then drag the cell’s range finder to the correct location:
NOTE
Choose Error Checking Options to view or change the settings for error checking. For details on these options, see “Setting Error Checking Options” in the next section.
For errors that aren’t as obvious, choose Show Formula Auditing Toolbar to access even more tools to help you fix your formula.
Using the Formula Auditing Toolbar The Formula Auditing toolbar, shown in Figure 5.8, is a toolkit for formula repair. The toolbar has been greatly improved for Excel 2002 and includes features that were formerly available only in the Visual Basic Editor.
4002c05.qxd 7/18/01 12:52 PM Page 162
162
CHAPTER 5 • Calculating with Functions
FIGURE 5.8 Use the Formula Auditing toolbar to diagnose worksheet errors.
NOTE
Two options on the Formula Auditing toolbar, Circle Invalid Data and Clear Validation Circles, are discussed in “Validating Data Entry” in Chapter 14.
Evaluating Errors Click the Evaluate Formula button to open the Evaluate Formula dialog box, shown earlier in Figure 5.7.
Error Checking Click the Error Checking button to check the worksheet for errors. If no errors are found, this message box is displayed:
If errors are found, Excel opens the Error Checking dialog box, shown here:
4002c05.qxd 7/18/01 12:52 PM Page 163
Finding and Fixing Formula Errors
163
The dialog box offers the same options as the Error Options button menu, but has the advantage of Previous and Next buttons, which allow you to move through a series of errors more quickly.
Setting Error Checking Options
Click the Options button in the Error Checking dialog box to open the Options dialog box, shown in Figure 5.9. Click the Reset Ignored Errors button to check the worksheet again and re-indicate errors in cells where you previously chose Ignore Error from the Error Options button menu.
FIGURE 5.9 Use the Error Checking page in the Options dialog box to work your way through a series of formula errors.
PART
Using Excel’s Functions
II
The dialog box settings determine the types of errors that Excel will recognize and mark with an error indicator and an Error Options button. The dialog box settings are detailed in Table 5.3.
TABLE 5.3
Error Option Settings
Setting
Details
Enable background error checking
Allows Excel to check for errors automatically.
Error indicator color
The default is green; choose a different color from the palette if you wish.
Evaluates to error value
Checks for formulas that result in an error and displays error warnings.
Text date with 2-digit year
Checks for formulas in text-formatted cells with dates that use two-digit, rather than four-digit, years.
4002c05.qxd 7/18/01 12:52 PM Page 164
164
CHAPTER 5 • Calculating with Functions
TABLE 5.3
Error Option Settings (continued)
Setting
Details
Number stored as text
Flags numbers preceded with apostrophes or formatted as text.
Inconsistent formula in region
Checks for formulas that differ from those that surround it; does not flag totals unless they are followed by another nontotal formula.
Formula omits cells in region
Flags formulas that include most, but not all, cells in a region.
Unlocked cells with formulas
If a worksheet is protected, flags unlocked cells that contain formulas.
Formulas referring to empty cells
Flags cells with formulas with precedent cells that are empty (disabled by default).
Select or clear check boxes to set the error checking parameters. If you turn off background error checking, you can fire up error checking manually by choosing Tools Error Checking from the menu or displaying the Formula Auditing toolbar (View Toolbars) and clicking the Error Checking button.
Tracing Errors Visually If the source of an error isn’t immediately apparent, select the cell with the error and click the Trace Error button on the Formula Auditing toolbar to show the formula’s precedents—the cells used in the active cell’s formula:
If the Formula Auditing Toolbar is not open, choose Tools Formula Auditing Trace Error to trace an error.
NOTE
4002c05.qxd 7/18/01 12:52 PM Page 165
Finding and Fixing Formula Errors
165
Dependents are cells with formulas that rely on the cell that has the error ; precedents are the cells that are referenced, either directly or indirectly, in the error cell’s formula. Click Trace Dependents to see cells that depend on the active cell. Click the Trace Precedents button, and Excel will show you the precedent cells. As you’re working with precedents and dependents to diagnose an error, click the Remove Precedent Arrows or Remove Dependent Arrows buttons to remove one type of arrow but leave the other. Click Remove All Arrows to hide both precedent and dependent arrows when you have diagnosed and corrected an error or need to clear the trace tools and start again.
Using the Watch Window
FIGURE 5.10 Use the Watch Window to monitor the results of formulas in one or more cells.
Click the Add Watch button to open the Add Watch dialog box. Select the cell you want to watch and click OK to add it to the Watch Window. The selected cell’s location, current value, and formula are shown. Click Add to add the selected cell to the list in the Watch Window. Change the value of a cell that the watched cell uses as a precedent, and the value in the Watch Window changes. To delete a watch, select the watch in the Watch Window and click the Delete Watch button. When you’re finished with the Watch Window, click the window’s close button.
PART
II Using Excel’s Functions
If you’ve worked in any of Microsoft’s development environments, you’ll be familiar with the Watch Window feature. The Watch Window is used to monitor the values of a cell’s contents when values in precedent cells are changed; you can add multiple watches, so you can change the values in one cell and see the results in other parts of the worksheet or on other workbook sheets without scrolling or switching between worksheets. To use the Watch Window, click the Watch Window button on the Formula Auditing toolbar. A Watch Window with several watches is shown in Figure 5.10.
4002c05.qxd 7/18/01 12:52 PM Page 166
166
CHAPTER 5 • Calculating with Functions
TIP The contents of the Watch Window are saved when the workbook is saved, so the next time you open the workbook, you can immediately check the cells you’re monitoring in the window.
Resolving Circular References Circular references are a special type of error. Circular references aren’t passively flagged in the background—a circular error brings Excel to a screeching halt. A circular reference occurs when a formula refers to the cell that it is in. For example, when the formula =SUM(J15:J20) is entered in cell J20, Excel tries to add J20 to itself over and over again. Excel will iterate 100 times; then it will give up and show an error message letting you know you have a circular cell reference:
Click OK, and Help opens with information about circular references. (Help only opens the first time you create a circular reference in a session.) Excel displays a blue dot next to the formula that created the circular reference and displays Circular: and the reference for the offending cell in the status bar. If Help opened, clicking the cell with the circular reference opens the Circular Reference toolbar (or you can turn it on by choosing View Toolbars or right-clicking any toolbar). If there’s a circular cell reference anywhere in an open workbook, CIRCULAR appears on the status bar. Use the drop-down list in the Circular Reference toolbar to find the reference.
The drop-down list in the toolbar displays the current circular reference; clicking the drop-down list shows all the circular references in all open workbooks. The other three buttons on the toolbar are used to trace dependents and precedents and remove all trace arrows.
NOTE
See “Tracing Errors Visually” in the previous section for help with error tracing.
4002c05.qxd 7/18/01 12:52 PM Page 167
Automatic and Manual Calculation
167
The precedent arrow shows that all the cells in the row, including the last cell, are included in the formula in the last cell. With circular errors, the problem is always a precedent—either the current cell address is included in the formula or, more indirectly, the current cell is used in a formula in one of the cells included in the current cell formula. In the example we’ve used so far, the circular reference was easy to find, because the formula referred directly to the cell it was stored in. Indirect circular references are harder to find. Just continue clicking the Trace Precedents button, and you’ll eventually find a formula that refers to the cell where the circular reference was reported.
TIP If the cell with the circular reference is used explicitly in the offending formula, you can search for it using Find. Open the Find dialog box (Edit Find or Ctrl+F) and enter the cell address you’re looking for: for example, J20. Find won’t help if J20 is included in the middle of a range in the formula argument, or if J20 is a named cell.
PART
Automatic and Manual Calculation When you open a workbook, Excel automatically calculates the values for all workbook cells. When you change an entry in a worksheet, Excel automatically recalculates that cell and all of its dependents. You can continue to work while the worksheet recalculates in the background, but if your worksheet is very large with many formulas, recalculation takes a lot of Excel’s attention, so it will be slower to respond to you. You can turn off automatic recalculation in the Options dialog box. Choose Tools Options to open the Options dialog box and click the Calculations tab. The Calculation options are shown in Figure 5.11. There are three calculation modes: • Automatic (the default mode) • Automatic except for data tables (explained in Chapter 19, “Solving Business Problems Using the Analysis Tools”) • Manual
Using Excel’s Functions
II
4002c05.qxd 7/18/01 12:52 PM Page 168
168
CHAPTER 5 • Calculating with Functions
FIGURE 5.11 The calculation options determine when Excel recalculates worksheet values.
WARNING If you choose Manual, you can turn off another automatic option, Recalculate Before Save, by disabling the check box. The Calculation options affect all open workbooks. If you choose Manual recalculation, Excel only recalculates when you force a calculation by pressing F9 or opening the Options dialog box and clicking the Calc Now button. When you force a recalculation, Excel recalculates all open worksheets in all open workbooks. To only recalculate the current worksheet, hold Shift and press F9. If you choose Automatic Except Tables, Excel automatically recalculates worksheets except for ranges occupied by data tables, which are used for analysis and forecasting. To recalculate data tables, force a recalculation of the current worksheet or all open worksheets as explained in the previous paragraph.
NOTE
For information on data tables, see “Creating Data Tables” in Chapter 19.
4002c06.qxd 7/18/01 12:55 PM Page 169
CHAPTER
6
MANIPULATING TEXT AND DATES F E ATU R I NG
Removing extra spaces in text strings
Parsing data to retrieve part of a string
Using the Text to Columns feature
Changing case
Finding a character in text
Concatenating strings
Working with the date functions
Using functions that exclude weekends and holidays
4002c06.qxd 7/18/01 12:55 PM Page 170
any Excel users do little or no number crunching with Excel. Instead, they use Excel’s powerful text and date functions to massage data from other sources or for use in other applications, such as Access, SQL Server, or HTML pages. Excel readily converts a wide variety of file formats, so it’s the tool of choice for fixing imperfect data that you receive from customers or vendors. With Excel’s text and date functions, you can shake and bake almost any type of PC data, turning barely useable data sets into standardized databases for use in Excel or publication on the Web.
m
Working with Text in Excel A chunk of text data is called a string or sometimes, redundantly, a text string. A string can be as short as a single character. Strings can include spaces, symbols, or numbers as well as uppercase and lowercase letters. Numbers formatted using the Text or Special formats in the Format Cells dialog box are text entries, as are cell contents preceded with an apostrophe.
NOTE
Excel includes more specialized functions for use with numbers and dates formatted as text. See “Converting Text to Dates” later in this chapter.
Removing Spaces and Nonprinting Characters Spaces at the end of a text string entry are called trailing spaces, and those at the beginning are leading spaces. Trailing spaces can be accidentally added when a user hits the spacebar before moving to another column or field in any application. For a large number of extra spaces, however, nothing can compete with space-packed data exported from a mainframe database. Some mainframe programs export fixed-length fields of data and fill unused field lengths with blank spaces. For example, if the City field in a database is 15 characters wide, a 10-character city name will be followed by five spaces. If the exported data needs to be used to create mailing labels, the spaces must be removed or a large gap will appear between the city name and the state name. Extra spaces in data are inconvenient and difficult to remove manually. You can’t see them, and even if you could, manually deleting spaces is tedious work. If you use a find-and-replace operation, you risk deleting spaces within a string that shouldn’t be removed. For example, if you replace all the spaces in the City column, you’ll remove the space within a city (for example, the space between Los and Angeles) as well as the extra spaces (following Angeles). Removing leading and trailing spaces while retaining the spaces within a string is a task for the TRIM function.
4002c06.qxd 7/18/01 12:55 PM Page 171
Working with Text in Excel
171
The TRIM function strips only the leading or trailing spaces from a text string; the syntax is =TRIM(string). If, for example, cell C2 contains the text string Los Angeles followed by four spaces, the formula =TRIM(C2) will return Los Angeles without the spaces. Function arguments can be constants or references to cells or, as with the SUM function, ranges of cells. For example, the string argument in the TRIM function can be a string typed in as part of the formula =TRIM(“ Los Angeles ”) or a reference to a cell that contains a string. =TRIM(C2). Nonprinting characters can’t be printed or accurately represented in Excel, which displays them as empty rectangles. Nonprinting characters include printer and data instructions and are sometimes found at the beginning of imported data files. The CLEAN function with the simple syntax =CLEAN(string) removes nonprintable characters from a string: for example, =CLEAN(C2). PART
Copying the Results of Text Functions If you create a formula with TRIM or CLEAN and then delete the cell that contains the original data (C2 in our examples), the formula will return an error. To preserve the results of the formula so you can delete the original data, you’ll need to use a variation on copy and paste. Begin by selecting and copying the cells with the text formulas. Click in an empty area of the worksheet where you want to paste the results of the formula, and then choose Edit Paste Special or right-click and choose Paste Special to open the Paste Special dialog box shown here:
Using Excel’s Functions
II
4002c06.qxd 7/18/01 12:55 PM Page 172
172
CHAPTER 6 • Manipulating Text and Dates
Choose the Values option in the Paste section and click OK to paste the results of the formula beginning in the active cell. Now you can delete the cells that contain the original, untrimmed data. If you prefer, you can paste the values over top of the original untrimmed data.
Parsing Data with LEFT, RIGHT, and MID The LEFT and RIGHT functions return a specified number of characters from the beginning or end of a string. If, for example, you receive a mailing list with the city and two-character state abbreviation in one cell (see the sample in Figure 6.1), you can use RIGHT to list just the two-character abbreviation. FIGURE 6.1 This spreadsheet contains useful data that can be massaged with text functions.
The syntax for the RIGHT function is =RIGHT(string,number of characters). To return the two character state abbreviation from cell C5, use this formula: =RIGHT(C5,2). This assumes, of course, that there aren’t trailing spaces in the entries in column C. To strip spaces from the end of the combined City/State string in our example, first TRIM the string, then apply the RIGHT function: =RIGHT(TRIM(C5),2).
Working with Nested Formulas in Excel The formula =RIGHT(TRIM(C5),2) contains a nested function: The results of the TRIM function are the first argument for the RIGHT function. You can easily enter nested functions in the Function Arguments dialog box. Start with the first function in the formula, the RIGHT function. Click the Insert Function (fx) button on the formula bar, then select RIGHT from the list of Text functions in the Insert Function dialog box.
4002c06.qxd 7/18/01 12:55 PM Page 173
Working with Text in Excel
173
When you click OK, the Function Arguments dialog box opens; in the formula bar, the function name RIGHT and the corresponding function punctuation are bold. In the Function Arguments dialog box, the text box for the first argument, Text, has focus:
PART
Open the drop-down list of functions (on the formula bar) and choose TRIM, or select More Functions to open the Insert Function dialog box and choose TRIM from the list of Text functions. When you close the Insert Function dialog box, the Function Arguments dialog box changes to display the arguments for the TRIM function, and the function TRIM is bold in the formula bar:
Click in cell C5 in the worksheet to enter the argument for the TRIM function. Use the formula bar to switch the function displayed in the Function Arguments dialog box. To display the arguments for the RIGHT function in the Function Arguments dialog box, click the RIGHT function name in the formula bar. Don’t choose RIGHT from the dropdown list; this appends another RIGHT function. To display the argument for the TRIM function, click TRIM in the Function Arguments dialog box. Excel supports up to nine levels of nesting in a formula.
Using Excel’s Functions
II
4002c06.qxd 7/18/01 12:55 PM Page 174
174
CHAPTER 6 • Manipulating Text and Dates
To return the area code (the first three characters) from a 10-digit phone number without parentheses, use =LEFT(cell_address,3). If the phone number includes parentheses around the area code like the numbers in column E of Figure 6.1, you have two choices. Use LEFT to retrieve five characters; the result will include the parentheses. To return the area code without parentheses, use the MID function. The syntax for the MID function is =MID(string,starting with,number of characters). =MID(E5,2,3) will return the second, third, and fourth characters in the telephone number in cell E5.
Using Functions to Change Case If you’re a Word user, you may miss the familiar Change Case command that appears on Word’s Format menu. Excel’s equivalents are the UPPER, LOWER, and PROPER functions, which convert a string to uppercase, lowercase, or proper case. Use UPPER to make a data set that contains uppercase and mixed case entries consistent. The UPPER, LOWER, and PROPER functions use only one argument: the string you want to convert (in quotes) or the address for the cell that contains a string. If cell C2 contains the text Los angeles, CA: =UPPER(C2) returns LOS ANGELES, CA =LOWER(C2) returns los angeles, ca =PROPER(C2) returns Los Angeles, Ca With the PROPER function, Excel converts the first letter and any letter that follows a symbol other than a letter (a space, a number, a hyphen) to uppercase. All other letters are lowercased, so the strings a and an are converted to A and An—not what you’d want in a title, but “proper” nonetheless. You can combine proper with RIGHT, LEFT, TRIM, MID, SEARCH (described in the next section), and other texthandling functions to apply the function to a portion of a text string.
Finding the Position of Text in a Cell There are two functions used to locate a substring within a string: SEARCH and FIND. Both have the same basic form: =SEARCH(substring,string to search,position to start) and =FIND(substring,string to search,position to start). In both functions, the position to start argument is optional and is used to begin to start searching partway into the string. FIND is the original text-searching function used in early versions of Excel; SEARCH is a beefed-up version of FIND that supports the * and ? wildcards, described in this section.
4002c06.qxd 7/18/01 12:55 PM Page 175
Working with Text in Excel
175
NOTE
Because FIND can’t use wildcards, you can use FIND to search for a string that contains a ? or * symbol. If the substring argument contains a question mark or asterisk symbol, but the string to search for does not, FIND returns an error.
Using SEARCH
TIP
The SEARCH function is not case sensitive.
SEARCH and LEFT can be combined to return only the city from the string in Figure 6.1 that includes the city name, a comma, and the state abbreviation. This is done by substituting the previously discussed SEARCH formula for the second argument in the LEFT function, which specifies how many characters to return: =LEFT(C5,SEARCH(“,”,C5)).
TIP
To determine the length of a text entry, use the LEN function. LEN returns the length of a string and has only one argument: the string or its cell address. An example would be =LEN(B15).
SEARCH supports wildcards, so you can use ? to search for a single character or * to search for more than one character. For example, =SEARCH(“UP?”,J5) returns the starting position of the first three-character string beginning with UP that appears in J5. If you need to search for a question mark or asterisk in a string, precede the ? or * with a tilde (~) symbol. =SEARCH(“~?”,J5) returns the position of the question mark symbol in the string in cell J5.
PART
II Using Excel’s Functions
The SEARCH function locates one string within another, so it can be used to find a single character in a string. The syntax for the function is =SEARCH(string to find, string to search in,starting with character); the result is the position of the string you want to find within the string you want to search. The final argument, starting with character, is optional. If you don’t specify where Excel should start searching, it begins at the start of the string. For example, to find the comma character in the combined City/State string in cell C5 (see Figure 6.1), use =SEARCH(“,”,C5). Excel will return the value 8, because the comma is the eighth character in the string Livonia, MI.
4002c06.qxd 7/18/01 12:55 PM Page 176
176
CHAPTER 6 • Manipulating Text and Dates
Converting Text to Columns Excel has another spiffy tool for massaging data: the Convert Text to Columns Wizard. The wizard is used to separate a column of data that has a delimiter—for example, a comma between the city and state or between last and first names, or a hyphen between a catalog number and an item number—or is fixed-length data. Before invoking the text to columns command, save your worksheet. Insert a blank column (if needed) to hold the data you’ll be splitting off. Select the column you want to split, and then choose Data Text to Columns from the menu to open the Convert Text to Columns Wizard. In the first step of the wizard, choose Delimited to split a column of data separated by a delimiter and click Next. In the second step of the wizard, shown here, choose the delimiter used in the data, or select Other and type the delimiter in the text box:
The wizard will separate your data into columns based on the delimiter you select. If, for example, you select a comma as a delimiter, Excel will place the data AAA,,CCC into three columns, and remove the commas. The text AAA will appear in the first column, the second column will be blank, and CCC will be placed in the third column. If you enable the Treat Consecutive Delimiters as One check box, the two commas will be treated as one, and CCC will be placed in the second column.
4002c06.qxd 7/18/01 12:55 PM Page 177
Working with Text in Excel
177
When you’ve set your delimiters and the check box, click the Next button. In the third step of the wizard, select a format for each column of data and a destination for the columns of separated data:
PART
If you don’t specify a destination, the first column of data is placed in the original column, and the remaining columns are placed to the right of the original column. If the columns to the right of the original column aren’t empty, you’ll be prompted to overwrite them. Click OK to convert the text into separate columns of data. If the form of the data you want to convert is very consistent, you can use the Treat Consecutive Delimiters as One option to strip out spaces that follow delimiters. In column A of our sample worksheet (see Figure 6.1), which has last names followed by first names, we can set both the comma and the space as delimiters and enable the Consecutive Delimiters check box. When Excel converts column A to text, both the comma and the space between the last and first names will be removed and the data will be placed in two columns. With the Treat Consecutive Delimiters as One option turned off, each first name in column B is preceded by a space (which can removed with the TRIM function, but that requires an extra step or two). We can’t do the same trick with the City/State data, however. Some city names include spaces (Los Angeles, St. Paul); if we treat spaces as delimiters, the data will be incorrectly separated into three, rather than two, columns.
Using Excel’s Functions
II
4002c06.qxd 7/18/01 12:55 PM Page 178
178
CHAPTER 6 • Manipulating Text and Dates
Putting Text Strings Together Using the CONCATENATE function in Excel 2002, you can reassemble text strings as easily as you can tear them apart. Concatenation is addition for text; each string is appended to the end of the prior string. The arguments for the function are each of the strings you want to add together, separated by commas: =CONCATENATE(string1 ,string2,string3…). The strings can be cells or text entered in parentheses. To concatenate a first name in cell A10 with a last name in B10, use this formula: =CONCATENATE(A10,” “,B10). The second argument, “ “, puts a space between the two names. If you’re just concatenating a couple of fields, it’s easier to use the symbol for concatenation: the ampersand (&). Place the ampersand in your formula between strings. This formula has the same result as the CONCATENATE formula in the previous paragraph: =A10&” “&B10. Use concatenation to combine a text string with the contents of a cell to label the results of a formula: for example, in Figure 6.2, we’ve used the formula =CONCATENATE (“Total Vehicle Expense: ” ,SUM(B5:B8)) to label the result of the SUM formula. FIGURE 6.2 Use a concatenation formula to add a string to label cell contents.
Formatting Numbers in Strings The result of the formula in cell B10 can’t be used in other formulas: it’s text, not a number. That also means it can’t be formatted using the number formatting tools like the Currency button on the Formatting toolbar. To format numbers within text, use the TEXT function, which has two arguments: the text you want to format and the numeric format to apply to the text, both enclosed in quotes. For example, the formula =CONCATENATE(“Total Expenses: ” ,TEXT(SUM(B5:B8),”$#0.00”) applies the custom format $#0.00 to the total of cells B5:B8.
See “Formatting Numbers” in Chapter 2 for information on creating custom formats.
4002c06.qxd 7/18/01 12:55 PM Page 179
Working with Text in Excel
179
TIP You can use the Office Clipboard to swipe the formatting from another cell to use in the TEXT function. Before creating the formula that uses TEXT, select a cell with the format you wish to use. Open the Format Cells dialog box. On the Number page, select and copy (Ctrl+C) the contents of the Type text box. When you’re creating the TEXT formula, paste (Ctrl+V) the format in the appropriate spot in the formula bar or Insert Function argument text box.
Converting Text to Dates
NOTE
DATEVALUE converts the date to a serial value (see “Working with Dates and Times” in the next section), so it can only be used for dates from 1/1/1900 to 12/31/9999. If the date is outside that range, the function returns a #VALUE error.
Creating Day of the Year (Julian) Dates Another type of date, sometimes erroneously referred to as a “Julian date,” is a day-ofthe-year date—a text string created by concatenating the current year with the number of days since the beginning of the year. For example, January 1, 2001 is represented as 2001001, where 2001 is the year and 001 is the first day of the year. The day of the year date was originally used in large computer systems, and served two purposes: ersatz dates that could be stored in a minimal amount of disk space, and added and subtracted more easily than text dates. To create a day-of-the-year date, use the following formula, which assumes that the date being converted to a day-of-the-year date is in cell C2: =TEXT(C2,”yyyy”)&TEXT((C2-DATEVALUE(“1/1/”&TEXT(C2,”yy”))+1),”000”)
PART
II Using Excel’s Functions
When you import dates from other applications, they are often imported as text strings. You can easily tell that a date is text rather than a value by widening the column that the date appears in. Dates are numbers, therefore dates are right-aligned by default. Text entries are left-aligned. The DATEVALUE function converts a text string date to a serial value; the syntax of the function is =DATEVALUE(text string date). If the text string doesn’t include a year (for example, June 8), Excel uses the current year, which is retrieved from the system clock.
4002c06.qxd 7/18/01 12:55 PM Page 180
180
CHAPTER 6 • Manipulating Text and Dates
NOTE
A modern Julian date (MJD) is the number of days and fractions thereof since noon on January 1, 4713 BCE. Julian dates are used in astronomy and, despite their name, have no relationship to the Julian calendar, which was used in western Europe until the 16th century when it began being displaced by the Gregorian calendar currently used. The Julian calendar was devised, in part, by Julius Caesar; Julian dates were devised in 1582 by astronomer Joseph. J. Scaliger, who named them to honor his father, Julius Caesar Scaliger.
Working with Dates and Times When you enter dates, Excel generally recognizes them as dates. If, for example, you enter 1/31/2001, 1-31-2001, or October 31, 2001, Excel recognizes it as a date. When you enter a date, time, or date and time in a form that Excel 2002 recognizes as a date, Excel immediately does two things: • Converts the entry to a serial value. • Applies the Date/Time format that most closely reflects the form used to enter the cell contents. (If you’ve previously formatted the cell, the format you specified is applied.) A serial value is the number of days since an imaginary date, January 0, 1900. January 1, 1900 is converted to serial value 1, January 2, 1900 is converted to 2. If you haven’t changed Excel’s default calculation settings, the serial value of 1/1/2001 is 36,892. Times are converted to fractions of a day, so 6 A.M. on January 2, 1900 would be converted to the serial value 2.25, one quarter of the way through the second serial day. To see the serial value for a date or time, format the cell with a non-Date/Time format like General.
NOTE
Serial values are often incorrectly assumed to be Julian dates.
Dates imported from another application may not fare as well; imported dates are often stored as text entries. Use the date and time conversion functions to convert text dates to number dates.
4002c06.qxd 7/18/01 12:55 PM Page 181
Working with Dates and Times
181
The fact that dates and times are numbers rather than text means you can add, subtract, and compare cells that contain dates or times. If you subtract 1/1/2001 from 1/2/2001, Excel performs a little sleight of hand and subtracts serial value 36,892 from serial value 36,893 to determine that there is one day between the two dates. The following are examples of date and time calculations you can complete in Excel: • Subtract today’s date from a book’s due date to see if it is overdue • Add days to a project’s beginning date to calculate the date when the project should be completed • Determine how many days fall between two dates • Sort dates in chronological order • Subtract the start time for a task from the ending time to determine how long it took to complete the task
NOTE
Date and Time formats are applied on the Number page of the Format Cells dialog box (Format Cells).
Date/Time Forms That Excel Recognizes Excel recognizes common date forms, including the date and time entries shown in column A in Figure 6.3. The dates and times in column C are not recognized as dates by Excel 2002. FIGURE 6.3 Excel recognizes a wide variety of date and time forms.
PART
II Using Excel’s Functions
Before you can do these things, you need to make sure Excel recognizes the string you entered as a date so it can perform the serial value conversion.
4002c06.qxd 7/18/01 12:55 PM Page 182
182
CHAPTER 6 • Manipulating Text and Dates
When you enter a date using the two-digit year format (see cell C9 in Figure 6.3), the cell is flagged with an error indicator. Select the cell and open the Error Options button’s menu to convert the entry to a 1900 or 2000 date.
Entering Times Use the colon symbol to separate the hours, minutes, and seconds in a time entry. For times from midnight to noon, enter 0:00 through 12:00. For times after noon, either enter PM (1:00 PM, including a space between the time and PM) or use the 24-hour clock (13:00) or Excel assumes that they’re A.M. times. Not all times are clock times. Enter 3:00:30 for either 30 seconds after 3 A.M. or the duration three hours and 30 seconds. For both clock and non-clock time entries, you must enter hours, even if the number of hours is zero. For example, to enter 20 minutes, enter 0:20, not 20 or :20. Excel treats 20 as 20 hours, and :20 as text. Excel includes time/date conversion and mathematical functions. The conversion functions convert or extract date and time data. The mathematical functions are used for addition and subtraction.
Entering and Storing Dates and Times in Excel 2002 If you enter a date with a two-digit year (1/1/01), Excel applies the following rule to determine which century to place the date in: • For year values 00–29, Excel assumes the date is in the 21st century: 1/1/2000 through 12/31/2029. • For year values 30–99, Excel assumes the date is in the 20th century: 1/1/1930 through 12/31/1999.
4002c06.qxd 7/18/01 12:55 PM Page 183
Working with Dates and Times
183
If your workbook includes dates prior to 1/1/1930 or after 12/31/2029, enter all four digits of the year so that Excel won’t need to interpret the date. If you want to force Excel to display four-digit years, change the Short Date Style setting on the Regional Settings page of the Windows Control Panel (Start Settings Control Panel). To ensure compliance with worksheets created on a Macintosh computer, Excel supports two date systems. In the default 1900 system used in Windows applications, January 1, 1900 has the serial value 1. In the 1904 system, used by the Macintosh operating system, 1/1/1904 is assigned serial value 1. Both systems have values for dates up to December 31, 9999. There will be a Y10K problem in Excel worksheets, but none of us will be here to worry about it.
Excel stores times as decimal fractions, based on a 24-hour clock. Midnight (0:00:00) is 0; noon (12:00:00) is 0.5; and one second before midnight (23:59:59) is 0.99999999. Format the decimal fractions using the Time formats in the Format Cells dialog box.
Basic Math with Dates Dates are stored as serial values, so you can easily add and subtract dates. For example, to add three days to the date in cell B10, use the formula =B10+3. To subtract five days, use the formula =B10-5. The result in both cases is a serial value, displayed with the date format of the formula cell or the date format used in B10 if there was no date format applied to the formula cell. You can format the results using any of the Date and Time formats. Excel stores times as decimal values rather than hours, minutes, and seconds. Table 6.1 lists the decimal values for an hour, commonly used fractions of an hour, minutes, and seconds.
PART
II Using Excel’s Functions
To switch to the 1904 system, choose Tools Options to open the Options dialog box. On the Calculation tab, enable the 1904 Date System check box. (If you open a worksheet created with Excel for the Mac, Excel will automatically enable the 1904 Date System check box.) Note, however, that this will not change the serial values Excel has assigned to dates you’ve already entered in workbooks.
4002c06.qxd 7/18/01 12:55 PM Page 184
184
CHAPTER 6 • Manipulating Text and Dates
TABLE 6.1 Time
D e c i m a l Va l u e s f o r U n i t s o f Ti m e Decimal Value
1 hour
0.0416666667
45 minutes
0.0312500000
30 minutes
0.0208333333
15 minutes
0.0104166667
10 minutes
0.0069444444
5 minutes
0.0034722222
1 minute
0.0006944444
1 second
0.0000115741
When you’re creating formulas, you don’t need to enter the decimal values. For example, to add one hour to a time in cell B10, instead of adding 0.0416666667, you can enter 1:00 or 1/24 (one twenty-fourth of a day). If you enter 1:00 or 1/24, Excel converts it to a decimal value. Table 6.2 shows the decimal equivalents for the hours of the day from midnight to 11 P.M.
TABLE 6.2
D e c i m a l Va l u e s f o r H o u r s o f t h e D a y
Time
Decimal Value
12:00 A.M.
0.0000000000
1:00 A.M.
0.0416666667
2:00 A.M.
0.0833333333
3:00 A.M.
0.1250000000
4:00 A.M.
0.1666666667
5:00 A.M.
0.2083333333
6:00 A.M.
0.2500000000
7:00 A.M.
0.2916666667
8:00 A.M.
0.3333333333
9:00 A.M.
0.3750000000
10:00 A.M.
0.4166666667
11:00 A.M.
0.4583333333
4002c06.qxd 7/18/01 12:55 PM Page 185
Working with Dates and Times
TABLE 6.2 Time
185
D e c i m a l Va l u e s f o r H o u r s o f t h e D a y ( c o n t i n u e d ) Decimal Value
0.5000000000
1:00 P.M.
0.5416666667
2:00 P.M.
0.5833333333
3:00 P.M.
0.6250000000
4:00 P.M.
0.6666666667
5:00 P.M.
0.7083333333
6:00 P.M.
0.7500000000
7:00 P.M.
0.7916666667
8:00 P.M.
0.8333333333
9:00 P.M.
0.8750000000
10:00 P.M.
0.9166666667
PART
11:00 P.M.
0.9583333333
II
If your worksheet contains hours expressed as decimals (for example, 9.5 for 9 hours and 30 minutes), divide the number by 24 to convert it to the decimal value shown in Table 6.2. Apply a time format to display the result as 9:30. Divide minutes by 1,440 to convert minutes to time values.
Subtracting Dates and Times Subtract one date or time from another as you would subtract any numbers. Figure 6.4 shows a portion of a worksheet with starting times, ending times, and total hours, calculated by subtracting the starting time from the ending time. The formula returns the hours formatted as a time (9:00 AM rather than simply 9:00). The format shown in Figure 6.4 is a custom format. In the Format Cells dialog box, delete the AM/PM portion of the default time format to leave the custom format h:mm. FIGURE 6.4 Subtract one time from another to find out how many hours elapsed between the two. The negative number in cell D5 displays an error.
Using Excel’s Functions
12:00 P.M.
4002c06.qxd 7/18/01 12:55 PM Page 186
186
CHAPTER 6 • Manipulating Text and Dates
There is one small problem in our worksheet. In cell D5, the result is a negative number because the shift extended past midnight into a new day. For math with times on either side of the witching hour, you need a more explicit formula that adjusts if the ending time is prior to the starting time. The formula that will produce the correct results in cell D5 and every other cell in column D is =(C5+(C5300000,6.5%*D4,IF(D4>250000,6%*D4,IF(D4>200000,5.5%*D4,5%*D4))) =IF(D50,C10-D10,0)
Principal paid with first payment
G10
=IF(C10>0,C10,0)
Principal to date for first transaction
H10
=LoanAmt-F10
Balance following first transaction
D11
=IF(C11>0,IF(C10>0,((B11-B10)/ 365)*AnnIntRate*H10,((B11-B9)/ 365)*AnnIntRate*H10),0)
Interest due between first and second transactions
E11
=IF(C11>0,D11+E10,E10)
Interest paid with second transaction
F11
=IF(C11>0,C11-D11,C11)
Principal paid or increased with second transaction
G11
=IF(C11>0,C11+G10,G10)
Payments to date
H11
=H10-F11
Balance after second transaction
If you’re building this worksheet, copy the formulas in D11:H11 for as many rows as you wish. The formulas in unused rows don’t return errors, so you can either display them or hide them using conditional formatting with IF and ISBLANK for the cell in column A—for example, =IF(ISBLANK(A20))=TRUE. This worksheet can’t use the PPMT and IPMT formulas to calculate principal payment and interest payment, because the payment amounts and dates aren’t constant. Instead, we calculate interest “the old-fashioned way” and subtract the interest payment from the total payment to determine principal payment. Let’s unpack the two interest formulas used in the worksheet. The formula in D10 calculates the interest paid in the first payment. The interest calculation is =((B10-LoanDate)/365)*AnnIntRate*LoanAmt. The first part of the formula, (B10-LoanDate)/365, subtracts the loan origination date from the payment
4002c08.qxd 7/18/01 1:01 PM Page 227
Working with Present and Future Value
227
date, then divides the result into the 365 days in a year to determine what decimal portion of a year passed between the two dates. The result is then multiplied by the annual interest rate and the loan amount: *AnnIntRate*LoanAmt. The final result is the interest due when the first payment is made. The formula in D11 differs from the formula in D10 in a noteworthy way. The first IF checks to see the payment in C11 is greater than zero. If it is not, then 0 is entered in the cell. The nested IF, IF(C10>0…) checks to see if the previous entry was a payment. Interest accumulates between one payment and the next, so we need to check the previous entry to see if it’s a payment or an addition to the loan. If C10 is greater than zero, the function calculates interest due since the previous transaction. If C10 is less than or equal to zero (an addition to the loan), the formula uses the date for the transaction before the loan addition in B9. A complex formula, but it returns the correct values. PART
The cells in column A are conditionally formatted. The font color for text entries (user comments) is set to blue using a Formula Is conditional format: =ISTEXT(A9) .
Calculating Future Value
www
You use FV to calculate the future value of two types of investments: the first type is one-time deposits (such as a certificate of deposit) and annuities, and the second type is periodic deposits, like an IRA to which you add $2,000 each April 15, the $50 savings bond purchased once a month through payroll deduction, or a weekly deposit into a savings account. The future value is the amount of the investment plus interest accrued on the investment. There are two types of interest: simple interest and compound interest. Interest is compounded when it is periodically added to the principal, effectively earning “its own interest” in future periods. For example, you can purchase a 24-month certificate of deposit that is compounded monthly. At the end of the first month, the interest due on the CD is accrued to the principal of the CD so you’re earning interest on more money in the second month: at the end of the second month, you earn interest on both the principal and the interest earned in the first month. Simple interest is called simple because it doesn’t compound. The four worksheets used in this section are available on the Sybex website.
II Using Excel’s Functions
TIP
4002c08.qxd 7/18/01 1:01 PM Page 228
228
CHAPTER 8 • Using Financial Functions
TIP There’s a guesstimator that all accountants are familiar with: the Rule of 72, used to quickly calculate how an investment, compounded annually, doubles in value. Divide 72 by an interest rate to determine how many years it will take for an investment to double; divide 72 by a number of years to find out what interest rate you need to double your money in that number of years. For example, money invested at 6 percent doubles in 12 years (72/6=12); money invested at 10 percent doubles every 7.2 years (72/10=7.2). If you need to double your money in 8 years, find an investment that pays 9 percent (72/8=9). The Rule of 72 doesn’t handle simple interest or interest compounded more than once a year. While it’s no substitute for Excel 2002, it’s a useful rule for quick calculations.
Calculating Simple Interest Simple interest is simple to calculate: there isn’t even a function for simple interest. Multiply the amount invested by the annual interest rate by the number of years the money is invested. Figure 8.6 shows the simple interest worksheet. The formulas used in column B are shown in column C. FIGURE 8.6 The Simple Interest worksheet calculates interest on a single deposit that pays simple interest.
The label in cell A10 is a formula: =”Value at end of “&B5&” years:”
Compound Interest The FV function was created to calculate compound interest. The Compound Interest worksheet in Figure 8.7 calculates compound interest for any number of periods and any number of compounding periods per year. We’re using the worksheet to determine the interest and annual rate of return (annual yield) on a two-year CD paying 7.5 percent compounded monthly.
4002c08.qxd 7/18/01 1:01 PM Page 229
Working with Present and Future Value
229
FIGURE 8.7 The Compound Interest worksheet calculates compound interest using the FV function.
Table 8.3 describes the names and formulas used in the Compound Interest worksheet. C o m p o u n d I n t e r e s t Wo r k s h e e t : N a m e s a n d Fo r m u l a s
Cell
Name
Description
B4
Invested
Amount invested
B5
TermYrs
Length of the investment in years
B6
PeriodsYr
Number of compounding periods in each year
B7
AnnIntRate
Annual interest rate on the investment
B9
PeriodicRate
Interest rate for one period
Cell
Formula
Description
B9
=AnnIntRate/PeriodsYr
Interest rate for one period
B10
=FV(PeriodicRate,PeriodsYr* TermYrs,,-Invested)
Value of investment plus interest at end of term
B11
=B10-Invested
Total interest earned over term of investment
B12
=(B11/Invested)/TermYrs
“Real” interest rate with compounding
The formula in B9 calculates the periodic interest rate by dividing the annual interest rate by the number of compounding periods in a year—a straightforward calculation. The formula in B10 uses the FV function to calculate the future value at the end of the investment term. The syntax of the FV function is =FV(Rate,Nper,Pmt,Pv,Type). The first two arguments, Rate and Nper, both use values based on the compounding
PART
II Using Excel’s Functions
TABLE 8.3
4002c08.qxd 7/18/01 1:01 PM Page 230
230
CHAPTER 8 • Using Financial Functions
period, not an annual rate. The third argument, Pmt, is left empty because there are no periodic payments. The two commas are included to note that the third argument is empty because we need to supply the fourth argument, the present value of the investment (Pv). In B11, we’re subtracting the original investment from the future value to determine the total interest earned. In cell B12, the total interest is divided first into the amount invested. (If we stopped here, the result would be the return on investment.) We then divided by the term of the investment to get the effective annual yield. The 0.56 percent difference between the 7.5 percent annual rate and the effective annual yield of 8.06 percent is the result of monthly compounding. If compounding 12 times a year increases the real interest rate by over a half percent, what would daily compounding do? If you’ve built this worksheet or downloaded it from the Web, you can answer the question by changing the 12 periods in B6 to 365. You may find the answer surprising.
Calculating the Future Value of an Annuity An annuity is an investment made as a series of deposits. After you have made all the deposits, you withdraw both your deposits and the interest earned on the deposits. Examples of annuities include the following: • Summer check clubs for school employees • IRA contributions made every year until you are eligible to withdraw them • Christmas or holiday clubs
TIP
Some investments are part annuity and part single-deposit. For example, you contribute $1,000 annually to an IRA starting when you are 25 years old and ending when you are 44. You start using the money from the IRA account when you are 68 years old. The 20 years of contributions can be calculated as an annuity. To determine the additional interest earned during the 24 non-contributing years, calculate the future value of a one-time deposit (the total value of the annuity) for 24 years.
In the Annuity worksheet shown in Figure 8.8, we’re calculating an investment made by depositing $166 every month (just under $1,000 a year) in an investment instrument that earns 6 percent annual interest.
4002c08.qxd 7/18/01 1:01 PM Page 231
Working with Present and Future Value
231
FIGURE 8.8 The Annuity worksheet calculates the future value of a stream of deposits.
Table 8.4 describes the names and formulas used in the Annuity worksheet. PART
A n n u i t y Wo r k s h e e t : N a m e s a n d Fo r m u l a s
Cell
Name
Description
B4
Pmt
Periodic payment
B5
AnnRate
Annual interest rate earned on annuity
B6
Term
Length of annuity in years
B7
PmtPerYear
Number of payments per year
B8
Type
TRUE if payments are made at beginning of period; FALSE otherwise
Cell
Formula
Description
B10
=Term*PmtPerYear
Total number of payments made
B11
=AnnRate/PmtPerYear
Periodic interest rate
B12
=FV(B11,PmtPerYear* Term,-Pmt,,Type)
Future value of the annuity
B13
=Pmt*Term*PmtPerYear
Total payments made
B14
=B12-B13
Total interest earned on annuity
With a small annuity, the difference between payments made at the beginning of the month and end of the month is slight. By making the payments at the start of
II Using Excel’s Functions
TABLE 8.4
4002c08.qxd 7/18/01 1:01 PM Page 232
232
CHAPTER 8 • Using Financial Functions
each month, the annuity shown in Figure 8.8 earns about $400 additional in interest over the 20 years: enough for a nice dinner for you and several of your closest friends. The Type argument for the FV function is optional, but if you omit it, the default is FALSE, which understates the future value of the annuity if payments are actually made at the beginning of the month.
Using the Depreciation Functions Businesses must select a depreciation method as assets are placed in service, and the method can’t be changed later (unless you want to file additional paperwork). The depreciation functions use these arguments: Life
The years of useful life of the asset.
Salvage
How much the asset will be worth when it’s past its useful life.
Months
The number of months the asset was in service the first year.
The worksheet in Figure 8.9 uses several of the depreciation functions to indicate methods a business could use to depreciate assets. (Row 16 has three #NUM errors, which we’ll explain shortly.) FIGURE 8.9 A worksheet for comparing different asset depreciation methods; Excel has a built-in function for each method.
The syntax for the four depreciation functions shown in Figure 8.9 is listed in Table 8.5.
4002c08.qxd 7/18/01 1:01 PM Page 233
Using the Depreciation Functions
TABLE 8.5 Function
D e p r e c i a t i o n Fu n c t i o n s
Syntax
Method
DB
=DB(Cost,Salvage,Life,Period,Month)
Fixed declining balance
DDB
=DDB(Cost,Salvage,Life,Period,Factor)
Double declining balance or other accelerated method (triple declining, etc.)
SLN
=SLN(Cost,Salvage,Life)
Straight-line
SYD
=SYD(Cost,Salvage,Life,Per)
Sum of the Years’ digits
=VDB(Cost,Salvage,Life,StartPeriod, EndPeriod,Factor,NoSwitch)
All methods, returns the depreciation for one or more specific periods
VDB
233
The Function Arguments dialog box provides help for each function. The arguments for the declining balance formula in cell B12 are shown in Figure 8.10.
PART
II Using Excel’s Functions
FIGURE 8.10 Arguments for the Declining Balance (DB) function
Three of the four depreciation methods return an error for year 6 (row 16 of the worksheet in Figure 8.9. Each of the cells with an error has an error-indicator triangle in the upper-right corner. In the final year, the depreciation can’t be calculated using the same depreciation function. Instead, the depreciation is any remaining amount that has not been depreciated in former years. In cell B16, for example, an appropriate formula would be =Cost-SalvageValue-SUM(B11:B15).
4002c08.qxd 7/18/01 1:02 PM Page 234
234
CHAPTER 8 • Using Financial Functions
NOTE
See “Auditing Worksheets” in Chapter 19 for information on handling errors in Excel worksheets.
Rounding Numbers in Excel Everyone knows how to round a number, but if you ask three different people about rounding, you’ll get three different answers. Excel has a rounding function for each of these three people and a few of their friends, too. Whether you want to round, round up, round down, or simply get rid of the non-integer portion of a number, there’s a function to support your calculation. Excel’s rounding functions are listed in Table 8.6.
TABLE 8.6
R o u n d i n g Fu n c t i o n s
Function/Syntax
Description
Examples
ROUND(number, number of decimal places)
“True rounding” rounds away from zero to the number of decimal places you specify.
ROUND(2.75,1) = 2.8 ROUND(31.45,-1) = 30
ROUNDDOWN(number, number of decimal places)
Always rounds toward zero.
ROUNDDOWN(2.75,1) = 2.7 ROUNDDOWN(-3.95,1)=-3.9
ROUNDUP(number, number of decimal places)
Always rounds away from zero.
ROUNDUP(2.72,1)=2.8 ROUNDUP(-3.95,1)=-4
CEILING(number, significant interval)
Rounds away from zero to the nearest significant interval.
CEILING(398,30)=420 CEILING(3.72,.25)=3.75
EVEN(number)
Rounds positive numbers up and negative numbers down to the nearest even number.
EVEN(45)=46 EVEN(-45)=-46
FLOOR(number, significant interval)
Rounds toward zero to the nearest significant interval.
FLOOR(398,30)=390 FLOOR(3.72,.25)=3.5
INT(number)
Rounds down to the nearest integer.
INT(4.67)=4 INT(-4.67)=-5
ODD(number)
Rounds positive numbers up and negative numbers down to the nearest odd number.
ODD(44)=45 ODD(-44)=-45
TRUNC(number)
Truncates a number by discarding the noninteger portion of the number.
TRUNC(23.67)=23 TRUNC(-45.6)=-45
MROUND(number, multiple)
Rounds to the nearest multiple; part of the Analysis ToolPak.
MROUND(3,5)=5 MROUND(497,100)=500
4002c08.qxd 7/18/01 1:02 PM Page 235
Using the QUOTIENT and MOD Functions
235
Why should you round numbers? Most of the number formats round numbers as well—or at least they seem to. If, for example, you format the number 3.975 in cell B20 with a currency format, no decimal places, the number is displayed as $4. But if you click on B10 and look in the formula bar, you’ll see that the number is still really 3.975. This makes a difference, as seen in the following examples: • If you multiply B10 by 10 and expect the result to be 400 rather than 397.50 • If you use B10 in a conditional formula: IF(B10>=4,,) • If you apply conditional formatting based on the value in B10: =IF(B10=4) The rounding functions change the value of the underlying number. In our example, the result of =ROUND(B10,0) is exactly 4. To round to the nearest cent, use =ROUND(B10,2): 3.98.
If you want to use MROUND, you must install the Analysis ToolPak.
Using the QUOTIENT and MOD Functions QUOTIENT and MOD are complementary functions used for a type of division called Modular division or Modulo, a kind of mathematics discovered by K.F.Gauss in the early 19th century. Most recipients of a western education learned Modulo before they learned regular division. Think back to the days of division problems with remainders—21 divided by 5 is 4 r 1—and you’re remembering Modulo. Modulo has lots of uses in arcane areas of computing from hashing algorithms to artificial intelligence. But that’s not why we love it. We love Modulo because it solves business problems: some things really have remainders. Here are three quick examples of problems easy to solve with Modulo and difficult to solve with decimal division: • In a paper supply warehouse, paper is pulled from stock and placed on a conveyor to be bundled and shipped. Cartons hold exactly eight reams of paper. The picker who pulls items for the order needs to let the shipper know how many items are in each order: how many cartons and how many individual reams. • Every cash register with an automatic change dispenser has a program that provides optimal change. If a customer’s change is 68 cents, the customer should receive two quarters, one dime, one nickel and three pennies, rather than six
PART
II Using Excel’s Functions
NOTE
4002c08.qxd 7/18/01 1:02 PM Page 236
236
CHAPTER 8 • Using Financial Functions
dimes and eight pennies. The change program uses Modulo. Cashiers use Modulo to give you the optimal combination of bills. • You want to create a conditional format to apply a light green fill to every third row of a worksheet.
NOTE
See “Creating Cheap Greenbar” in the “Using Formulas as Conditions” section of Chapter 12 to find out how to use a Modulo formula to conditionally format every second, third, or nth row in a worksheet.
There are only two Modulo functions. The QUOTIENT function returns the integer portion of a division problem: =QUOTIENT(25,7) returns 3 =QUOTIENT(100,25) returns 4 The MOD function returns the remainder from a division problem: =MOD(25,7) returns 4 =MOD(100,25) returns 0 The Change Calculation worksheet shown in Figure 8.11 illustrates a change dispensing application. At the top of the worksheet, the user enters the amount of a sale and the cash tendered by the customer. The formula in B5 subtracts the sale from the cash to calculate the total change, then uses a series of QUOTIENT and MOD functions to determine the optimal combination of bills and coins. FIGURE 8.11 The Change Calculation worksheet uses Modulo to calculate the optimal change combination.
4002c08.qxd 7/18/01 1:02 PM Page 237
Using the QUOTIENT and MOD Functions
237
The formulas in B7:B15 are all QUOTIENT functions. The MOD functions are hidden in Figure 8.11, but they are an integral part of the worksheet. Figure 8.12 shows the entire worksheet, including hidden results: FIGURE 8.12 The Change Calculation worksheet with hidden results displayed.
PART
Table 8.6 lists the formulas used in rows 7 and 8 of the worksheet. The formulas in B8 and D8 were filled to complete the table.
TABLE 8.6
C h a n g e C a l c u l a t i o n Wo r k s h e e t Fo r m u l a s
Cell
Formula
Description
B7
=QUOTIENT(B5,C7)
Returns the integer portion of the change required divided by 50.
D7
=MOD(B5,C7)
Returns the remainder of change required divided by 50.
B8
=QUOTIENT(D7,C8)
Returns the integer portion of the remainder from the previous row divided by 20.
D8
=MOD(D7,C8)
Returns the remainder from the remainder of the previous row divided by 20.
Use QUOTIENT and MOD whenever the leftovers of a division problem are best described as whole units rather than fractions or decimal portions of a number.
Using Excel’s Functions
II
4002c08.qxd 7/18/01 1:02 PM Page 238
238
CHAPTER 8 • Using Financial Functions
Generating Random Numbers Random numbers, like modular division, find more application in science than in business. And yet, there are times when only a random number will do: bingo at the company picnic, choosing a winner for a trade-show door prize, or creating a table of numbers to use to test a user-defined function. The random number function generates a random decimal number between 0 and 1 (like 0.97834 or 0.12874), which you then multiply by another value if you want numbers between 1 and 75 (Bingo!), 1 and 100, or any other range. The syntax of the random number function is =RAND(). There are no arguments. Figure 8.13 shows a table of random numbers in column A, the numbers transformed to the range of 1–100 in column B, and transformed to 1–50 in column C. FIGURE 8.13 Use the RAND function to generate random numbers.
The formula in cell B4, =INT(100*A4), returns the integer portion of the random number multiplied by 100. There’s a similar formula in C4: =INT(50*A4). The formulas in row 4 were filled to the remaining cells.
TIP RAND is a volatile function: a function that recalculates with each change in the worksheet, even if the cell that’s changed is 500 rows away. In Chapter 6, “Manipulating Text and Dates,” we introduced two other volatile functions: NOW and TODAY. The INDEX function discussed in Chapter 7, “Using Logical Functions,” is also volatile. Whenever you close a workbook that uses a volatile function, Excel prompts you to save changes, even if you made no changes at all.
4002c09.qxd 7/18/01 1:04 PM Page 239
PA R T
III USING CHARTS AND GRAPHICS ◗
Creating pie charts and series charts
◗
Editing and formatting charts
◗
Creating radar, bubble, and stock charts
◗
Using fills, textures, and gradients in charts
◗
Using the drawing tools
◗
Inserting clip art and objects
◗
Formatting objects
4002c09.qxd 7/18/01 1:04 PM Page 240
This page intentionally left blank
4002c09.qxd 7/18/01 1:04 PM Page 241
CHAPTER
9
CREATING EASY-TO-UNDERSTAND CHARTS F E ATU R I NG
Selecting the chart that best represents your data
Creating, moving, and sizing charts
Previewing and printing charts
Formatting charts
Modifying charts
4002c09.qxd 7/18/01 1:04 PM Page 242
early one-third of the adult population does not understand the relationship between numbers. They can’t really make sense of a budget, accurately calculate their household income tax, or make change from a five dollar bill. In the new millennium, the numerically challenged aren’t spending their days sitting in basic math classes. They spend their time at work. They serve on committees and boards that approve or reject projects and expenditures dear to your heart and your organization’s bottom line. Excel’s charting feature is a tool that helps bridge the gap between the figures in spreadsheets and the people who need to understand them, making numbers accessible to people who can’t or don’t work well with numbers. And even people who like numbers appreciate a well-built chart. Charts make it easier to compare and understand numerical values and highlight information that can be lost in a long list of numbers. Every chart tells a story. Stories can be simple (“See how our sales have increased”) or complex (“This is how our overhead costs relate to the product price”). A well-designed chart provides context and focus so the story you want to tell is easily understood. Charts are constructed with data points, which are the individual numbers in a worksheet, bundled into data series, which are the groups of related data points within a column or row. For example, Figure 9.1 shows the Undiscovered Country Travel Destination Package Sales worksheet we’ll use to create charts in the first portion of this chapter. Each of the numbers in the worksheet is a data point. There are many possible sets of data series in this worksheet: one set includes four data series— one for each city’s row. Another set includes a data series for each month’s column. Each column or row of numbers is a series.
n
FIGURE 9.1 Each number in this worksheet is a data point, and each row or column is a potential data series.
A Quick Overview of Chart Types Excel supports a broad selection of chart types. Your data and the story you want to illustrate determine the type of chart you will plot the data on. In this chapter, we’ll focus on the chart types used most frequently for business charts in North America. Other chart types are explained in Chapter 10, “Advanced Charting in Excel 2002.”
4002c09.qxd 7/18/01 1:04 PM Page 243
A Quick Overview of Chart Types
243
Pie Charts Use pie charts to show the relationships between pieces of an entity. The implication is that the pie includes all of something. In the simple pie chart shown in Figure 9.2, the pie shows all the packages sold in the second quarter. The pie chart type isn’t appropriate for illustrating some of anything, so if there’s not an obvious “all” in the data you’re charting, don’t use a pie chart. FIGURE 9.2 A pie chart from the Destination Package Sales worksheet
Series Charts In a series chart, you can chart more than one data series. Series charts let you compare the data points in the series, such as April vs. June or Las Vegas compared to Orlando. Series charts are open-ended; there is no requirement that the data shown is all the
PART
III Using Charts and Graphics
A pie chart can only include one data series. If you select more than one data series, Excel uses the first series and ignores all others. No error message appears, so you won’t necessarily know that the chart doesn’t show the data you intended to include, unless you examine the chart carefully. Pie charts almost always show relationships at a fixed point in time—the end of the year, or a specific month, day, or week. It is possible to create a pie chart with more than one time frame; however, this kind of information would be better represented in a series chart. When you create a pie chart, you don’t need to create worksheet formulas to calculate percentages. Excel totals the data points in the series and then divides the value of each data point into the series total to determine how large each data point’s pie slice should be. Don’t include a total from the worksheet as a data point; this doubles the total Excel calculates, resulting in a pie chart with one large slice that represents exactly 50 percent of the pie.
4002c09.qxd 7/18/01 1:04 PM Page 244
244
CHAPTER 9 • Creating Easy-to-Understand Charts
data for a month or year. There are several types of series charts, so you can often improve the usefulness of a series chart simply by changing the chart type. The charts shown in Figures 9.3, 9.4, and 9.5 were created using the same data series.
Line, Ribbon, and Area Charts The series chart in Figure 9.3 is a line chart showing the relationship between package sales and each city during the first quarter. The chart includes a data table that lists the values illustrated by the chart. Each data series is a city. Line charts are available in a 2D version as shown or in a 3D version called a ribbon chart. An area chart is a line chart with the area below the line filled. Line, ribbon, and area charts are typically used to show one or more variables (such as sales, income, or price) changing over time with the time on the x-axis. FIGURE 9.3 Line charts are typically used to illustrate changes over time.
Column and Bar Charts In Figure 9.4, the data is presented as a bar chart. The bars are bulkier, thus giving added substance to the chart. In the line chart (Figure 9.3), what the user notices is the trend up or down in each line and the gaps between the lines. The bar chart
4002c09.qxd 7/18/01 1:04 PM Page 245
A Quick Overview of Chart Types
245
makes all package sales seem more substantial, but it also makes the difference between destinations even more clear. Changing the chart type shifts the focus to the difference between cities rather than the trend for each city. Line and area charts share a common layout. The horizontal line is the x-axis, and the vertical line is the y-axis (the same x- and y-axes you may have learned about in algebra class). In a bar chart, however, the chart is turned 90 degrees so the x-axis is on the left side. With a little help from Excel, you can combine columns with line or area charts and embellish line or column charts with 3D effects. You can move beyond the column/bar spectrum and use tubes, pyramids, cones, or cylinders to represent data, or you can transform regular bars into floating 3D bars. FIGURE 9.4 The bar chart focuses the user on the difference between cities.
PART
Using Charts and Graphics
III When you need to show totals and the data points that make up the total, the natural choice is a stacked bar chart or a stacked column chart. A stacked 3D column chart is shown in Figure 9.5. Stacking adds another dimension to the chart, since it allows the user to compare sales between, as well as within, time periods—like providing a column chart and a pie chart for each time period. In a 2D chart, the x-axis is the category axis and the y-axis is the value axis. In a 3D chart, the y-axis becomes the series axis, and values are plotted on the third axis, the
4002c09.qxd 7/18/01 1:04 PM Page 246
246
CHAPTER 9 • Creating Easy-to-Understand Charts
z-axis, which provides the “third dimension” of depth in the chart. Don’t worry about memorizing which axis is which in each chart type; there are ways to know which is which when you’re creating or editing the chart. FIGURE 9.5 The stacked column chart provides total and detail information.
Excel includes other chart types suitable for presenting scientific, statistical, and financial data. Scatter charts are used to present experimental results. Surface and contour charts are good for presenting 3D and 2D changes in data. Radar charts show data values in relation to a single metric: a standard, average, or other measurement. Stock charts present values for between three and five series of data, including open, high, low, close, and volume trading information. These chart types are discussed in Chapter 10.
Creating a Chart The easiest way to create a chart is by using the Chart Wizard. In most circumstances it’s also best to use the wizard because it provides easy access to all the chart options you might need. Here’s an overview of the steps for creating an Excel chart with the Chart Wizard: 1. Select the ranges you want to include in the chart. 2. Click the Chart Wizard button on the Standard toolbar.
4002c09.qxd 7/18/01 1:04 PM Page 247
Creating a Chart
247
3. In the first wizard step, select a chart type and subtype, then click Next. 4. In the second step, verify that you have selected the correct range and choose to have the series represented by rows or by columns. Click Next. 5. In the third step, set options for the chart, including titles, data labels, and legend placement. Click Next. 6. In the fourth step, select a location for the chart. Click Finish.
TIP
To quickly create a column chart, select the data, then press F11 or Alt+F1.
Selecting Data for the Chart First, select the data that you want to include in the chart. With the exception of the chart’s title, everything that appears in the chart should be selected from somewhere in the worksheet. Column and row labels provide text for the axes and legend. Make sure that the ranges you select are symmetrical: If you select four labels in rows 9–12 of column A, select data points from the other columns in rows 9–12. If you select labels in columns A–D of row 5, then the data series you select should also be in columns A–D. Figure 9.6 shows the data selected to create the charts originally shown in Figures 9.3 through 9.5.
PART
III Using Charts and Graphics
FIGURE 9.6 Select all the data required for the chart-data points and text that will serve as labels.
4002c09.qxd 7/18/01 1:04 PM Page 248
248
CHAPTER 9 • Creating Easy-to-Understand Charts
TIP The selection in Figure 9.6 doesn’t include the empty cells in row 5. If you include blank rows or extra empty columns in your selection, you’ll have empty spaces in your chart. Remember that you can hold the Ctrl key to select noncontiguous ranges of data. If you select some cells you don’t want to include, press Escape and start selecting again.
Using the Chart Wizard With the text and numbers selected, click the Chart Wizard button on the Standard toolbar. The Chart Wizard and the Office Assistant both open. You can close the Assistant if you want to. The Chart Wizard includes a button that will reopen the Assistant if you need help. In the first step of the Chart Wizard, choose a chart type in the Chart Type list box (see Figure 9.7). If the type of chart you want isn’t listed, check out the chart types on the Custom page. The wizard creates a preview so you can check the chart’s general appearance using your data. After choosing a chart type in the left pane on the Standard Types page, choose a subtype in the right pane. To see a rough sample of the type and subtype using your data, use the Press And Hold To View Sample button in the Chart Wizard. When you’ve selected a type and a subtype, click Next to continue. FIGURE 9.7 Choose a chart type and subtype in the first step of the Wizard.
4002c09.qxd 7/18/01 1:04 PM Page 249
Creating a Chart
249
In the second step, shown in Figure 9.8, check the Data Range page to make sure the range you selected is correct. If it isn’t, use the Collapse Dialog button and select the proper range before continuing. Choose Rows or Columns in the Series In option group, and the preview will change to reflect the range and series arrangement you specify. Figure 9.9 shows the preview by Rows (months on the x-axis) and Columns (destinations on the x-axis).
FIGURE 9.8 In the second step of the wizard, check the selected data range.
PART
III Using Charts and Graphics
FIGURE 9.9 Indicate whether the chart’s series are in rows or columns.
4002c09.qxd 7/18/01 1:04 PM Page 250
250
CHAPTER 9 • Creating Easy-to-Understand Charts
Click the Series tab (Figure 9.10) to verify selected ranges and values for the series used in the chart. Select any of the items listed in the Series list box to see which cells or cell ranges in the spreadsheet correspond to the selected series and category labels. Use the Collapse Dialog button next to the series’ Name text box, the Values text box, or the Category (X) Axis Labels text box to change the ranges used for these chart elements. To remove a series, select the series in the list and click the Remove button. To add a series, click the Add button. Specify a cell reference for the label and a range for the series data. FIGURE 9.10 Verify the series data and name and axis labels on the Series page.
TIP You don’t need to use data from your worksheet as the series names. In Figure 9.10, each series’ name comes from column A, the city name. To change the names (for example, to include the country name), select a series, select the cell reference in the Name box, and type the new entry: for example, Luxor (Egypt). Repeat this for each series.
4002c09.qxd 7/18/01 1:04 PM Page 251
Creating a Chart
251
In the third step, use the tabs (shown in Figure 9.11) to set options for various aspects of the chart: Titles
Enter titles for the chart and axes.
Axes
Display or hide axes.
Gridlines Legend
Display gridlines and display or hide the third dimension of a 3D chart. Display and place a legend.
Data Labels
Display text or values as data labels.
Data Table Show the selected range from the worksheet below the chart. As you change options, the chart preview reflects your changes. When you’ve finished setting options, click Next to continue. FIGURE 9.11 Set the chart’s titles, labels, and display options.
PART
III Using Charts and Graphics
Every chart needs a title. The title provides information that is not already included in the graphical portion of the chart. The chart’s picture, legend, and title taken together should answer any questions about the timing, location, or contents of the chart. In the last step of the Chart Wizard, you can choose to place the chart on the current worksheet or on a new, blank sheet in the same workbook. If the chart is placed on its own sheet, it will print as a full-size, single-page chart whenever it is printed. If
4002c09.qxd 7/18/01 1:04 PM Page 252
252
CHAPTER 9 • Creating Easy-to-Understand Charts
you add it to the current worksheet as an object, it will print as part of the worksheet, but can also be printed separately:
Enter a new sheet name (or choose As Object In and select the worksheet in which to place the chart) and click Finish to create and place the chart. The Office Assistant will open and offer further help with charts. The Excel Chart toolbar will open in the workbook window. You can move a chart object to its own worksheet or make a chart an object in another worksheet (like a picture that you can reposition and resize). Select the chart or chart object, right-click, and choose Location from the shortcut menu to open the Chart Location dialog box.
Editing and Formatting Charts After you create and save your chart, use Excel’s editing and formatting tools to modify it or improve its appearance. If you placed the chart as an object, you’ll probably need to move and resize the chart to place it correctly in an existing report or worksheet. Moving and resizing are only the beginning. You can add, delete, and reorder data series, display error bars and data labels, or change the fill, font, and spacing of various chart elements.
Moving, Sizing, and Printing Chart Objects If you place the chart as an object in the current worksheet, you’ll inevitably need to resize and move it so it will print well with the existing data. The chart object floats on a layer above the worksheet, so it may cover part of the worksheet data or fall across a page break. Fortunately, moving a chart (or any other object) in Excel is a snap.
TIP The Office applications handle all objects in roughly the same way as a chart object, so if you’ve worked with WordArt or clip art in Word or PowerPoint, you know how to move and resize chart objects. You’ll find detailed information about working with drawing objects in Chapter 11, “Using Drawing and Graphics Tools.”
4002c09.qxd 7/18/01 1:04 PM Page 253
Editing and Formatting Charts
253
When the Chart Wizard closes, the square handles on the corners and sides of the chart object indicate the chart is selected. If the chart isn’t selected, click once on the chart to select it. To deselect the chart and return to the worksheet, click anywhere in the worksheet except on the chart object. When the chart is selected, you can move it by pointing to the chart (anywhere inside the chart frame except the plot area or on the title or legend) and holding the mouse button down. When the pointer changes to a four-headed arrow, drag the chart to its new location. To change the chart’s size, move the mouse pointer to one of the chart’s handles. Hold the mouse button and drag the handle to stretch or shrink the chart. Handles on the sides of the chart change the size in one direction (width or height). To increase width and height proportionally, use a corner handle.
TIP Turn on Page Break Preview when sizing and moving charts to make sure they remain within the boundaries of a page. The View menu doesn’t include the Page Break Preview command when a chart is selected, so click anywhere in the worksheet to deselect the chart, choose View Page Break Preview, and reselect the chart. Choose View Normal to return to regular editing mode.
Printing Charts as Objects or Worksheets If you placed your chart as an object in the current worksheet, you can still print it separately. If the chart is selected when you print, the chart will print by itself on a full page—ready to turn into an overhead or slide. If the worksheet is selected, the worksheet prints, including the chart object. • To print a worksheet, including a chart object, activate any worksheet cell before printing. • To print a chart object as a full-page chart, select the chart before printing.
PART
Adding a Data Series You can modify Excel charts quickly and easily. If you have an existing series chart, you can select and drag any excluded series to add them to the chart. Here are the steps for adding a data series to a chart: 1. In the worksheet, select the data series to be added. 2. Point to the border of the cell pointer and drag the series and drop it in the chart.
Using Charts and Graphics
III
4002c09.qxd 7/18/01 1:04 PM Page 254
254
CHAPTER 9 • Creating Easy-to-Understand Charts
If you prefer a more structured approach or wish to change the label for the series, use the Chart Wizard. Select the chart object or chart worksheet and click the Chart Wizard button. Click Next to move to the second step of the Chart Wizard and add or adjust series on the Series tab. This is also a fine place to delete a data series.
Deleting a Data Series A chart is a collection of graphic objects. The chart object contains a data series object, which contains data point objects. To access the objects, first select the chart. Then click a series to select the entire series. The series will have handles.
TIP
To select a data point, first select the chart, then the series, then the data point.
When an object is selected, you can delete or format the object. Use these steps to delete a data series from a chart: 1. In the chart, select the data series or any data point in the series. 2. Press the Delete key on the keyboard.
NOTE
Press the Delete key when the chart is selected to delete the entire chart object.
Formatting Charts The chart area (see Figure 9.12) is a rectangular area within the chart window bounded by the chart border that contains all of the parts and pieces of the chart including the title, legend, and the border surrounding the chart object. Changing the size of the chart object changes the size of the chart area. The plot area (see Figure 9.12) is bounded by the axes and contains the columns, lines, wedges, or other objects used to represent the data points. Objects that form the boundaries of the plot area have fixed location areas and cannot be moved or individually sized. For example, the x-axis labels must be located near the x-axis.
Resizing and Deleting Objects in a Chart You can resize all the objects in the plot area by increasing or decreasing the plot area itself. (There’s an exception to this rule; see “Exploding Pies” later in this chapter.) Objects outside the plot area and axes can be sized or moved to other locations in the chart area. The title and legend can be placed above, below, or in the plot area.
4002c09.qxd 7/18/01 1:04 PM Page 255
Editing and Formatting Charts
255
FIGURE 9.12 The chart area is the entire chart. The plot area is the graphical area of the chart.
Any object in a chart can be selected and then formatted or deleted, with the exception of individual data points. Data points can be formatted, but only data series can be added or deleted. To select a data point, first select the data series, and then click the data point once.
Formatting the Chart with the Chart Toolbar Common formatting options are available on the Chart toolbar (View Toolbars Chart). The first button is used to select one of the objects in the chart; the other buttons format the entire chart or selected chart object. See Table 9.1 for descriptions of the buttons on the Chart toolbar.
Button
C h a r t To o l b a r B u t t o n s Button Name
Function
Chart Objects
Selects the object chosen from the list.
III
Format Object
Opens the Format dialog box for the selected object. The drop-down arrow opens a menu of chart types; clicking the button applies the type indicated on the button face. Displays or hides the legend.
Using Charts and Graphics
TABLE 9.1
Chart Type
Legend
PART
4002c09.qxd 7/18/01 1:04 PM Page 256
256
CHAPTER 9 • Creating Easy-to-Understand Charts
TABLE 9.1 Button
C h a r t To o l b a r B u t t o n s ( c o n t i n u e d ) Button Name
Function
Data Table
Displays or hides the data table.
By Row
Angle Clockwise
Uses the selected worksheet row(s) as a data series. Uses the selected worksheet column(s) as a data series. Angles selected text downward.
Angle Counterclockwise
Angles selected text upward.
By Column
Formatting Individual Objects The difference between a “good” chart and an outstanding chart is often found in a number of small, almost insignificant changes. The chart shown in Figure 9.12 is the chart as it appears right out of the Wizard. Figure 9.13 shows the same chart after we’ve invested three minutes to format a few of the chart objects. FIGURE 9.13 The chart shown in Figure 9.12 with formatting changes.
4002c09.qxd 7/18/01 1:04 PM Page 257
Editing and Formatting Charts
257
The following formatting changes were made: • Plot area pattern set to None • Plot area increased • Corners on chart area rounded • Legend positioned at bottom • Legend text box resized • Y-axis label retyped in caps and rotated • Axis labels’ font size decreased • Title font size decreased and edited to break across lines • Title font changed to match worksheet font To format chart objects such as a data series, select the object from the Chart Objects drop-down menu on the Chart toolbar. Double-click any selected object or click the Format Objects button on the Chart toolbar to open the formatting dialog box for the object. For example, double-clicking any column in a data series opens the Format Data Series dialog box, shown in Figure 9.14.
FIGURE 9.14 Double-click any object to open its formatting dialog box.
PART
Using Charts and Graphics
III
4002c09.qxd 7/18/01 1:04 PM Page 258
258
CHAPTER 9 • Creating Easy-to-Understand Charts
There are five or six tabs in this dialog box; depending on the chart type, the dialog box may include a tab for Shape, Axis, or Y Error Bars. Each page contains a group of settings for the selected data series that include: Patterns
Applies a selected color and pattern for each series.
Axis Adds a second vertical axis at the right end of the plot area scaled to the selected series. The chart must contain two or more series. Y Error Bars Adds a graphic display of sampling errors when the data in the chart is a statistical sample being applied to a larger population. Data Labels the series.
Adds a descriptive label or the numeric value for each data point in
Series Order Reorders the series in a chart; especially useful with 3D charts, where the selected range is charted in reverse order. Options
Settings for the bar or column overlap, gap, and color variation.
For more information on a specific control within the Data Series dialog box, click the Help button in the Title bar of the dialog box, and then click the control. Similar options are available when you double-click a selected data point, the plot area, chart area, or other chart object. To change font and alignment settings for axis labels (such as the April, May, and June x-axis labels in Figure 9.13, select the axis and open the Axis dialog box.
EXPERT TIP To quickly format an object, select it, right-click, then select Format from the shortcut menu. If the entire chart is selected, Chart Options appears on the menu. If you want to change the type of chart from a pie to a bar chart, for example, you can choose also Chart Type from the shortcut menu.
Inserting and Formatting Titles If you didn’t give the chart a title while creating it, you can add one at any time. Select the chart, right-click, and open the Chart Options dialog box from the shortcut menu. On the Titles tab of the dialog box, you can edit or format existing titles (including placeholders) in a selected chart. Or you can edit directly in the chart. To change the text in a title, click once to select the title, and then edit the selected text.
EXPERT TIP To use the contents of a cell as a title or chart label, select the title text box or create a new text box using the Text Box tool on the Drawing toolbar. Select the text box. Type an = in the Formula Bar, then click in the cell you want to use as a title or label. Press Enter to insert the text into the text box.
4002c09.qxd 7/18/01 1:04 PM Page 259
Editing and Formatting Charts
259
To wrap a title into multiple lines, place the insertion point where you want the second line to begin and press Enter. Double-click a title (or select the title, right-click, and choose Format Title from the shortcut menu) to open the Format Title dialog box. Use the controls on the Pattern, Font, and Alignment tabs to format the title as you would format other text.
TIP
To change all the fonts used in a chart, double-click in the chart area and change fonts in the Format Chart Area dialog box. If you don’t like the results, click Undo to revert to the original style.
Exploding Pies If you want to emphasize specific data points in a pie chart, you can explode the pie chart by moving one or more pieces of the pie farther from the center. In Figure 9.15, the Antigua/Tikal slice has been exploded. Although you can select an exploded pie in the Chart Wizard, the wizard explodes either all slices of the pie or the first slice, depending on which explosion sample you choose. It’s easier to create an unexploded pie of the type you want, and then edit the chart to explode selected slices. If you want to explode all the slices in a chart, select the chart and then select the pie in the plot area. Drag any slice away from the center to explode all the pie slices. To explode a single slice, select the chart and then click the pie to select the data series. With the series selected, click to select the slice you want to explode. Drag the slice away from the center.
PART
III Using Charts and Graphics
FIGURE 9.15 Explode a pie slice to emphasize a particular data point.
4002c09.qxd 7/18/01 1:04 PM Page 260
260
CHAPTER 9 • Creating Easy-to-Understand Charts
When you explode all slices in a pie, each slice gets smaller as you increase the space between the slices. If you explode slices individually, the other slices remain centered in the plot area, and the slices don’t get smaller.
Changing 3D Views You can change the perspective for 3D charts using the 3D View tool in the Chart menu. With this tool, you can tilt and rotate 3D series charts and pie charts to emphasize specific data series or individual data points. For example, here’s the pie from Figure 9.15 rotated and tilted so that the exploded slice is at the bottom right in the foreground where it is more noticeable. The slice also stands out better, because its lighter color is next to the darker color of the adjacent slice.
A 3D chart looks three-dimensional because objects in the “foreground” are larger than objects in the “background.” Some purists reject 3D charts because the resizing of objects to create the 3D appearance distorts the actual values represented by the objects; the slice at the bottom of a 3D pie chart is larger than it would be if it appeared at the top of the pie. Many users willingly accept the distortion created by 3D charts because they like the look or they use the distortion to exaggerate a point. For more complex charts, optimizing the view is essential if you want to convey the data’s message to viewers. Important chart objects can be obscured by other chart objects that appear closer. The larger foreground objects dominate the chart’s visual
4002c09.qxd 7/18/01 1:04 PM Page 261
Editing and Formatting Charts
261
impact, possibly drawing attention away from smaller elements that could be important points in a presentation or report. When a 3D column chart includes multiple series, you’ll often need to change the 3D view or rearrange the series so that all the data is visible. Use these steps to change a chart’s 3D view: 1. Select the chart and choose Chart 3-D View to open the 3-D View dialog box:
2. Click the Elevation arrows on the left to change the elevation (degree of tilt of the chart). The wire-frame preview changes to show the effects of your setting, as does the number in the Elevation box. 3. Use the Perspective arrows to change the ratio of the front of the chart to the back; increasing the perspective increases the depth of the chart. (3D pie and bar charts don’t have Perspective controls.) 4. Click the clockwise or counterclockwise rotation buttons to change the chart’s horizontal orientation. The Rotation settings and the preview will change to reflect your choices.
6. Click OK to apply changes and close the dialog box. To return the chart to the original settings, click the Default button and check the Auto Scaling box. There’s also an alternate way to change the 3D perspective, elevation, and rotation on 3D series charts: Choose Corners from the Chart Objects menu on the Chart toolbar and use the handles to tilt or rotate the chart.
PART
III Using Charts and Graphics
5. Type in a different percentage in the Height text box to collapse or expand the chart’s height (the z-axis) relative to its width (the x-axis). A higher percentage will make the chart taller or wider, while a lower percentage will make it shorter or smaller.
4002c09.qxd 7/18/01 1:04 PM Page 262
This page intentionally left blank
4002c10.qxd 7/17/01 1:26 PM Page 263
10
CHAPTER
ADVANCED CHARTING IN EXCEL 2002 F E ATU R I NG
Creating charts with the specialized chart types
Creating combination charts
Setting chart options
Formatting charts with fills and graphics
4002c10.qxd 7/17/01 1:26 PM Page 264
n Chapter 9, “Creating Easy-to-Understand Charts,” we discussed charting fundamentals and the most commonly used chart types. Excel 2002 includes over 100 different types of charts, but only a score of the types is regularly used. Chances are the last Excel chart you saw in a report or presentation was one of three types: a column, a pie, or a bar chart, perhaps of the 3D variety. This chapter explores less frequently used but very useful charts, including area charts, radar charts, surface charts, and high-low charts. This chapter also demonstrates some unique uses for the charts initially discussed in Chapter 9. We’ll examine different formatting techniques including applying fills and using pictures in place of data tables.
i
Creating Specialized Charts
www
We readily understand garden-variety pie, bar, column, and line charts, because they’re the charts we encounter most frequently, the charts taught to elementary school students. The purpose of a chart is to illustrate rather than obscure information so we naturally rely on chart types that users will understand. But there are data series that aren’t easily plotted using these chart types. For example, none of these charts can illustrate three related but independent data series measured at a specific point in time, nor can they show how actual performance compares to a standard composed of five or six numeric measures. If you’re having difficulty creating a chart that accurately represents your data, the problem may be the chart type. Table 10.1 describes some of the more specialized chart types and their usual applications. The worksheets used in this section are available on the Sybex website at www.sybex.com.
TABLE 10.1
E x c e l 20 0 2 S p e c i a l i z e d C h a r t Ty p e s
Chart
Uses
Area
Illustrates cumulative change over time for several related series; for example, population of the West coast states in 1960, 1970, 1980, 1990, and 2000.
Bubble
Compares series of three values at a fixed point in time; for example, sales, number of employees, and market share for companies in the same industry.
Donut
Shows the relationship of data points to the data series for more than one series; for example, vehicle sales by the “Big Three” for 1999, 2000, and 2001.
Radar (Spider)
Compares two or more series with multiple values at a fixed point in time: for example, actual performance against a set of standards.
4002c10.qxd 7/17/01 1:26 PM Page 265
Creating Specialized Charts
TABLE 10.1
265
E x c e l 20 0 2 S p e c i a l i z e d C h a r t Ty p e s ( c o n t i n u e d )
Chart
Uses
Scatter
Plots two parallel data series as Cartesian coordinates (X,Y values); for example, the independent and dependent variables in an experiment.
Stock
Shows a range of values for a period and a final value; for example, the high, low, and closing price for a stock or the high, low, and current temperature.
Surface
Illustrates two different but related sets of data to find optimal solutions or other areas of intersection; for example, the size of the deer herd and number of deer-related vehicle accidents by state.
In the sections that follow, we’ll provide examples for each of the specialized charts listed in Table 10.1 and explore Excel 2002’s advanced charting options.
TIP
www
When a chart is selected, the arrow keys move through the chart objects.
There’s another common chart that’s not listed in the chart types: a Gantt chart. Gantt charts illustrate the time required to complete various tasks in a project. If you frequently need to create Gantt charts, we recommend Microsoft Project 2000. If you need to create Gantt charts infrequently, there’s a multi-step method for Excel 2002 detailed on the Microsoft Office Update site at http://office.microsoft .com/assistance/2002/articles/CreateAGanttChartInExcel2002.aspx.
Creating an Area Chart
The data series in this area chart are arranged in alphabetical order by county name. To rearrange the series order in a series chart, double-click any series or rightclick any series and choose Format Data Series to open the Format Data Series dialog box. On the Series Order page, shown in Figure 10.2, use the Move Up and Move Down buttons to place the series in the order that best illustrates your point.
PART
III Using Charts and Graphics
www
Area charts barely qualify as specialized charts; many users create area charts. Like line charts, area charts are designed to show trends within a data series. However, area charts are more than a substitute for line charts. The stacked area chart illustrates both series and aggregate trends: series values increasing or decreasing, driving the aggregate higher or lower over time. The area chart in Figure 10.1, for example, shows the population trends in northwestern Michigan by county from 1920 to 1990. National, state, and county population information is available for free download from the U.S. Census Bureau at www.census.gov.
4002c10.qxd 7/17/01 1:26 PM Page 266
266
CHAPTER 10 • Advanced Charting in Excel 2002
FIGURE 10.1 The area chart of the county data shows both individual and aggregate trends. This chart would be appropriately labeled “Northwestern Michigan Grows!”
FIGURE 10.2 Rearrange the series order in the Format Data Series dialog box.
4002c10.qxd 7/17/01 1:26 PM Page 267
Creating Specialized Charts
267
The chart in Figure 10.1 partially obscures an important fact: while the five counties have grown in population, the bulk of the growth is in one county: Grand Traverse County. Rearrange the data series as shown in Figure 10.3 and the chart clearly shows four counties with minimal growth, and one county that accounts for most of the aggregate growth. FIGURE 10.3 With the series reordered, it is clear that most of the growth is in only one of the five counties. Though it uses the same data as the chart in Figure 10.1, this chart’s label could be more specific: “Northwestern Michigan Grows Thanks to Grand Traverse County!”
NOTE
See Chapter 9 for information on changing the 3D View.
PART
III Using Charts and Graphics
Before we leave area charts, there are two other styles of area charts worth examining. Area charts are line charts with the area between the line and the x-axis filled in. But with more bulk than a column or bar chart, the 3D area chart, which comes in both stacked and unstacked flavors, bears little resemblance to a line chart. In Figure 10.4, we’ve changed the chart type (right-click the chart area and choose Chart Type from the shortcut menu) to the 3D area chart. We then rearranged the counties and changed the perspective and elevation of the 3D view so all five bars are visible. Unstacking the series is a not so subtle statement: in the two stacked charts, the five counties were part of a whole. Now, they are parallel, perhaps competitors. This chart’s story? “Unlike the rest of the counties, Grand Traverse County grows!”
4002c10.qxd 7/17/01 1:26 PM Page 268
268
CHAPTER 10 • Advanced Charting in Excel 2002
FIGURE 10.4 The 3D, unstacked area chart makes a totally different statement.
The area chart in Figure 10.5 is a 100 percent stacked area chart. To create this chart, Excel totals the population for all five counties for each year. The area for the county represents the county’s population as a percentage of the five-county population for that year. If you need to show the changing contribution to gross profit for departments in a company or products in a product line, consider a 3D, 100 percent stacked area chart. FIGURE 10.5 The 100 percent stacked area chart shows each county’s percentage contribution to the area population.
4002c10.qxd 7/17/01 1:26 PM Page 269
Creating Specialized Charts
269
Reversing Series and Category Order You can change the plot order for categories and values in charts (other than radar charts) as easily as you change the series order in a 3D chart. To change the order of values or categories, select the axis that contains the values or categories you want to rearrange. Choose Format Selected Axis or right-click and choose Format Axis from the shortcut menu to open the Format Axis dialog box.
Depending on the data plotted on the axis you selected, one of the following Reverse Order check boxes appears on the Scale page in the Format Axis dialog box. Enable the check box to reverse the plot order. • Enable Categories in Reverse Order check box to reverse categories. • Enable Values in Reverse Order check box to plot the values in reverse.
• Enable Dates in Reverse Order check box if the values or categories on the selected axis are dates.
TIP The default chart type is a column chart. To change the default chart type, right-click a chart that you want to make the default and choose Chart Type. Click the Set as Default button in the Chart Type dialog box.
PART
III Using Charts and Graphics
• Enable Series in Reverse Order check box to reverse series.
4002c10.qxd 7/17/01 1:26 PM Page 270
270
CHAPTER 10 • Advanced Charting in Excel 2002
Creating a Surface Chart Surface charts are most often used to plot mathematical functions, but they are also used to illustrate two data sets that intersect in a number of locations. Surface charts look like topographic maps; the data points within a range have the same color. The surface chart in Figure 10.6 summarizes test results of actual fuel consumption at various speeds for vehicles with various fuel consumption ratings. FIGURE 10.6 The surface chart shows the effect of speed on fuel consumption.
A surface chart is a summary of a data table with a constant spread between X values and Y values. The data table used to create Figure 10.6, shown here, has X values that increase by 5 and Y values that increase by 10:
Creating a Donut Chart There are two chart types with food-related names; this fact has helped obscure the true value of donut charts. Donuts are more than pies with the center sucked out. Pie charts can show only one data series. Donuts are designed to show multiple data series in relation to each other: a wrap-around version of a 100 percent stacked bar
4002c10.qxd 7/17/01 1:26 PM Page 271
Creating Specialized Charts
271
chart, as shown in Figures 10.7 and 10.8. Both charts illustrate three sets of data from a 1997 U.S. population study. The three series, disaggregated by age, are the total population, the institutionalized population living in group settings, and the noninstitutionalized population living in group settings. FIGURE 10.7 The 3D 100% percent stacked bar chart represents the ratio of each data point to its series.
NOTE
If people will use your chart on screen rather than as part of a print report, don’t bother with data labels. Excel 2002 features chart tips (see Figure 10.7) that display the name and value of the underlying data.
PART
III Using Charts and Graphics
FIGURE 10.8 The donut chart presents the same information as a series of concentric circles.
4002c10.qxd 7/17/01 1:26 PM Page 272
272
CHAPTER 10 • Advanced Charting in Excel 2002
As with a pie chart or 100 percent stacked bar or column chart, each series in a donut chart is comprehensive. The second and third groups combined are a small percentage of the total population, so the differences between age groups can’t be analyzed when presented in a regular 3-D column chart:
Treating the three disparate populations as equals aids in the analysis by age group. By presenting each series as a total population, the donut chart allows the user to easily compare the percentage of each age group living in group settings. If you work with organizations in the Pacific Rim, you’ve probably seen plenty of donut charts. But in North America, donut charts usually require explanation. When you include a donut chart in a presentation, make sure users understand how the data is represented in the chart.
Creating a Scatter Chart If you passed high school algebra, you’ve created scatter charts. Scatter charts, also called XY charts, are used to plot sets of two values: for example, (0,0), (1,-5), (300,350). Scatter charts are the direct descendents of charts invented by Rene Descartes, the French mathematician and philosopher best known for the assertion “I think, therefore I am.” In Cartesian charts, the x and y axes are identically scaled, as in the chart shown in Figure 10.9. Outside of the worlds of science and mathematics, scatter charts are used in market research and marketing. The data points show individual responses, and a line is often added to show an overall trend obtained through regression or extrapolation.
4002c10.qxd 7/17/01 1:26 PM Page 273
Creating Specialized Charts
273
FIGURE 10.9 Cartesian charts use the same scale for x and y axes, which intersect at 0,0.
TIP
For scatter charts arrange the data in two columns or rows with X values listed first.
Creating a Bubble Chart Bubble charts are a type of scatter chart used to compare sets of three values. The first two values are plotted as a single point at the intersection of the X and Y values, just like a scatter chart. The third value determines the size of the bubble that surrounds the point. The chart shown in Figure 10.10 illustrates three aspects of the five companies in a market: sales staff size, number of unique products offered, and market share. PART
III Using Charts and Graphics
FIGURE 10.10 The bubble chart illustrates market share for five competing companies.
4002c10.qxd 7/17/01 1:26 PM Page 274
274
CHAPTER 10 • Advanced Charting in Excel 2002
TIP
For bubble charts, arrange the data in three columns: X values, then Y values, then the values to be used for bubble size.
Bubble charts take a bit of extra work. Select the data but not the labels, then start the Chart Wizard. In the first step, choose the plain or 3D type of bubble chart. In the second step, shown in Figure 10.11, make sure the controls for the X Values and Y Values contain the data you want to plot as an intersection of the x- and y-axis and that the Sizes control contains the data you want to plot as the bubble size. FIGURE 10.11 Verify the ranges used for the X Values, Y Values, and Sizes.
We made two additional changes to the chart in Figure 10.12. We added data labels using the Text Box tool on the Drawing toolbar, and we varied the color of the bubbles to make it easier to refer to the bubbles verbally during a presentation or discussion. To set options for the data series, right-click any bubble, choose Format Data Series from the shortcut menu, and click the Options tab to view available options for the chart type, as shown in Figure 10.12.
4002c10.qxd 7/17/01 1:26 PM Page 275
Creating Specialized Charts
275
FIGURE 10.12 Data Series options for bubble charts.
Creating a Radar Chart Radar charts are used for multivariate analysis, the analysis of several categories of information in a single chart. Figure 10.13 shows a typical radar chart, which shows a food critic’s rating of quality of a meal eaten at Partners, the restaurant up the street from our office.
PART
III Using Charts and Graphics
FIGURE 10.13 Radar charts are used to analyze several different variables simultaneously.
4002c10.qxd 7/17/01 1:26 PM Page 276
276
CHAPTER 10 • Advanced Charting in Excel 2002
For a radar chart to be easily understood, each of the variables must be plotted using the same scale. In Figure 10.13, all five quality variables have been rated on a scale of 1 to 10. If the critic’s ratings were the same in each category, the chart’s polygon would be symmetrical. The lack of symmetry allows a user to quickly grasp the chart’s information: the food critic liked everything but the food’s temperature and the ambiance at Partners. If Partners wants the critic to give a better score next time, they know what factors need work.
TIP What if your data sets don’t use the same scale? For example, you need to plot four data sets; three of the four sets use the scale of 1 to 100, and the fourth uses 1 to 10. The rule is to always convert all the data sets to the least precise scale: to divide the first three sets by 10 rather than multiply the fourth set by 10. In Figure 10.14, we’ve plotted the quality ratings from four food critics on the same chart. The series had to be reordered so that the polygon with the smallest area was in front and that with the largest area in the back. While we can’t see all the plotted values, the consensus is clear: do something about the ambiance (buy some ferns?), then address the consistency of food temperature, which received mixed reviews. FIGURE 10.14 A radar chart illustrating four sets of responses.
4002c10.qxd 7/17/01 1:26 PM Page 277
Creating Specialized Charts
277
Radar charts are often used in quality assurance. The radar chart in Figure 10.15 illustrates average performance on objective measurements in the order fulfillment department in June 2001. The dark outlined pentagon shows the quality goals plotted as a data series. (The quality goals series was formatted with no fill and a heavier line weight.) The filled pentagon chart shows the time it took to perform each of the five measured functions; areas that lie outside the dark pentagon did not meet goal. FIGURE 10.15 The radar chart shows overlaps and gaps between two data series.
Creating a Stock Chart
PART
III Using Charts and Graphics
Like bubble charts, stock charts (also called high-low charts) show three values: a high price, a low price, and a closing price. (In real-time systems, the third value is sometimes used to display the current price.) Arrange the three data sets in that order— high, low, closing—and Excel will crank out a stock chart with little effort. The chart in Figure 10.16 shows the stock prices for Microsoft stock (symbol: MSFT) for the first two weeks of May 2001. There is one problem with the chart, however. The markets aren’t open on the weekend, so there are no values for Saturday and Sunday, May 5th and 6th. In early versions of Excel, this would not be a problem; the range we selected doesn’t include data for 5/5 and 5/6 (see Figure 10.17), so it would not have been charted. But Excel 2002 detects the x-axis series as a time-scale series and faithfully creates an x-axis value for each day. Excel chose the time-scale unit (day, month, or year) based on the smallest difference between two dates in the data series. To fix this problem, we need to change the x-axis settings.
4002c10.qxd 7/17/01 1:26 PM Page 278
278
CHAPTER 10 • Advanced Charting in Excel 2002
FIGURE 10.16 The stock chart displays the daily price range as a vertical line.
FIGURE 10.17 The data range used to create the stock chart.
Right-click in the chart area and choose Chart Options from the shortcut menu or choose Chart Chart Options from the menu bar to open the Chart Options dialog box. On the Axes tab, shown in Figure 10.18, change the Primary Axis option to Category to use the data values rather than the date/time series created by Excel.
TIP
Time-scale axes are available for the following chart types: stock, column, line, bar, and area. Excel only recognizes intervals of days, months, and years.
4002c10.qxd 7/17/01 1:26 PM Page 279
Creating Specialized Charts
279
FIGURE 10.18 Choose Category to use the worksheet dates rather than automatic or time-scale dates on the x-axis.
Creating a Combination Chart Combination charts combine two different chart types to show two or more data series. Combination charts superimpose one data series on another for easy comparison: actual performance and a goal, or this year’s sales and last year’s sales by quarter. The classic example of a combination chart is a combination Line-Column chart where the line shows a standard, minimum, or maximum, and the columns show actual values. The chart in Figure 10.19 shows columnar test scores with a line indicating the score required to pass the test.
PART
III Using Charts and Graphics
FIGURE 10.19 Combination charts superimpose one data series on another. The difference in chart type clearly identifies the different types of data series.
4002c10.qxd 7/17/01 1:26 PM Page 280
280
CHAPTER 10 • Advanced Charting in Excel 2002
The chart uses two data series: one column of test scores, and a parallel column with the passing score (80) in every cell for which there is a test score in the first column. We created a named constant, Passing, with a reference of =80, and copied the formula =Passing to the data range in the second column, making it easy to change the passing score for all tests in the workbook.
TIP
The following modifications were made to the chart created by the wizard: data point markers on the second series were set to None; the title font was increased; the y-axis scale was set to max out at 100, the highest score possible; and the legend was removed.
Combination charts are on the Custom page in the first step of the Chart Wizard, shown in Figure 10.20. There are four combination charts: • Column-Area • Line-Column • Line-Column on Two Axes • Lines on Two Axes
FIGURE 10.20 Choose combination charts from the Custom page of the Chart Wizard.
4002c10.qxd 7/17/01 1:26 PM Page 281
Creating Specialized Charts
281
Some users don’t like cluttering up their workbooks with constants like a column filled with the passing score of 80. If the line is a constant, as in the chart in Figure 10.19, there’s another way to illustrate the same test-score data using a regular bar or column chart, as shown in Figure 10.21. FIGURE 10.21 This 2D bar chart uses the gridline to show the passing score.
Rather than add a data series with the passing score, we changed the major unit on the y-axis to 80 and turned off the Automatic check boxes for Minimum, Maximum, and Major Units, resulting in a single gridline at the passing score.
PART
Using Charts and Graphics
III
4002c10.qxd 7/17/01 1:26 PM Page 282
282
CHAPTER 10 • Advanced Charting in Excel 2002
Creating and Saving Chart Types With Excel 2002, when you modify a chart, you can save the chart settings as a custom chart. Custom charts work like templates: you can apply them later to create charts or share them with other users by sharing the workbooks that contain the charts. User-created custom charts are stored in the XLUSRGAL.XLS workbook. To save a chart’s settings as a custom chart, right-click anywhere in the chart except on an axis, and choose Chart Type from the shortcut menu. On the Custom Types tab, choose the User Defined option, then click the Add button to open the Add Custom Chart Type dialog box.
Enter a name and description for the chart type and click OK to add it to the list of user-defined custom chart types.
TIP
To copy a custom chart type from another workbook, open the workbook, select the chart, and follow the steps for saving a chart’s settings.
To delete a user-defined custom chart type, open the Chart Type dialog box and select the chart. Click the Delete button, then click OK to confirm the deletion.
Setting the Default Chart Type Excel 2002’s default chart type is a two-dimensional column chart. If you usually create two-dimensional column charts, this is a convenience. If you more typically create pies, bars, or any other chart type, follow these steps to change the default chart type: 1. Right-click on a chart and choose Chart Type from the shortcut menu. 2. Select the new default chart from the Standard Types or Custom Types tab.
4002c10.qxd 7/17/01 1:26 PM Page 283
Additional Charting Techniques
283
3. Click the Set as Default Chart button. 4. Click OK to confirm the assignment and apply the chart type to the selected chart. You can’t click Undo to change the chart back to the previous type, so make sure you want to apply the default type to the selected chart.
You can change the default type and create a custom chart type all in one operation. To use the current chart as the new default chart type and save it as a custom type, choose the Custom Types tab in step 2, but do not select a chart type from the list. When you confirm the assignment, the Add Custom Chart Type dialog box will open so you can name and describe the chart.
Additional Charting Techniques The tips and techniques in this section aren’t limited to one chart type; they can be used with a variety of charts.
Adding a Second Axis
TIP
A chart can only have three axes, so you can’t add a secondary axis to a 3D chart.
Double-click either data series to open the Format Data Series dialog box. On the Axis tab, choose the Secondary Axis option to add a secondary axis to the chart. On the Options tab, increase the gap between the columns to make the columns narrower. Click OK to close the dialog box.
PART
III Using Charts and Graphics
Use a secondary axis when your chart contains data series with disparate value ranges or when you’re plotting two different types of data in one chart. The chart in Figure 10.22, for example, reports new training contracts and new contract hours per month. The average number of new hours per month is 56, while the maximum for new contracts is 3. When we include both series in the same chart, the columns representing the new contracts get lost in the shadows of the new hours.
4002c10.qxd 7/17/01 1:26 PM Page 284
284
CHAPTER 10 • Advanced Charting in Excel 2002
FIGURE 10.22 This chart, showing contracts and hours, needs a secondary data axis scaled for the values in the contracts data series.
When you open the Chart Options dialog box (to open the dialog box, right-click the chart area and choose Chart Options from the shortcut menu), the Titles tab includes text boxes for titles for the new X and Y axes.
The result in Figure 10.23 is a chart that shows two data points per month, plotted on different axes using different scales.
4002c10.qxd 7/17/01 1:26 PM Page 285
Additional Charting Techniques
285
FIGURE 10.23 With the addition of a secondary axis, the data series can be easily compared.
Setting Chart Options There are only a few chart options in Excel’s Options dialog box, but they include critical settings that tell Excel how to handle missing values and hidden cells. To set chart options, select a chart, then choose Tools Options. In the Options dialog box, click the Chart tab, shown in Figure 10.24. The Chart options only affect the selected chart. FIGURE 10.24 Set Chart options to plot (or not plot) missing and hidden values. PART
Using Charts and Graphics
III
4002c10.qxd 7/17/01 1:26 PM Page 286
286
CHAPTER 10 • Advanced Charting in Excel 2002
Plotting Missing Values The employee whose sales and commission are illustrated in the chart in Figure 10.25 took a week of vacation in the middle of May. The ominous gap in the middle of the chart gives the impression that she was abducted by aliens. FIGURE 10.25 By default, missing values aren’t plotted at all, leaving gaps like the gap in this chart.
The default option for empty cells is to plot them, leaving gaps in the chart. Choose the Zero option to have Excel plot missing values as 0, as shown in Figure 10.26. In this situation, Zero is the correct choice. The sales and commission for the week were actually zero. FIGURE 10.26 Choose the Plot Empty Cells option of Zero to plot missing values as 0.
4002c10.qxd 7/17/01 1:26 PM Page 287
Additional Charting Techniques
287
TIP Commission is the result of a formula: 6.5 percent of sales. If you plot the commission values in Figure 10.26 on a secondary value axis, the result appears to be a single line with two value axes. Choose the third option, Interpolated, and Excel calculates missing data points. Interpolation is an appropriate choice when the data is non-zero, but missing: for example, when you have 11 months of nearly identical mileage data, but the October mileage sheet is hiding somewhere in your hard drive. In a line chart, Excel draws a straight line between the existing data points, passing through the missing (unmarked) data point. Interpolated isn’t the correct choice for our chart because sales were actually zero, not missing, but we’ll show it to you anyway in the May 2001 Sales Commissions chart in Figure 10.27. Interpolation is only an option for charts that use lines or surface areas to connect data points. You can’t interpolate an extra bar, column, or pie slice. FIGURE 10.27 Choose Interpolated to have Excel calculate the missing data point and chart the connecting line based on the surrounding data.
PART
Plotting Hidden Cells By default, Excel only plots visible cells. If you hide a column of values, their corresponding data series disappears from the chart. Disable the Plot Visible Cells Only check box (see Figure 10.24) to plot hidden cells as well as visible cells.
Using Charts and Graphics
III
4002c10.qxd 7/17/01 1:26 PM Page 288
288
CHAPTER 10 • Advanced Charting in Excel 2002
Sizing Chart Worksheets The Chart Sizes with Window Frame setting, turned off by default, applies to chart sheets only, not charts embedded in worksheets. With the Chart Sizes check box enabled, the active chart worksheet fills the worksheet window. This usually does not reflect how the chart will look when printed.
TIP Choose View Sized with Window to adjust the chart worksheet to fill the window without changing the Chart options. Choose View Sized with Window again to switch back to the view that most closely reflects how the chart will appear when printed.
Displaying Chart Tips Chart tips are displayed when a user points to a data point or points to the connection between two data points in a line, area, or surface chart. By default, both the name of the series and the value of the data point are displayed. Turn off one or both check boxes if you don’t want to display chart tips in the current chart.
Customizing Fill and Line Colors Excel 2002 automatically fills charts and draws chart lines with the 16 colors in the chart color palette. You can change the colors to create a custom color palette for the current workbook. To change the color palette, choose Tools Options to open the Options dialog box. On the Color tab, shown in Figure 10.28, the two rows of chart palette colors appear below the forty standard colors used for text. The first row of chart colors is used for fills and is applied from left to right. The first data series in a chart will be filled with the first color, the second with the second color, and so on. The second row of chart colors is used for lines.
TIP
The palette applies to the workbook, so changing the default color palette changes the colors for the current chart, future charts, and existing charts in the workbook.
To modify a color, select the fill or line color and click the Modify button to open the Colors dialog box. Select a replacement color from the Standard tab or use the Color Picker on the Custom tab to mix a color. Click OK to close the Colors dialog box and return to the Options dialog box.
4002c10.qxd 7/17/01 1:26 PM Page 289
Additional Charting Techniques
289
FIGURE 10.28 Change the color palette on the Color tab of the Options dialog box.
To copy a palette from another open workbook, select the workbook in the Copy Colors From drop-down list. When you are finished modifying the palette, click OK to close the Options dialog box and apply the colors to existing charts.
Applying Custom Fills
PART
III Using Charts and Graphics
In Excel 2002, you’re not limited to solid color fills for chart elements. And after this, you may never be satisfied with solid color fills again. To apply a custom fill to a data series or data point, select the series or point, right-click, and choose Format Data Series or Format Data Point from the shortcut menu to open the dialog box. On the Patterns tab, click the Fill Effects button to open the Fill Effects dialog box, shown in Figure 10.29. You can fill a data series or point with a pattern, gradient, texture, or picture. Click the appropriate tab, choose a fill, set any options, and click OK. To fill with a picture, select the Picture tab, shown in Figure 10.30, then click the Select Picture button. Locate the picture you wish to use and click OK to return to the Fill Effects dialog box.
4002c10.qxd 7/17/01 1:26 PM Page 290
290
CHAPTER 10 • Advanced Charting in Excel 2002
FIGURE 10.29 Select a pattern, gradient, texture, or picture to use as a fill for a data series or data point.
FIGURE 10.30 Use a picture as the fill for a data series or individual data point.
4002c10.qxd 7/17/01 1:26 PM Page 291
Additional Charting Techniques
291
After you’ve selected the picture, set the following options: Format Choose Stretch to stretch one copy of the picture to fit each data point. Choose Stack to stack as copies of the picture horizontally and vertically until the data point is filled. Choose Stack and Scale and enter a Units/Picture value to have Excel stretch the picture so that the data point is filled with the specified number of copies of the picture. Apply To For 3D charts, choose whether the picture should be applied to the front face, sides, and/or ends of the data point. Not all pictures make good chart fills, but the perfect picture is better than an annotation or title. Look for images that reinforce the theme of the chart or data element: for example, pictures of currency used to fill for income or sales, or pictures of national flags used to fill pie slices showing sales in specific countries.
Using Pictures of Data Data tables are not displayed by default. You choose to display a data table in the wizard if you want users to be able to compare actual values presented in the chart. A chart with a data table is shown in Figure 10.31. The chart data table feature is great when you have few numbers, or small numbers, but is unworkable if you have a lot of data that you want to include with a chart or if you use one of the chart types such as the bubble chart that don’t support data tables. The data table’s width is limited to the width of the plot area—often a considerable limitation. And if you have several data series in the chart, they will all be included in the data table, whether you want them or not. If data tables frustrate you, there’s an easy way to present your numerical data with a chart that provides more control so you can fine-tune the display.
PART
III Using Charts and Graphics
FIGURE 10.31 The data table displays values from the chart.
4002c10.qxd 7/17/01 1:26 PM Page 292
292
CHAPTER 10 • Advanced Charting in Excel 2002
To add a picture of data to a chart, select the range of data that you want to include and copy it to the clipboard. Select the chart. Hold Shift then select Edit Paste Picture from the menu to paste the picture of the range into the chart. (If Paste Picture isn’t a menu option, you’re not holding Shift.) In Figure 10.32, we’ve added a picture of the market share percentages from the worksheet to a bubble chart created earlier in this chapter. You can’t add data tables to bubble charts, so this is the only way you can display source data as part of the chart. FIGURE 10.32 Pasting a picture of a data range is an alternative to the inflexible data tables included with charts.
After you paste the picture, there are a few modifications you’ll want to make. If the range you copied did not have a fill applied, neither will the picture of the range. In Figure 10.31, we placed the picture on the chart. To prevent the gridlines from appearing behind the picture, we applied a white fill to the picture; we also added a border to the picture. Right-click the picture and choose Format Picture to access the fill and border options. The picture is not linked to the data range, so if the data changes, the chart will change but your picture will not. To link the picture to the data range: 1. Select the picture object in the chart. 2. Click in the formula bar. 3. Type an = symbol. 4. Select the pictured range—the cells you copied to create the picture. 5. Press Enter to create the link.
4002c10.qxd 7/17/01 1:26 PM Page 293
Additional Charting Techniques
293
After the picture is linked, you can’t format the picture. You can, however, format the range, and the picture will reflect the formatting.
Storing Charts Excel offers two chart locations: as an object in a worksheet or on its own chart sheet. We have some large workbooks with a half-dozen worksheets and 20 or 30 charts. We don’t want the charts to print as part of the worksheets, but we really don’t want to add 20 or 30 sheet tabs to the workbook. We handle this by storing all the charts together in one or two chart worksheets. To create a blank chart sheet, select an empty cell and press F11. If you have data selected, F11 creates a default chart in a chart sheet. With no data selected, you just get the chart sheet. To save a chart in the chart sheet, enter the name of the chart sheet in the last step of the Chart Wizard. To move existing charts to the chart sheet, right-click the chart, choose Chart Location, Select the As an Object In option, and then choose the chart sheet. The charts are embedded in the chart sheet; feel free to scrunch them up to make room for more charts. When you select an individual chart, it will print normally.
TIP When you store charts on separate sheets, give all the chart sheet tabs the same color so you can easily distinguish charts from data. Right-click a sheet tab and choose Tab Color from the shortcut menu to set the color.
PART
Using Charts and Graphics
III
4002c10.qxd 7/17/01 1:26 PM Page 294
This page intentionally left blank
4002c11.qxd 7/18/01 1:13 PM Page 295
11
CHAPTER
USING DRAWING AND GRAPHICS TOOLS F E ATU R I NG
Using Microsoft Draw
Creating AutoShapes
Creating diagrams
Converting text to graphics with WordArt
Formatting and enhancing objects
Inserting graphics from Microsoft Clip Organizer
4002c11.qxd 7/18/01 1:13 PM Page 296
raphics tools are available everywhere you look in Office XP. If you have even the smallest creative bone in your body, there is a tool for you. Worksheets, unadorned, are not the most interesting of documents. However, with the appropriate use of graphics tools you can draw attention to the important numbers and make your worksheets stand out from the crowd. You’ve already learned how to make exciting charts from your data in Chapters 9 and 10. Here are a few of the other imaginative things you can do to spice up your worksheets that we’ll cover in this chapter:
g
• Add drawing objects • Construct flowcharts • Add text boxes • Design graphical text • Draw organizational charts • Create conceptual diagrams • Insert clip art, photos, and other objects You can add all of these graphic touches to your worksheets by using a couple of Office XP’s extra tools such as Microsoft Draw and Microsoft Clip Organizer. In this chapter, we’ll show you how to make the most of these tools—so hold on and watch for that creativity to seep out.
Using Microsoft Draw If you want to design your own graphic objects, Microsoft Draw has a bundle of useful tools. You can unleash your creativity or, if you’re not very artistic, simply annotate your worksheets with arrows and textboxes using the drawing tools on the Drawing toolbar. The Drawing toolbar is displayed by default, but you may have closed it at some time to gain more worksheet space. To display the Drawing toolbar in Excel 2002, use either of these methods: • Click the Drawing button on the Standard toolbar. • Right-click any toolbar or choose View Toolbars, and then select Drawing from the shortcut menu.
4002c11.qxd 7/18/01 1:13 PM Page 297
Using Microsoft Draw
297
The Drawing toolbar includes two broad groups of menus and buttons. The first group, beginning with the AutoShapes drop-down list button and ending with the Insert Picture button, is used to create drawing objects. The remaining buttons on either side of this set are used to format objects you’ve already created.
Inserting AutoShapes AutoShapes consist of lines; basic shapes such as triangles, cylinders, hearts, and braces; block arrows; flowchart shapes; and many more objects. Choose the More AutoShapes option to see the complete list. The easiest way to insert AutoShapes into a worksheet is to display the AutoShapes toolbar, click the category that contains the shape you want, and then click the shape to select it. Use either of the following methods to display the AutoShapes toolbar: • Click the AutoShapes button on the Drawing toolbar, point to the top of the toolbar, and click and drag it to make it float. • Choose Insert Picture AutoShapes. To insert an AutoShape in your worksheet (other than a Curve, Freeform, or Scribble line, all of which are discussed later): 1. Click the AutoShapes button on the Drawing toolbar, and then select a category to display its menu of AutoShapes, shown in Figure 11.1. Alternatively, display the AutoShapes toolbar and click the button of the category you want to use. 2. Click an AutoShape, position the insertion point where you want to place the AutoShape, and then click in your worksheet to insert it.
PART
III Using Charts and Graphics
FIGURE 11.1 Drag the AutoShape category menu’s title bar to create a floating toolbar, making it easier for you to quickly insert shapes in your worksheet.
4002c11.qxd 7/18/01 1:13 PM Page 298
298
CHAPTER 11 • Using Drawing and Graphic Tools
TIP Not only can you drag the AutoShapes menu into your worksheet for easier access, you can also drag the submenus such as Lines or Connectors. Click any button on the AutoShapes toolbar except More AutoShapes, point to the bar at the top of the menu, and drag to float it in the worksheet window. When you click to insert a selected AutoShape, it is created in its default size. If you want to create a custom size, position the insertion point in your worksheet after selecting an AutoShape; notice that the mouse pointer appears as crosshairs. Drag diagonally (from the top left to the bottom right) to create an AutoShape in a custom size. If you’ve already inserted the AutoShape, you can drag one of the AutoShape’s corner handles to increase or decrease its size proportionally. Drag a top or side handle to resize the AutoShape disproportionately. Callout AutoShapes are text boxes used for annotating other objects or worksheet elements, including chart elements. When you insert a callout in your worksheet, the insertion point automatically appears inside the callout so you can begin entering text. To place text in any closed AutoShape except those created using the Lines category, right-click the AutoShape and choose Add Text from the shortcut menu.
NOTE
See the explanation on using text boxes in the “Adding Line Art Objects” section later in this chapter.
Creating Curve, Freeform, and Scribble Objects Curve, Freeform, and Scribble objects are AutoShape line objects that consist of multiple line segments you create individually. The line segments are extremely small in Curve and Scribble objects; in fact, they are so small that the lines appear to be curved. You can easily see the various line segments in a Freeform object. To create a Curve, Freeform, or Scribble AutoShape, follow these steps: 1. Click the AutoShapes button and select Lines to display its menu of AutoShapes. 2. In the menu, click Curve, Freeform, or Scribble. 3. Position the mouse pointer where you want to begin the line, and then click to start it. Gradually move your mouse to a different location and click again to form the first segment of the line. Continue until the line appears as you want, and then double-click to form the end of the line.
4002c11.qxd 7/18/01 1:13 PM Page 299
Using Microsoft Draw
299
If your object is a closed Freeform, double-click near the beginning of the line to close it. Alternatively, double-click to end the freeform object and then to close it, right-click the selected Freeform and choose Close Path in the shortcut menu that appears.
TIP
The Curve object creates a straight line between clicks so the more often you click the more flexibility you have to curve in different directions.
Creating Flowcharts Almost anyone involved in business has been asked at one time or another to create a flowchart. You don’t need to know what each of the different shapes is used for. A basic flowchart created using only rectangles and lines is a good way to analyze and present the steps of a process. AutoShapes provides all the tools you need to create professional-looking flowcharts with minimal effort. To create a flowchart you need two objects: shapes to represent processes or actions in the chart (and to hold the labels that describe them) and lines to connect the shapes. With AutoShapes, you can create the flowchart shapes and then use Connectors to connect the shapes. After two shapes are connected, they retain their connection when moved. Figure 11.2 shows a simple flowchart using Connectors. To create a flowchart, follow these steps: 1. Select the first Flowchart shape you want to use from the AutoShapes Flowchart menu. Click in your worksheet or within a Drawing Canvas to create the shape. PART
3. Create a second flowchart object and position it appropriately.
III
4. Select a Connector from the Connectors submenu on the AutoShapes menu. 5. Move the pointer into the first flowchart object. Blue handles appear on the sides of the object. 6. Click the handle you want to connect and drag toward the second object. When blue handles appear on the second object, drag the line to connect to the side you want. Release the mouse button to complete the connection. 7. Repeat steps 1–6 until you have completed your flowchart.
Using Charts and Graphics
2. Right-click and choose Add Text to place the shape in Edit mode so you can enter text into the shape. Resize as necessary.
4002c11.qxd 7/18/01 1:13 PM Page 300
300
CHAPTER 11 • Using Drawing and Graphic Tools
FIGURE 11.2 To design a flowchart, create shapes using the Flowchart shapes and then use Connectors to join them all together.
EXPERT TIP
After you have created your flowchart, it’s not always easy to align the objects so that the lines run perpendicular to the worksheet gridlines. Microsoft Draw can do this for you so you don’t have to do it manually. To align flowcharts objects, hold the Ctrl key and click each object to select it. Click the Draw button on the Drawing toolbar, choose Align or Distribute from the menu, and choose Align Center for vertical objects and Align Middle for horizontal objects. You may also want to choose Distribute Horizontally or Distribute Vertically to evenly space the objects in the flowchart.
Adding Line Art Objects Line art objects include AutoShapes, lines, arrows, rectangles, ovals, and text boxes. You can easily insert any of these objects in your worksheet by using the appropriate tool on the Drawing toolbar. The Line and other object buttons work like the Format Painter button: when you have more than one object to draw, begin by double-clicking its button. The button
4002c11.qxd 7/18/01 1:13 PM Page 301
Using Microsoft Draw
301
stays pressed, allowing you to draw more objects, until you click any other drawing object’s button. When you are finished drawing objects, just click the button that is depressed on the Drawing toolbar to turn it off. To draw a line or arrow, follow these steps: 1. Click the Line button or the Arrow button. 2. Move the pointer, which now appears as a crosshair, to the position where you want the line to begin. 3. Hold down the left mouse button and drag to draw the line. 4. Release the button to create the line, and then click the Line or Arrow button to turn off that tool. Unless you originally selected the button with a double-click, the tool turns off automatically when you release the mouse button. When you use the Arrow tool, an arrowhead appears at the end of the line where you released the mouse button.
TIP
If you want a line or arrow that is horizontal or vertical in relation to the page, hold down the Shift key while dragging.
To draw a rectangle or oval, follow these steps: 1. Click the Rectangle or Oval button. 2. Move the pointer, which now appears as a crosshair, to the top-left corner or edge of the object you want to draw. 3. Hold down the left mouse button and drag down and to the right to draw the object. 4. Release the button to create the rectangle or oval and turn off the Drawing tool.
PART
TIP
To create an exact circle or square, hold down the Shift key while dragging.
Because both the rectangle and oval are closed objects, you can add text in them just as you can in the closed AutoShapes. Right-click the object, and then choose Add Text in the shortcut menu to position the insertion point inside the object.
Using Charts and Graphics
III
4002c11.qxd 7/18/01 1:13 PM Page 302
302
CHAPTER 11 • Using Drawing and Graphic Tools
TIP
If you need a series of identical objects, create one object and then copy and paste as many copies of that object as necessary in the locations you want.
Creating and Applying Text Boxes Use the Text Box tool to create text that floats on a layer above standard worksheet text. A text box is a great way to add notes to a worksheet. If you type explanatory text in a text box rather than typing it in a cell, you can resize the text box to accommodate the text, move the text box to an appropriate position on the worksheet, and format the text box so it stands out and adds graphic appeal to the worksheet. The text boxes in Figure 11.3 turn an ordinary invoice into a nicely designed document. FIGURE 11.3 Text boxes add a professional touch to this invoice.
To insert a text box, click the Text Box button on the Drawing toolbar. Draw the text box as you would a rectangle. When you release the mouse button, the text box is active—an insertion point appears in it and a lined border appears around it. Type
4002c11.qxd 7/18/01 1:13 PM Page 303
Using Microsoft Draw
303
the text you want in the active text box. The text box supports word wrap, so don’t press Enter unless you’re starting a new paragraph within the box. When the text box is selected, you can drag it to a different location on the page. You can also use the handles surrounding the selected text box to change its size. This is important, because text boxes do not automatically conform to the size of their contents—in other words, they don’t grow as you add text or shrink when you delete text. To activate a text box when you want to edit or format the text, just click inside the text box to place the insertion point in it. You can then select the text and apply formatting to it using the options and buttons on the Formatting toolbar and the commands on the Format menu. To delete a text box, select the text box by clicking on the text box’s border, then press the Del key on your keyboard. (If the insertion point is displayed in the text box, you’re in edit mode, and pressing Del deletes the next character, not the object.) When you delete a text box, all the text in it is also deleted.
NOTE
To change your text box into a three-dimensional object with color, tints, lines, and shadows, see “Formatting Objects” later in this chapter.
Designing WordArt WordArt is used to create a graphic object out of text. You can use WordArt to create text logos, emphasize titles, and add excitement to a worksheet. For example, you can create a vibrantly colored title page for a proposal or report. To create WordArt follow these steps:
2. Click the style you want for your text graphic in the Select a WordArt Style area. 3. Click OK to display the Edit WordArt Text dialog box, shown in Figure 11.5. 4. Type the text in the Text text box. 5. Use the Font and Size drop-down lists and the Bold and Italics controls to format the text. 6. Click OK to place the WordArt object in your worksheet and display the WordArt toolbar.
PART
III Using Charts and Graphics
1. Place the insertion point where you want the graphic and click the Insert WordArt button on the Drawing toolbar to open the WordArt Gallery dialog box, shown in Figure 11.4. Alternatively, choose Insert Picture WordArt to open the WordArt Gallery dialog box.
4002c11.qxd 7/18/01 1:13 PM Page 304
304
CHAPTER 11 • Using Drawing and Graphic Tools
FIGURE 11.4 You can choose a style for your text graphic in the WordArt Gallery dialog box.
FIGURE 11.5 Type the text for your WordArt graphic in the Edit WordArt text box.
The WordArt toolbar is only displayed when a WordArt object is selected in the worksheet. Use the buttons on the WordArt toolbar, described in Table 11.1, to edit and apply formatting to your WordArt object.
NOTE
To deselect an object, just click anywhere in the worksheet. Deselected objects appear just as they will when the worksheet is printed.
4002c11.qxd 7/18/01 1:13 PM Page 305
Using Microsoft Draw
Button
Wo r d A r t To o l b a r B u t t o n s Name
Use
Insert WordArt
Displays the WordArt Gallery dialog box to create a new WordArt object.
Edit Text
Displays the Edit WordArt Text dialog box to edit text.
WordArt Gallery
Opens the WordArt Gallery dialog box to change the style of the selected WordArt object.
Format WordArt
Opens the Format WordArt dialog box so you can format colors, size, position, and wrap properties.
WordArt Shape
Opens a shape menu so you can select the basic shape into which the text will be poured.
WordArt Same Letter Heights
Makes all letters the same height, irrespective of case.
WordArt Vertical Text
Changes the WordArt orientation from horizontal to vertical. Click again to reverse.
WordArt Alignment
Opens an alignment menu with standard options and unique WordArt options.
WordArt Character Spacing
Opens an adjustment menu so you can change space between characters.
Formatting Objects Even though you can create some pretty cool shapes with the tools on the Drawing toolbar, they are pretty boring without a little formatting. After you create the objects you want, you can add color, lines, fills, and shadows and even make them 3D. Most of the formatting tools you need are available on the Drawing toolbar. If you want even more options, right-click any object and choose Format [Object Type]. To select a single object, just click the object. To select multiple objects, either hold down the Shift key while clicking each object or click the Select Objects tool and drag a rectangle around the objects you want to select. Use the following tools to format a selected object:
PART
III Using Charts and Graphics
TABLE 11.1
305
4002c11.qxd 7/18/01 1:13 PM Page 306
306
CHAPTER 11 • Using Drawing and Graphic Tools
Fill Color Click the drop-down list button to display a palette of colors. If you want an object without any color, choose No Fill. You can drag the Fill Color palette onto your screen as a floating menu, which is useful if you want to apply different fill colors to several objects. You can also choose More Fill Colors on the menu to create a custom color and Fill Effect to apply a gradient, texture, pattern, or a picture as the fill for an object. Line Color Click the Line Color drop-down list button to display the Line Color palette, and then choose a color to apply to the lines in and around the selected object. Like the Fill Color palette, the Line Color palette can be dragged onto your worksheet so it becomes a floating menu. You can create a custom color for the line or apply a pattern to it for different effects. Font Color Click the Font Color drop-down list button to display its palette, and then choose a color for the text in a selected object such as a text box or callout. Drag the Font Color palette to make it a floating menu. You can use it to create custom colors to apply to the text in selected objects.
TIP
Click the Fill Color, Line Color, or Font Color button to apply its current color to a selected object.
Line Style Click the Line Style button to display a menu that contains various line styles and click the style you want for the lines in and around a selected object. Alternatively, select More Lines from the menu to open the Format AutoShape dialog box and display the Colors and Lines page. You can change the line style, color, and weight as well as many other attributes of the selected object.
NOTE
The Format Text Box dialog box, which appears when you double-click the border of a text box, contains options similar to those of the Format AutoShape dialog box. The dialog box allows you to change the fill color, line style, line weight, size, and scale for an object.
Dash Style Click the Dash Style button to display its menu, and then click one of the dashed line styles to apply that style to all of the lines in the selected object. You can change the weight of a dashed line by selecting a different point size in the Line Style menu. To change the lines back to a solid line, select that style in the Dash Style menu.
4002c11.qxd 7/18/01 1:13 PM Page 307
Using Microsoft Draw
307
Arrow Style Click the Arrow Style button, and then select the style in the resulting menu to apply to the ends of the selected line. You can choose an arrowhead or one of various other line terminators. If the combination of line endings you want isn’t in the menu, choose More Arrows to display the Format AutoShape dialog box, set a beginning and ending style for the line, and then click OK. Arrow styles can be applied only to lines, arrows, and open AutoShapes. The Draw menu, which appears when you click the Draw button on the Drawing toolbar, also contains some commands that allow you to change the appearance of a selected object. These commands include the following: Edit Points Changes the appearance of a Curve, Freeform, or Scribble AutoShape. When you do, each position in which you clicked your mouse while drawing the AutoShape appears with a small, black move handle. Drag the handle to change its position, thereby changing the appearance of the AutoShape. Change AutoShape Replaces the current AutoShape with a different one. When you choose Change AutoShape, the AutoShapes menu appears. Choose the category that contains the AutoShape, and then choose the replacement. Any text in the AutoShape remains in the new shape.
NOTE
You cannot use the Change AutoShape command to change the shape of a Line AutoShape. Instead, you must use the Edit Points command and drag the endpoints to different positions. Alternatively, you can delete a Line AutoShape and insert an AutoShape in a different category.
Special Shadow and 3D Effects Shadow and 3D effects are designed to give a selected drawing object more depth. You cannot apply both shadow and 3D formatting to an object. If you apply a 3D effect to a shadowed object, the shadow is removed. Any drawing object can have either a shadow or a 3D effect applied to it. If you apply a shadow to an object that has 3D formatting, the 3D effect is removed. Click the Shadow button to display a menu of various shadow styles, and then click the style you want for the selected object. To change the format of the shadow, click the Shadow button again, and then choose Shadow Settings to display the Shadow Settings toolbar. The toolbar buttons and their uses are described in Table 11.2.
PART
III Using Charts and Graphics
Set AutoShape Defaults Inserts subsequent AutoShapes of the kind selected with the same formatting applied. Every new AutoShape of that type will appear in the same size, color, and such, until you specify a different default.
4002c11.qxd 7/18/01 1:13 PM Page 308
308
CHAPTER 11 • Using Drawing and Graphic Tools
T ABLE 11.2: Button
Th e S h a d o w S e t t i n g s To o l b a r B u t t o n s Name
Use
Shadow On/Off
Displays or removes the object’s shadow.
Nudge Shadow Up
Pushes the shadow up.
Nudge Shadow Down
Pushes the shadow down.
Nudge Shadow Left
Pushes the shadow to the left.
Nudge Shadow Right
Pushes the shadow to the right.
Shadow Color
Displays a palette so you can select the color for the shadow.
To choose the 3D effect to apply to a selected object, click the 3-D button on the Drawing toolbar, and then click the option you want in the menu that appears. To change the formatting applied to the 3D effect, click the 3-D button again, and then choose 3-D Settings to display the 3-D Settings toolbar. Table 11.3 shows how to use the buttons on the toolbar to quickly change the format of the 3D effect.
TABLE 11.3 Button
Th e 3 - D S e t t i n g s To o l b a r B u t t o n s
Name
Use
3-D On/Off
Hides or displays the 3D effect applied to the object.
Tilt Down
Tilts the object “toward” the user.
Tilt Up
Tilts the object “away from” the user.
Tilt Left
Rotates the 3D effect to the left.
Tilt Right
Rotates the 3D effect to the right.
Depth
Allows you to select or specify a different depth for the 3D effect.
4002c11.qxd 7/18/01 1:13 PM Page 309
Using Microsoft Draw
TABLE 11.3 Button
309
Th e 3 - D S e t t i n g s To o l b a r B u t t o n s ( c o n t i n u e d )
Name
Use
Direction
Allows you to select the direction the 3D effect points to and to specify whether the direction is Perspective (extends all sides of the effect to a single point) or Parallel (extends all sides of the effect parallel to one another).
Lighting
Adjusts the position and intensity of the “light” shining on the 3D effect to present a different appearance.
Surface
Allows you to select the appearance of the composition of the 3D effect.
3-D Color
Displays a palette so you can select the color for the 3D effect.
Arranging Objects The Draw menu on the Drawing toolbar includes other options for manipulating objects. For example, you can change the position of a selected object on the page, display a grid to help you position an object precisely, and even group objects in order to move or edit them simultaneously. Drawing objects are placed in separate layers on top of the text in a worksheet, in the order in which they were created. If you have several overlapping objects, it may be helpful to choose which object is “on top,” which is next, and so on. To move objects from layer to layer follow these steps: 1. Select the object you want to reposition.
3. Choose one of the following options to change the order of the selected drawing object: • Choose Bring to Front to place the selection above (on the top layer of) all other graphic objects. Choose Send to Back to place the selection below (on the bottom layer of) all other graphic objects. • Choose Bring Forward or Send Backward to move the selected object one layer at a time.
PART
III Using Charts and Graphics
2. Click the Draw button and choose Order to display the Order menu. If necessary, drag the menu by its title bar to display the Order toolbar.
4002c11.qxd 7/18/01 1:13 PM Page 310
310
CHAPTER 11 • Using Drawing and Graphic Tools
Snapping to the Invisible Grid
If you’re doing detailed work, you can line up objects to the cell borders in an Excel worksheet or to other objects in the worksheet by turning on Snap to Grid or Snap to Shape. Snap to Grid works by automatically pulling each object you draw into alignment with the nearest cell border. Snap to Shape aligns objects with invisible horizontal or vertical gridlines that run through the edges of other shapes in your worksheet. Snap to Grid turns on automatically if you have turned on Snap to Shape. You can also turn on Snap to Grid by following these steps: 1. Click the Draw button on the Drawing toolbar. 2. Choose Snap To Grid to toggle the grid on and off.
When Snap to Grid is turned on, you can move objects only in increments of cell heights and widths. When Snap to Grid is off, you can move objects freely around the worksheet. To turn on Snap to Shape, follow these steps: 1. Click the Draw button on the Drawing toolbar. 2. Choose Snap To Shape to automatically align drawing objects with the horizontal and vertical edges of other drawing objects. Snap to Shape is also a toggle. When it is turned on, you have more flexibility to align the object with another object rather than just to cell borders.
Aligning Objects
There are several other ways to adjust the positions of selected objects in a drawing. Click the Draw button on the Drawing toolbar and then choose from the following: • Nudge (Up, Down, Left, or Right) to move the selection incrementally. • Align or Distribute to set alignment options relative to other objects. To use these options, you must select more than one object. • Rotate or Flip to change the orientation or direction of an object.
4002c11.qxd 7/18/01 1:13 PM Page 311
Using Microsoft Draw
311
TIP
To nudge using the keyboard, select the object, then hold the Ctrl key and use the arrow keys. Nudging overrides the Snap to Grid setting.
Grouping and Ungrouping Objects When your drawing is complete, you can group all the drawing objects so that they are treated as a single object. When objects are grouped, you can select all of the objects by selecting any one object in the group. Any formatting you apply is applied to every object in the group. For example, if you have selected a group of AutoShapes and you choose to apply a shadow, the shadow appears on each object in the group. You can also use the Nudge, Align or Distribute, and Rotate or Flip commands to manipulate the position of the group, or you can simply drag the group to a new location on the page to move every object in the group. Grouped objects don’t need to be in close proximity. It is easy to combine several objects into a group: 1. Hold down the Shift key while you click each object to select it. 2. Click the Draw button on the Drawing toolbar and choose Group. The handles on the multiple selected objects are replaced with one set of handles that can be used to size or move the entire object. If you want to move, resize, format, or delete an individual element in a group, you can ungroup the grouped object, thereby changing the group back into separate objects. Each object can then be edited independently of the group. Follow these steps to ungroup a grouped object: 1. Click the group to select it. 2. Click the Draw button on the Drawing toolbar and choose Ungroup. Alternatively, right-click the group and choose Grouping Ungroup.
PART
TIP Clip art images are often composed of a group of objects. To change the appearance of a clip art object, ungroup it and then edit individual objects as necessary. Excel may tell you that it first needs to convert the object to a Microsoft Drawing object. Tell it OK, and you can then manipulate the object any way you want. When you have finished editing, you may want to regroup the objects so you can move or size the entire image. You’ll be pleased to note that you don’t have to reselect
Using Charts and Graphics
III
4002c11.qxd 7/18/01 1:13 PM Page 312
312
CHAPTER 11 • Using Drawing and Graphic Tools
every single object from the original group. To regroup an ungrouped set of objects, follow these steps: 1. Select any object that was previously in the group. 2. Click the Draw button on the Drawing toolbar and choose Regroup. Alternatively, right-click the object and choose Grouping Regroup.
TIP
To add new objects to a group, select the group and the additional objects, then choose Draw Group again.
Constructing Diagrams and Organizational Charts Microsoft Org Chart has been available as an add-in application for many versions of Office. For the first time, however, you can create organizational charts as a built-in feature of Excel. In addition, you can create other types of diagrams such as Cycle and Venn diagrams. To create a diagram, click the Insert Diagram or Organizational Chart button on the Drawing toolbar. This opens the Diagram Gallery, shown in Figure 11.6, from which you can choose a diagram type.
FIGURE 11.6 Choose from several diagram types in the new Diagram Gallery.
Table 11.4 shows the types of diagrams you can choose and how you can use them; the section that follows explains how to use the diagram tools in Excel 2002.
4002c11.qxd 7/18/01 1:13 PM Page 313
Using Microsoft Draw
TABLE 11.4 Diagram
313
Ty p e s o f D i a g r a m s Name
Use
Organizational chart
Shows organizational relationships between people or departments.
Cycle diagram
Represents a process that has a continuous cycle.
Radial diagram
Shows relationships of multiple entities/concepts to a central point.
Pyramid diagram
Illustrates entities or concepts that are based on a foundation.
Venn diagram
Demonstrates entities that overlap.
Target diagram
Identifies steps toward a central goal.
Creating an Organizational Chart
NOTE
If you work in a company that has a nontraditional organizational structure—for example, shared leadership, a partnership, or another less hierarchical structure—you have to be creative to represent your structure with this tool. You cannot position more than one box at the top level. To work around this limitation, you might want to use the top level to represent your company, board, or your customers or other stakeholders. Or rightclick the top level shape and choose Format AutoShape, then set the Colors and Lines options to make it invisible (no line and no fill). Another option is to create your organizational chart using AutoShapes and Connectors (see “Inserting AutoShapes” and “Creating Flowcharts” earlier in the chapter).
PART
III Using Charts and Graphics
When you select the Organizational Chart from the Diagram Gallery, Office creates an organizational chart object with four boxes: one manager and three subordinates, as shown in Figure 11.7. The Organization Chart toolbar also turns on by default. You can add, delete, and reposition boxes to fit your specific needs. Click in any of the boxes to enter up to two lines of text. To add additional boxes, select one box to which the new box is related and choose Insert Shape from the Organization Chart toolbar. Click the down arrow on the Insert Shape button, to add a subordinate, coworker, or assistant. To delete a box, select it and then press Del.
4002c11.qxd 7/18/01 1:13 PM Page 314
314
CHAPTER 11 • Using Drawing and Graphic Tools
FIGURE 11.7 An Org Chart object, shown here with the Organization Chart toolbar, gives you a head start on creating your organizational chart.
Changing the Layout of the Org Chart The Layout button on the Organization Chart toolbar gives you options to change the layout of your chart from the standard horizontal configuration to one that is more vertical. To change the layout, select the manager shape at the top of the section you want to alter and then select Both Hanging, Left Hanging, and Right Hanging (and, no, we’re not talking about chads on Florida’s ballots) from the Layout dropdown menu on the Organization Chart toolbar. You can also change the size of the org chart object by choosing Fit Organizational Chart to Contents, Expand Organizational Chart, or Scale Organizational Chart from the Layout menu. To have Office automatically rearrange and resize the org chart to fit the object frame, choose AutoLayout from the Layout menu.
Selecting Sections of the Org Chart As charts become more complex, it becomes harder to select individual sections that you want to move or alter in some way. You can use the Select button on the
4002c11.qxd 7/18/01 1:13 PM Page 315
Using Microsoft Draw
315
Organization Chart toolbar to do your selecting for you. Select the first box in a section you want to select and then choose from the following: Level Branch
Selects all the boxes on the same level. Selects this box and all subordinates.
All Assistants
Selects the assistants in the branch you select.
All Connecting Lines
Selects all connecting lines.
Applying Styles from the Style Gallery To make your org chart stand out, click the AutoFormat button on the Organization Chart toolbar. This opens the Organization Chart Style Gallery shown in Figure 11.8. From here, you can choose a style for your chart that affects the box shape and style, colors, fills, and lines.
FIGURE 11.8 Choose a style from the Organization Chart Style Gallery to autoformat your organizational chart.
PART
Creating Conceptual Diagrams The other five types of diagrams available from the Diagram Gallery when you click the Insert Diagram or Organizational Chart button on the Drawing toolbar can be used interchangeably to represent a process or related concepts. Select the type of diagram that most closely resembles the message you want to communicate. See Table 11.3 earlier to review the types of diagrams and how they can be used.
Using Charts and Graphics
III
4002c11.qxd 7/18/01 1:13 PM Page 316
316
CHAPTER 11 • Using Drawing and Graphic Tools
The Diagram toolbar, shown in Figure 11.9, is similar to the Organization Chart toolbar with only a couple of exceptions. FIGURE 11.9 Use the Diagram toolbar to add elements and format the diagram.
In addition to the Insert Shape, Layout, AutoFormat, and Text Wrapping buttons, you also have the ability to change the level or position of a particular shape using the Move Shape Backward, Move Shape Forward, and Reverse Diagram buttons. You can use the Change To button to convert a diagram from one type to another—for example, if you created a Pyramid diagram but now feel a Venn diagram would better communicate your message.
Accessing Clips from Microsoft Clip Organizer In the first part of this chapter, you’ve had to rely on the right side of your brain to create graphic objects one element at a time. If you’ve discovered that you are better off leaving drawing to the professionals, you can breathe a sigh of relief, because now we’ll show you how to access clip art and other objects created by people who get paid to do this sort of thing. You can insert clips into your worksheets and use the Clip Organizer to organize all your pictures and multimedia files for use in Excel and other applications. Microsoft Clip Organizer, formerly the Microsoft Clip Gallery, has been dramatically revised for Office XP. Shared by Excel 2002 and all of the other Office applications, the Clip Organizer contains an even broader selection of clips, including pictures, sounds, and motion clips. Although you can still browse the clips by category (referred to as collections), it is now much easier to search for clips by topic or style. In addition, it is even simpler to add clips from your own collection or download additional clips directly from Microsoft’s online clip gallery, Microsoft Design Gallery Live. Finally, the Clip Organizer is a great place to catalog and manage all of the graphics, sound files, and animated graphics files you have stored anywhere on your system.
4002c11.qxd 7/19/01 2:19 PM Page 317
Accessing Clips from Microsoft Clip Organizer
317
In Excel 2002, the Insert Clip Art task pane offers options for searching or organizing clips. You can quickly access clips online or examine tips for finding the perfect clip.
NOTE
Not all of the clips listed in the Clip Organizer are installed in a typical installation. When you insert a clip that is not installed, you may be prompted to insert the Office XP CD that contains the clip.
To access clip art, click the Insert Clip Art button on the Drawing toolbar or choose Insert Picture Clip Art to display the task pane with clip art options as shown in Figure 11.10. The first time you do this you are prompted to catalog your media files. You’ll have better luck searching for clips if you let Office do this, and it only takes a few minutes.
FIGURE 11.10 The Insert Clip Art task pane allows you to search for and insert clip art from a number of sources.
PART
Searching for the Clip You Want Microsoft assumes you are probably too busy to spend time browsing hundreds of images to find the perfect image to illustrate a concept in your worksheet. The task pane gives you immediate access to the Clip Organizer’s built-in Search feature. Search saves time, frustration, and that inevitable feeling of “any clip will do” that
Using Charts and Graphics
III
4002c11.qxd 7/19/01 2:19 PM Page 318
318
CHAPTER 11 • Using Drawing and Graphic Tools
comes from browsing through the vast clip collection. To search for a specific type of clip, follow these steps: 1. Enter a keyword or two in the Search Text box. (See Table 11.5 for tips on what to enter.) 2. Choose which collection(s) you wish to search by selecting from the Search In drop-down list. 3. Choose the type of file you’re looking for—clip art, photographs, movies, or sound—in the Results Should Be list. 4. Click the Search button to display clips that meet your criteria. Figure 11.11 shows results of an Office Collections keyword search on business, computer.
TABLE 11.5
S e a r c h Ti p s
Search For
Results to Expect
A particular word: school
Clips that are cataloged with school as a keyword
Multiple words separated by commas: school, teacher
Clips that have one or both of the keywords you typed
Words in quotes: “school teacher”
Clips that have school teacher as a keyword
Multiple words without quotes or commas: school teacher
Clips that have both keywords you typed
Filenames with wildcards: sc*.jpg
Media clips with filenames such as school.jpg and
scooter.jpg
FIGURE 11.11 The Insert Clip Art task pane displays search results.
4002c11.qxd 7/19/01 2:19 PM Page 319
Accessing Clips from Microsoft Clip Organizer
319
Scroll through the search results to find the clip(s) you want to use. To see more clips at one time, click the Expand icon at the top of the pane. If you wish to search again, click the Modify button to modify the search criteria. When you move the mouse over a clip, a drop-down indicator, called the Clip Options button, appears on its right border. Click it to see a shortcut menu with options for things you can do to that clip.
To insert a clip, click it. (You can also choose Insert from the shortcut menu if you’ve displayed it.) After the clip is placed in your worksheet, chances are you will want to adjust its size and position. See “Inserting Pictures into Worksheets,” later in this chapter.
Finding Similar Clips
Exploring Your Clip Collection Using Microsoft Clip Organizer’s new Explorer interface, shown in Figure 11.12, you can browse your stored clips and reorganize clips using the file management tools you already know, such as cut, copy, paste, and drag and drop.
PART
III Using Charts and Graphics
When you’ve found the perfect clip, you can instruct the Clip Organizer to find additional clips that share a similar design style with the first one: for example, all the Art Deco clips or all the cartoon clips of bulky guys in suits. Click the clip’s drop-down menu and choose Find Similar Style. The results may have nothing in common with the content of the original clip except the style, but you can use this feature when you want to provide a consistent look throughout your workbook.
4002c11.qxd 7/18/01 1:13 PM Page 320
320
CHAPTER 11 • Using Drawing and Graphic Tools
FIGURE 11.12 Microsoft Clip Organizer’s Explorer interface lets you preview your clips and use file management tools to organize them into collections.
Clips are stored in folders on your local drive or network drives. Clips are assigned to one or more collections, categories that cross folders. If you assign clips to collections, you don’t need to know where a clip is stored to use it in a worksheet. And more importantly, you can store images where they belong in your folder structure (for example, pictures from a client site in the client’s folder) and access them using the Clip Organizer. You can create new collections and move and copy clips into existing collections. The Clip Organizer automatically creates at least three collections in the My Collections folder (you may have more, depending on your operating system and the profiles on your computer): Favorites Your most frequently used clips, such as your company’s logo or other similar clips. Unclassified Clips Clips that you have not added to other collections. Included in this collection are clips that the Clip Organizer identifies when it reviews your system to look for media clips. Pictures Photographs or other clips that you want to classify as Pictures. Depending on your operating system, this collection, which is a folder, may also be called My Pictures and may be listed under your user name\My Documents\My Pictures.
4002c11.qxd 7/18/01 1:13 PM Page 321
Accessing Clips from Microsoft Clip
321
In addition, the Clip Organizer creates folders of Office Collections and Web Collections. The Office Collections folder holds the media clips that come with Office. Click the Expand button (plus symbol) in front of Office Collections to see the list of included collections. The Web Collections folder lets you access media clips from Microsoft’s online clip gallery, the Design Gallery Live. You must be connected to the Internet to access the clips in Web Collections. Expand the folder and then select a collection just like you did in the Office Collections folder. The only difference is that the clips that appear are from an ever-changing collection on the Web.
TIP Microsoft Clip Organizer is a freestanding application you can also launch directly from the Programs menu: Start Programs Microsoft Office Tools Clip Organizer. You can organize your clips, import clips from other sources, search and browse clips, and insert clips into applications that are not part of the Office suite.
Browsing the Collections Some collections have subcollections that you can also access by clicking the Expand button in front of them. You know when a collection contains clips because thumbnails of the clips appear in the right pane, as shown earlier in Figure 11.12.
If you’d prefer to see a list of the media files, choose View List. Choose View Details to see Name, Size, Type, Caption, Keywords, Duration, and Date.
TIP
Movie files, or animations, are designated by the yellow star in the bottom-right corner.
NOTE Animated graphics are only animated when displayed in a web browser or viewed in a PowerPoint slide show. They do not animate when inserted into Excel worksheets unless you preview the page in a browser (File Web Page Preview).
PART
III Using Charts and Graphics
You can distinguish sound files by the speaker icon and file name that appear in place of an image.
4002c11.qxd 7/18/01 1:13 PM Page 322
322
CHAPTER 11 • Using Drawing and Graphic Tools
Organizing the Clips You Find After you find the perfect clips, you can save future searching time by adding them to the Favorites collection or to another collection of your choice. For either option, point to the clip in the task pane and then click the Clip Options button to open the shortcut menu. Choose Copy to Collection or, if it’s a clip that is not part of the original Clip Organizer, choose Move to Collection. This opens the Copy to Collection dialog box shown in Figure 11.13. Choose Favorites or select another collection from the list. After you choose the collection you want, click OK to add the clip to that category and close the dialog box. FIGURE 11.13 You can copy media clips to other collections using the Copy to Collection dialog box.
TIP Press and hold the Ctrl key to select multiple clips that you want to move or copy to a collection. To select contiguous clips, press and hold the Shift key to select the first and last clip you want to move or copy.
Creating a New Collection If you would like to create a new collection, open the Copy to Collection dialog box (see previous section) and click the New button or, in Clip Organizer click any of the
4002c11.qxd 7/18/01 1:13 PM Page 323
Accessing Clips from Microsoft Clip
323
collections in the My Collections folder and choose File New Collection. This opens the New Collection dialog box.
Enter the name of the new collection and select the folder you would like it to be a part of. When you click OK, the new collection appears in the list.
NOTE You can’t create a new collection in the Office Collections or Web Collections folders. You must select a folder in My Collections before attempting to create a new collection.
Assigning Keywords to Clips
1. Point to the clip you want to change. 2. Click the Clip Options button and chose Edit Keywords from the shortcut menu. This opens a Keywords dialog box, such as the one shown in Figure 11.14. 3. To edit the keywords of each clip individually, use the Clip by Clip tab. 4. To delete a keyword, select the keyword you want to delete and click the Delete button.
PART
III Using Charts and Graphics
To make it easier to find clips, clips can be assigned keywords, which are used by the Clip Organizer’s Search tool to locate the clips you are searching for. The media files that come with Office already have keywords assigned. Figure 11.14 shows a piece of clip art and the accompanying keywords that will help you find this clip. You can add additional keywords and delete existing keywords from any of the clips in My Collections. To add, delete, or modify keywords of individual clips, follow these steps:
4002c11.qxd 7/18/01 1:13 PM Page 324
324
CHAPTER 11 • Using Drawing and Graphic Tools
5. To add a keyword, click in the Keyword text box and enter the new keyword or, if it’s a keyword you’ve added previously, select it from the drop-down list. Click the Add button. 6. To modify a keyword, select the keyword, make the editing changes you want and click the Modify button. 7. Click the Next button to edit the keywords of the next clip or click OK to apply the changes and close the dialog box.
FIGURE 11.14 A variety of keywords make it easier to find the clips you are looking for.
To add, delete, or modify keywords of a group of clips, select the clips you want to edit: to select multiple clips, hold the Ctrl key and click each clip; to select multiple contiguous clips, click the first clip and hold Shift while you click the last clip. Then follow steps 2–7, selecting the All Clips at Once tab, shown in Figure 11.15, to make your edits.
EXPERT TIP
If you are editing clips in My Collections, you might also want to add a caption to the clip. The caption appears when you point to the clip’s thumbnail in the Clip Organizer. If a clip does not have a caption, the list of keywords appears when you point to the thumbnail. To add a caption, right-click the thumbnail and choose Edit Keywords. Enter the caption in the Caption text box of the Clip by Clip page and click OK. Also remember to edit keywords if you’ve added clips to the Clip Organizer (see “Improving Your Clip Collection” later in this chapter) or if you have copied clips to a new collection for use in a specific project.
4002c11.qxd 7/18/01 1:13 PM Page 325
Accessing Clips from Microsoft Clip
325
FIGURE 11.15 Use the All Clips at Once tab to add, delete, or modify keywords for multiple clips in My Collections.
NOTE
You can add and delete keywords from a clip in the Office Collections and Web Collections folders only if you’ve previously copied the clip to My Collections.
Organizing Clips According to Your Own Projects PART
III Using Charts and Graphics
One of the best ways to gain control of your clips is to create your own collections and keywords and organize the clips according to the projects you’re working on. Let’s say, for example, you produce a monthly newsletter for your department or organization. You can create a collection for the newsletter and copy all the design clips that designate special sections of the newsletter to this collection. To make using clips even easier, you can add custom keywords and captions to help you quickly find all the clips you need through a keyword search. If you’re really organized, create collections to organize photographs of your company’s products, your company logos, and photos of key employees to use as you need them. (See “Importing Clips into the Clip Organizer” later in this chapter to add your own photos to the Clip Organizer.) As you are preparing for the next issue, continue to organize the artwork as you go along. When you are ready to produce the newsletter, all the art you need is right at your fingertips.
4002c11.qxd 7/18/01 1:13 PM Page 326
326
CHAPTER 11 • Using Drawing and Graphic Tools
Improving Your Clip Collection The Clip Organizer is not limited to the clips that come with Microsoft Office. If you really want to make it useful, add all your photographs, clip art, sound files, and motion clips, even if they come with their own cataloging software. Having one-stop shopping for all your clips makes using clips more convenient and improves the overall quality of your work by offering you the greatest number of choices. You can add existing clips to your collections, and download clips from Microsoft’s Design Gallery Live as you need them.
Importing Clips into the Clip Organizer When you import clips into the Clip Organizer, you have three options for handling the import process. To access any of these options, choose File Add Clips to Organizer. From here, you can choose the following: Automatically Searches your hard drive for graphic, sound, and motion files and adds them to the Clip Organizer for you. The clips are added to a collection called Unclassified Clips. Keep in mind that when you choose this option, the Clip Organizer may even add clips used by applications and websites that you’ve accessed. On My Own Adds clips you select to the Clip Organizer. Click the Add To button in the Add Clips to Organizer dialog box to specify which collection to add the clips to. From Scanner or Camera Imports clips directly from an installed scanner or camera. If the scanner or camera you plan to use does not appear in the Device dropdown list, make sure the device is properly installed and working.
Removing Clips from the Clip Organizer
In both the Automatically and On My Own options, the Clip Organizer creates a shortcut to the clip files but does not change their file locations. If you delete a clip from the Clip Organizer, the file is still available in its original location. To delete a selected clip from the Clip Organizer, select Delete from Clip Organizer from the Clip Options shortcut menu or click the Delete from Clip Organizer button on the Clip Organizer toolbar. This option deletes the clip from all Clip Organizer collections it is in.
4002c11.qxd 7/18/01 1:13 PM Page 327
Accessing Clips from Microsoft Clip
327
To delete a clip from a specific collection, choose Delete from Collection Name from the Clip Options shortcut menu.
Accessing Shared Clip Organizer Catalogs If your company’s system administrator has created shared Clip Organizer catalogs and made them available on the server, you can add them to your Clip Organizer by choosing File Add Clips to Organizer On My Own and choosing Shared Catalogs (*.mgc) from the Files of Type drop-down list in the Add Clips to Catalogs dialog box. Locate the shared catalog and click Add to include the catalog in your Clip Organizer.
NOTE
To access the clips in a shared catalog, you have to be logged on to the network and have access to the file location where they are stored.
Finding New Clips on Microsoft Design Gallery Live Microsoft has made sure that you have all the clips you need by posting a special website just for Clip Organizer users. This site is filled with over 100,000 clips, including clip art, photographs, sound clips, and motion files. The site is updated regularly and always has featured clips based on the season or upcoming holidays. To access Microsoft Design Gallery Live, click the Clips Online button on the Clip Organizer toolbar or the link from the Insert Clip Art task pane.
NOTE
The first time you access Microsoft Design Gallery Live, you have to accept the Addendum to the Microsoft End User License Agreement.
1. Enter a search term in the Search For text box (see Figure 11.16). To get the best results, be descriptive but not too precise. For example, if you wanted clips of women basketball players, search for basketball players. Basketball would give you balls, nets, and players and women basketball players would return no clips.
PART
III Using Charts and Graphics
In the Design Gallery Live, you can browse by category or search for keywords. Searching is the best way to find what you are looking for quickly. To search, follow these steps:
4002c11.qxd 7/18/01 1:13 PM Page 328
328
CHAPTER 11 • Using Drawing and Graphic Tools
2. Choose a category from the Search In drop-down list. If you are unsure, choose Everywhere. 3. Choose the type of results you want from the Results Should Be drop-down list: Anything, Clip Art, Photos, Sound, or Motion. 4. Choose the order you want the results to appear in from the Order By dropdown list: Newer, File Size, or Media Type.
FIGURE 11.16 Microsoft Design Gallery Live is a great place to find clip art, photos, sounds, and motion clips.
When you get results, use the page controls in the top-left corner of the page to see additional pages of clips.
4002c11.qxd 7/18/01 1:13 PM Page 329
Accessing Clips from Microsoft Clip
329
When you find the clips you want, you can download them one at a time or you can collect them all first and then download them all at once. To download them one at a time, click the drive icon with the downward-pointing red arrow at the base of the clip.
EXPERT TIP If you access Design Gallery Live from a fast Internet connection, you may want to increase the number of clips that Design Gallery Live displays on a page. Click the Options link in the top navigation bar of Design Gallery Live to change the grid size by increasing the number of columns and rows and then clicking Update. If you notice too much degradation in speed, go back to Options and choose Restore Defaults. The clip is immediately downloaded and the Clip Organizer opens, showing only the downloaded clip. Right-click the clip to add a caption, recategorize it, and edit the keyword list (the clip comes with keywords already assigned). Close the Clip Organizer and reopen it to see all the Clip Organizer clips.
NOTE If Microsoft Clip Organizer is not running when you download the clip, you can find your new clips by clicking the Downloaded Clips category the next time you launch the Clip Organizer. PART
III Using Charts and Graphics
Clip Gallery Live allows you to collect clips and download them all at once. Just click the check box under a clip to select it. If you want all the visible clips, click the Select All link. As you add clips to the download, you will notice the counter at the top of the page increase. When you are ready to download the files, click the Download n Clips link. When you are ready, click Download Now.
4002c11.qxd 7/18/01 1:13 PM Page 330
330
CHAPTER 11 • Using Drawing and Graphic Tools
EXPERT TIP
Microsoft Clip Organizer maintains a database of the clips, captions, collections, keywords, and other properties. Proper maintenance of this catalog, especially if you have added or deleted clips from the catalog, makes it run faster and with fewer problems. On a routine basis, you can compact the catalog and repair any corrupted data by choosing Tools Compact from the Clip Organizer menu.
Inserting Pictures into Worksheets Finding the perfect clips is more than half the battle. Positioning them in your worksheet so they enhance rather than detract from your message is the rest. Excel makes it easy to work with pictures, but knowing a few tricks will give you full control of how your clips appear in your worksheets. To insert a clip into a worksheet, click the clip in the Insert Clip Art task pane. When you insert a picture, the top of the clip aligns with the top of the cell at the location of the cell pointer, so it’s helpful to position your cell pointer before you insert the clip. You can reposition the picture by pointing to the clip and dragging it with the four-headed arrow pointer to a different location on the worksheet.
Resizing Clip Art When you click a picture (or any object) to select it, eight handles appear around the outside: four at the corners and one on each side. When you point to any one of these handles, the pointer changes to a two-headed resize arrow. Drag any handle to resize the object in the desired direction. Drag one of the corner handles if you want to resize the object while maintaining the object’s original proportions.
NOTE As long as you resize a picture using a corner handle, Excel 2002 automatically maintains the picture’s original proportions. To turn this feature off, clear the Lock Aspect Ratio check box on the Size tab in the Format Picture dialog box (to get to the Format Picture dialog box, right-click the picture and choose Format Picture). You can still maintain proportions even with this option turned off by holding the Shift key while dragging a corner handle.
4002c11.qxd 7/18/01 1:13 PM Page 331
Inserting Pictures into Worksheets
331
Modifying Pictures with the Picture Toolbar Although Excel does not have the features of photo-editing software such as Microsoft Photo Editor or a third-party photo-editing package such as Adobe PhotoShop, you still have some basic editing options available to you within Excel. When you want to change a picture by adjusting the contrast or brightness, setting the transparency, or cropping it, the Picture toolbar may just have the tools you need. Table 11.6 describes the buttons you can find on the Picture toolbar.
Button
Th e P i c t u r e To o l b a r B u t t o n s Name
Use
Insert Picture from File
Opens the Insert Picture dialog box so you can insert a picture from a file.
Color
Determines the appearance of the picture: Automatic (applies the most appropriate format, usually the default colors); Grayscale (converts each color to a shade of gray); Black & White (changes each color to black or white, converting the image to line art); or Washout (changes the picture to a low-contrast format like a watermark image).
More Contrast
Increases color intensity.
Less Contrast
Decreases color intensity.
More Brightness
Adds white to lighten the colors.
Less Brightness
Adds black to darken the colors.
Crop
Trims rectangular areas from the image.
III
Rotate Left
Rotates the picture 90 degrees counterclockwise with each click.
Line Style
Formats the border that surrounds the picture.
Compress Pictures
Reduces the size of graphics by changing the resolution of the picture for web/screen and print uses, compressing the picture by applying JPEG compression to highcolor pictures (may result in a loss of quality), and deleting cropped areas of a picture.
Using Charts and Graphics
TABLE 11.6
PART
4002c11.qxd 7/18/01 1:13 PM Page 332
332
CHAPTER 11 • Using Drawing and Graphic Tools
TABLE 11.6 Button
Th e P i c t u r e To o l b a r B u t t o n s ( c o n t i n u e d ) Name
Use
Format Picture/Object
Displays the Picture tab in the Format Object dialog box so you can change the format to exact specifications.
Set Transparent Color
Used like an eyedropper to make areas of JPEG pictures transparent. Used extensively in web design.
Reset Picture
Returns the picture to its original format.
NOTE
The Crop and Set Transparent Color buttons are used with areas of the picture. All other buttons affect the entire picture.
Gaining Control of Size and Other Properties You can access a number of formatting options by clicking the Format Picture button on the Picture toolbar. The Format Picture dialog box opens by default to the Picture tab, shown in Figure 11.17. The dialog box is dependent on the file type of the selected picture. If, for example, the picture is a Windows Metafile, the dialog box includes a Colors and Lines tab. If the picture is a GIF, there is no Colors and Lines tab. If a dialog box control is not enabled, the property is not available for that file type or is available but cannot be changed by the user. On the Colors and Lines tab, set the fill color and transparency level for the fill and line (outside border) properties including color, style, and weight. This tab is not displayed for all file types. On the Picture tab, you can adjust the crop settings, as well as color, brightness, and contrast of the image using more precise settings than you can find on the Picture toolbar. To adjust the size properties, click the Size tab of the Format Picture dialog box to change the height, width, and rotation of the image. If you want to protect the image from being moved, resized, or changed, click the Protection tab and select the Locked check box. Protection is not enabled until you also protect the worksheet (Tools Protection Protect Sheet).
4002c11.qxd 7/18/01 1:13 PM Page 333
Inserting Pictures into Worksheets
333
FIGURE 11.17 In the Format Picture dialog box, you can adjust picture properties such as image control, size, and object positioning.
To control how an object responds when you move and resize cells, click the Properties tab and then select one of the following options: • Select Move and Size with Cells if you want the object to move and change when you move the cells that surround it or when you resize rows or columns. • Choose Move but Don’t Size with Cells (the default choice) if you would like to maintain the relationship between the surrounding cells and the object but not change the size of the object when you resize the rows and columns. • Choose Don’t Move or Size with Cells if you would like the object to stay where you position it. PART
III Using Charts and Graphics
Clear the Print Object check box if you do not want to print the object when you print the worksheet. Use the Web tab if you are going to publish the worksheet on an intranet or the Internet and you would like alternative text to appear while the object is loading. Alternative text is also used by people who use a text reader because of vision impairment and can be used by search engines to catalogue the images in your site.
4002c11.qxd 7/18/01 1:13 PM Page 334
334
CHAPTER 11 • Using Drawing and Graphic Tools
TIP Many of the settings you learned about in this section in relation to pictures, such as the options on the Picture toolbar and the Format Picture dialog box, can be applied to any object you insert into an Excel worksheet regardless of the source application—Excel charts, Microsoft Draw objects, WordArt objects, and so on. The Picture toolbar is not automatically displayed when you select objects other than pictures. To display the toolbar, right-click any toolbar and choose Picture from the shortcut menu.
Rotating Images At the top of each picture you insert into a document is a green-filled circle above the center handle. This is the Free Rotate tool and it allows you to rotate the picture in any direction. When you point to the tool, the pointer changes to a circular arrow. When you click the arrow, the pointer changes to four circular arrows. Drag the pointer to rotate the image.
4002c11.qxd 7/18/01 1:13 PM Page 335
Inserting Pictures from Other Sources
335
Inserting Pictures from Other Sources In addition to using the Clip Organizer as a source of art, you can insert pictures into your worksheet from any file you can access. You can also format pictures inserted from a file by using the buttons on the Picture toolbar. To insert a picture that isn’t in the Clip Organizer, follow these steps: 1. Choose Insert Picture From File or display the Picture toolbar and click the Insert Picture from File button to open the Insert Picture dialog box, shown in Figure 11.18. 2. Select the name of the file that contains the picture. 3. Click the Insert button to insert the selected picture into your document.
FIGURE 11.18 You can insert pictures into your documents from a variety of sources using the Insert Picture dialog box.
PART
With today’s digital cameras, scanners, and endless CDs filled with photos and clip art, it’s pretty easy to capture just the right images for your documents. It may take a little legwork, but if it’s out there, there is a way to turn it into a digital image. Excel 2002 has built-in tools to accept images directly from scanners and digital cameras.
III Using Charts and Graphics
Inserting Scanned Graphics and Digital Photos
4002c11.qxd 7/18/01 1:13 PM Page 336
336
CHAPTER 11 • Using Drawing and Graphic Tools
Excel 2002, like the rest of the Office XP applications, supports two image acquisition standards: TWAIN and WIA. TWAIN is the established cross-platform standard for retrieving images from scanners and cameras; Excel 2002 supports TWAIN 1.7. Windows Image Acquisition (WIA) retrieves images from scanners and cameras, including still-image acquisition from DV cameras. To import images from a digital camera, scanner, or other TWAIN or WIA device, first make sure the device is connected to your computer and the software for the device is installed. Then follow these steps: 1. Set up the picture in the scanning device. 2. Choose Insert Picture From Scanner or Camera. 3. Select the device you want to use from the Device drop-down list. 4. Choose the resolution you want—Web Quality or Print Quality—depending on how you plan to use the picture. 5. Click Insert or, if you are using a scanner and want to change the image settings, choose Custom Insert. If the Insert button is unavailable because your scanner doesn’t support automatic scanning, you must choose Custom Insert. You can modify, reposition, and resize scanned images and digital photos just like any other images.
4002c12.qxd 7/18/01 1:15 PM Page 337
PA R T
IV MANAGING DATA WITH EXCEL 2002 ◗
Creating an Excel database
◗
Sorting, filtering, and subtotaling
◗
Applying conditional formatting
◗
Creating pivot tables and pivot charts
◗
Modifying and formatting pivot tables
◗
Adding calculated fields and items to pivot tables
◗
Using and creating templates
◗
Protecting worksheets and workbooks
◗
Constructing reports for non-users
◗
Using the Excel form controls
4002c12.qxd 7/18/01 1:15 PM Page 338
This page intentionally left blank
4002c12.qxd 7/18/01 1:15 PM Page 339
CHAPTER
12
USING AN EXCEL DATABASE F E ATU R I NG
Understanding Excel databases
Sorting a database
Using filters
Using subtotals to summarize data
Extracting a subset from a database
Using a data form for data entry, editing, and searching
Using Excel’s database functions
Applying conditional formatting
Creating array formulas using the Conditional Sum Wizard
4002c12.qxd 7/18/01 1:15 PM Page 340
his is the first of two chapters dedicated to using Excel’s database features. Excel’s data capabilities cover the entire range, from basic sorting and filtering to extracting data based on criteria, removing duplicate records from a database, and applying database and array formulas to worksheet ranges. And while conditional formatting is not a database-only feature, databases and data analysis spawn some of the more interesting applications of conditional formatting. Before we jump into Excel databases, we’ll unpack some of the fact and fiction about the Microsoft data tools. Excel, Access, and SQL Server are members of the same clan, but which is the “best” database? The first section of this chapter will help you answer that question based on your needs and project requirements.
t
Basic Database Concepts In its simplest form, a database is a list with a specific structure, defined by its fields: the categories of information it contains. A telephone directory, for example, is a database with fields that include last name, first name, middle initial, address, and telephone number. Database software allows you to do two distinct things: organize, or sort, the data in a specific order (for example, alphabetized by last name) and filter (or query) the data to find specific information (for example, all the entries for a specific city). If an application doesn’t allow you to sort and filter, it’s not database software. An individual listing in the phone book is a record in the telephone directory database that contains a single set of the fields: one person’s last name, first name, middle initial, address, and telephone number. In a database, each field must have a unique field name: LastName, last name, LASTNAME, and LastNameforListing are all possible field names for a field containing last names. In Excel, fields are columns, and each record is an individual row. Excel’s very rigid about this; formatting that blurs the distinctness of columns and rows, such as merged cells, is inappropriate in a database. It’s sad, but true: the plainer the structural appearance of your database, the easier it is to work with. If plain vanilla formatting bores you, leave the cells alone and go hog wild with fonts, borders, and other text features.
TIP Excel worksheets usually include more numbers than text; databases are often the exception. Two text features, AutoComplete and Pick from List, discussed in Chapter 2, “Creating Excel Worksheets,” are very useful in databases.
4002c12.qxd 7/18/01 1:15 PM Page 341
www
The Traverse Tree Sales worksheet (shown in Figure 12.1) is an Excel database. Each field is a separate column. Column labels (Month, County, Type, Quantity, Bundles, and Cost) are field names. Each individual row is a record. Columns E and F contain formulas. All seedlings are sold in bundles of 500, so the formula for bundles in E5 is =D5/500. The formula in F5 is slightly more complex. Spruce cost more than the other seedlings: =IF(RIGHT(TRIM(C5),6)=”Spruce”,E5*699,E5*599). You can download this workbook, Traverse Tree Database, from the Sybex website at www.sybex.com.
NOTE
For information on the RIGHT or TRIM functions, see Chapter 6, “Manipulating Text and Dates.”
FIGURE 12.1 An Excel database is a section of a worksheet bounded by an empty row and an empty column.
Creating a database is as simple as creating any other worksheet, but there are additional rules for worksheets that you intend to use as databases: Blank rows and blank columns Because blank rows and columns signal the end of a database, don’t leave a blank row between column headers and data records. DO leave a blank row after all records and before totals, averages, or other summary rows. Don’t leave blank columns within a database, and make sure there are no blank columns hiding between the columns of a database that you inherit.
341
PART
IV Managing Data with Excel 2002
Basic Database Concepts
4002c12.qxd 7/18/01 1:15 PM Page 342
342
CHAPTER 12 • Using an Excel Database
Field names The field names at the tops of columns must be unique within a database. Be consistent: label every column. If a label is too wide for the column contents, wrap or rotate the labels (Format Cells Alignment). With the Extend List Formats and Formulas option enabled, Excel 2002 automatically formats new database records (added at the bottom of the database) to match the other records and it copies formulas from the previous row for the new record. In the database in Figure 12.1, for example, a date entered in cell A21 will be formatted with the mmm-yy format, and the formulas in columns E and F will be extended to cells E21 and F21 after data is entered in columns A through D. The Extended Formats and Formulas option is enabled by default. If it has been turned off, follow these steps to turn it back on: 1. Choose Tools Options to open the Options dialog box. 2. On the Edit tab, enable the Extend List Formats and Formulas check box. Any existing worksheet can be used as a database, but you might have to delete or insert rows, delete columns, or edit column labels so that your worksheet meets Excel’s requirements for a database. When you think about applying the database tools, don’t limit your thinking to traditional “name and address” databases. The table of furnace burn-in test temperatures in Figure 12.2 is also a database that can be sorted and filtered to glean information about furnace performance. FIGURE 12.2 The table of furnace test temperatures is a prime candidate for Excel’s database tools.
4002c12.qxd 7/18/01 1:15 PM Page 343
Choosing a Database Application: Excel or Access There’s a myth that all “real” databases are created in Access or server databases like SQL Server. Don’t believe it. Excel 2002 is the database tool of choice for desktop projects for a number of reasons: • You can create simple databases more quickly in Excel than in Access or SQL Server. • There are more users with Excel skills than Access or SQL Server skills, so more potential users for your Excel database. • The high-end data analysis tools like pivot tables are easier to use in Excel than in Access. • Excel imports and exports data in more formats more easily than Access or SQL Server. A database created in Excel can be easily sorted and filtered by beginning Excel users. Put that same database in Access, and you’ve increased the difficulty level for both of these tasks, and made your users more reliant on your assistance. (This is only flattering at first.) Excel’s data manipulation tools and data functions are almost as powerful as those in Access, and the statistical functions in Excel are unmatched in Access. Excel and Access use the same engine to query and sort, so databases sort and filter as fast or faster in Excel than in Access.
TIP In the last three releases of Office, Microsoft has been evolving Access to make it a superior front-end form and report tool for SQL Server databases. These changes have also made Access bulkier, and therefore a slower desktop database compared to prior versions. Excel is an outstanding database tool. There are, however, four factors that will force you to use Access or another database tool rather than Excel: complexity, size, integrity, and security. We’ll discuss each of these factors so that you can better evaluate which tool is right for your needs.
Database Complexity The type of database you can create in Excel is known as a list or flat file: a single worksheet or table. More elaborate databases consist of many tables related by common fields. For example, the Traverse Tree Sales database is limited to orders placed by one type of customer. The company, Traverse Tree Sales, may also need to track retail customers, suppliers, employees, inventory, and other data, but there’s no place for
343
PART
IV Managing Data with Excel 2002
Basic Database Concepts
4002c12.qxd 7/18/01 1:15 PM Page 344
344
CHAPTER 12 • Using an Excel Database
this information in the database in Figure 12.1. Employees, suppliers, orders, and customers of all types are interrelated. When you need to create more than one table and relate the tables, you’ve generally outgrown Excel. To relate data from more than one table, you need a relational database. In a relational database, each type of information has its own table, and queries are used to pull together information from different tables to answer complex questions. Microsoft Access and Microsoft SQL Server are both relational databases.
NOTE
There are minor exceptions to the relational database rule when one table exists to serve a supporting role for another table. See the “Using Lookups” in Chapter 7 to find out how to relate two Excel tables.
Database Size Excel 2002 databases are limited to the number of rows in a worksheet. With Access 2002, the only limit to the number of records is the amount of space on your hard drive. If you’re creating a database with lots of fields—for example, to store and analyze the results of a multipage survey—you’ll notice another limitation: Excel can handle only 256 fields. While a single Access table has the same limitation, Access’ relational ability means you can separate fields into two or more tables without compromising your ability to analyze data across the tables. If your database has more than 65,535 records or 256 fields in a table, the data belongs somewhere other than Excel. Access may meet your needs, but if you hit the record limitation, you should look first at Microsoft SQL Server rather than Access.
Data Integrity Data in an Excel worksheet is always at risk. Users can accidentally delete information, overwrite or change formulas, insert or delete columns, or fail to save changes before closing the workbook. Worksheet and workbook protection has been enhanced in Excel 2002; however, you can’t make an Excel workbook foolproof. And if you don’t protect your work, the integrity of the data is often determined by the knowledge and sense of adventure of the least skilled user. With Access, data integrity is foremost. Access saves every record automatically so users don’t have to remember to save. Users work with data in forms and reports, effectively isolating the data from the user. You can create forms, restrict access to fields, or provide view-only access to critical data. If your mission-critical database will be used by inexperienced or low-level users, Access has all the tools you need to protect data integrity.
4002c12.qxd 7/18/01 1:15 PM Page 345
Data Security Excel 2002 has vastly improved worksheet protection, but for desktop database security, it’s hard to beat Access. Access meets or exceeds industry standards for data security. You can grant users or groups of users permissions to view existing data, add new data, or edit data. You can effectively deny access to sensitive data while allowing users to view other fields as appropriate. If you need to limit users’ exposure to specific data fields, look at Access 2002 before you consider Excel. Even if an analysis of your data’s complexity, size, integrity, and security results in a decision to use Access or SQL Server rather than Excel, you’ll want to know how to use Excel’s database features. Excel’s list management features are powerful tools for manipulating tables and smaller sets of records from larger databases. There are tasks that are easily done in Excel, but difficult to do in Access. You can save an Access table in the Excel format, manipulate the data, and return it to Access.
TIP
Tools like the Access Links add-in (see Chapter 16, “Using Excel 2002 with Other Databases”) bridge the gap between Excel and Access, allowing you to export directly to Access from Excel and create Access forms for use with Excel databases.
Sorting an Excel Database To sort the data in a database, first select any cell in the database, then choose Data Sort from the menu bar to have Excel select the records in the database and open the Sort dialog box, shown in Figure 12.3. FIGURE 12.3 Order the rows in a database with the Sort dialog box.
345
PART
IV Managing Data with Excel 2002
Sorting an Excel Database
4002c12.qxd 7/18/01 1:15 PM Page 346
346
CHAPTER 12 • Using an Excel Database
Excel selects all cells above, below, to the right, and to the left of the cell you selected until it encounters the edge of the worksheet or a blank column and row.
TIP If you forget to select a database cell before choosing Data Sort, an Excel message box informs you there is no list to select. Close the message box, select a cell in the database, and choose Data Sort again. If the first row of the database range contains only text and dates, Excel does not include it in the selected range; the design assumption is that a row of text entries is probably column labels rather than data. The last section of the Sort dialog box lets you correct an incorrect selection by specifying whether you have a header row.
Multilevel Sorting In a phone list, records are typically sorted by last name. This type of sort is called the primary sort. If some records may have the same entry in the primary sort field (for example, two Smiths), you can specify a secondary sort on another field, like the first name field. And if you might have two David Smiths, you can use the middle initial or another field for a tertiary sort. Note that the secondary and tertiary sorts occur only in case of an identical value at a higher level of sorting. In Excel, you can sort by as many levels as you have columns of data. Within each sort, records can be sorted in ascending order (A–Z or 1–100) or descending order (Z–A or 100–1). Descending order sorting is typically used for dates (most recent to least recent) and numbers (largest to smallest).
Sorting With the Sort Dialog Box You can sort up to three levels using the Sort dialog box. In the Sort By drop-down box, select the primary sort field name, and choose a sort order. Use the first Then By drop-down box to select the secondary sort field. For databases with many similar records (like a customer list), you might want to add a tertiary sort, using the second Then By box. When you have made all the sort selections, click OK to sort the database according to your specifications.
NOTE
If you need to sort by more than three fields, see “Sorting Using the Sort Buttons” in the next section.
4002c12.qxd 7/18/01 1:15 PM Page 347
Setting Sort Options In the Data Sort dialog box, click the Options button to open the Sort Options dialog box, shown in Figure 12.4. Use the dialog box to set the following custom sorting options: First Key Sort Order Choose Normal (the default) or one of the custom lists to sort by days of the week or months of the year rather than by date. Case Sensitive By default, Excel sorting is case insensitive. With the Case Sensitive check box enabled, lowercase or title case entries have a lower value and appear first in an ascending sort compared to uppercase versions of the same entry. For example, the entries FIRST, first, and First will appear in this order: first, First, FIRST. Orientation Choose the default Sort Top to Bottom to sort a standard database with fields in columns and records in rows. Choose Sort Left to Right to sort a table with fields in rows and records in columns. FIGURE 12.4 Change the Sort Options settings to apply case sensitivity in sorting as well as sorting direction.
NOTE
You can create your own custom lists, which will appear in the First Key Sort Order drop-down list. See “Creating Custom Lists” in Appendix A for more information.
Sort options are set for a worksheet. If, for example, you change the orientation and enable case sensitivity to sort one area of a worksheet, those sort options apply when you sort in another area of the worksheet, but not in a different worksheet in the same workbook. Sort options are saved when you save the workbook. If you have databases that use different sort options, put the databases on separate worksheets to take advantage of Excel’s sort options management. If you need to display the results of the database sorts on a single screen or printed page, see “Using the Camera” in Chapter 18. To print multiple worksheets in a single report, see “Creating Reports” in Chapter 19.
347
PART
IV Managing Data with Excel 2002
Sorting an Excel Database
4002c12.qxd 7/18/01 1:15 PM Page 348
348
CHAPTER 12 • Using an Excel Database
Sorting Using the Sort Buttons You can also sort a database (or any worksheet range bounded by blank columns and rows) using the sort buttons on the Standard toolbar. Select a single cell within the column you want to sort by. Click the Ascending Sort or Descending Sort button to sort the database. This is an easy way to sort, but it has one major drawback: Excel doesn’t allow you to verify that the selection includes the entire database. We recommend sorting the database once using the Sort dialog box to ensure that you and Excel agree on what is included in the database. After the first sort, use the toolbar buttons.
WARNING If some columns of data are not selected, the selected columns will be sorted but the unselected columns will not be, ruining the integrity of the data by mixing up the records. (This is why you never include empty columns in a database, and only select one cell.) Always check to be sure that all columns were included before sorting. Click Undo immediately if some columns were omitted in a sort. If you know how Excel sorts, you can use the sort buttons to do secondary and tertiary sorts. When Excel sorts the records in a database, it only rearranges records when necessary. If a list is already sorted by city, sorting it by state will create a list sorted first by state, and then by city within each state, because the existing city sort will only be rearranged to put the states in order. In the list on the left, the data has been sorted by city. The same database, sorted then by state, appears on the right:
In the states with more than one city listed, the cities appear in alphabetical order because the database was already sorted by city before we sorted it by state using the Ascending Sort button.
EXPERT TIP
If you need to sort by more than three fields, use the toolbar buttons. Sort the least important field first and work backward through the sort fields to the primary sort field.
4002c12.qxd 7/18/01 1:15 PM Page 349
Filtering a Database There are many times you’ll want to work with a database subset: a group of records in the database. For example, you might want to print all sales records for one salesperson or division, all the orders from one client, all the customers who haven’t made a purchase this year, or all the course offerings taught by a specific instructor. A filter is used to select records that meet specific criteria and temporarily hide all the other records.
Applying an AutoFilter To set up an AutoFilter, select any cell in the database and choose Data Filter AutoFilter. Excel reads every record in the database and creates a filter criteria list for each field. Click the drop-down arrow that appears next to a field name (see Figure 12.5) to access the field’s criteria list. FIGURE 12.5 Click the drop-down arrow next to the column heading to choose AutoFilter criteria.
The default criteria setting in each field is All, which means that the contents of the field are not being used to filter the records. Top 10 is used in numeric fields to display the top or bottom 10, 5, or any other number of records or a percentage of records. See “Using the Top 10 Filter” in the next section for more information on Top 10 filters. Custom prompts you to create a custom filter (see “Creating a Custom Filter” a little later in this chapter) for choices that don’t appear on the list.
349
PART
IV Managing Data with Excel 2002
Filtering a Database
4002c12.qxd 7/18/01 1:15 PM Page 350
350
CHAPTER 12 • Using an Excel Database
When you apply a filter, all the records not included in the subset are hidden, as shown in Figure 12.6, where the records are being filtered on Type for Frazier Fir. The number of records found and the total number of records in the database are displayed in the status bar. Each record retains its original row number; the row numbers of filtered records appear in blue. The drop-down arrow for the filtered field turns blue to show that it is being used to filter the database. FIGURE 12.6 Records displayed as filter results keep their original row numbers.
To open the AutoFilter list in a column, either click the filter arrow or select the column heading with the AutoFilter arrow and press Alt+↓. Table 12.1 lists other keyboard shortcuts you can use with Excel’s AutoFilter lists.
TABLE 12.1
A u t o F i l t e r Ke y b o a r d S h o r t c u t s
Key
Action
↓
Move down one list item.
↑
Move up one list item.
Alt+↑
Close the list.
Home
Move to the start of the list (All).
End
Move to the last item in the list.
Enter
Apply the selected item.
Filter on more than one field to select, for example, all the Scotch Pine sales in Oakland County. Set the criteria using each field’s drop-down list. Only records that meet all the criteria you select will be included in the filtered subset. To display the entire database, change the filter criteria for all filtered fields back to All or choose Data Filter Show All to reset the filters in all columns. You’ll know
4002c12.qxd 7/18/01 1:15 PM Page 351
at a glance that all records are displayed because the drop-down arrows and the row headings will all be black again.
Using the Top 10 Filter Top 10 filters display records based on their value. The name is misleading: you can filter for n records with the highest or lowest value, so it doesn’t have to be either top or 10. When you choose Top 10 as your filter criterion, the Top 10 AutoFilter dialog box shown in Figure 12.7 opens. FIGURE 12.7 Use the Top 10 filter to display the top or bottom N rows or top or bottom N percent of records.
In the first drop-down list, choose Top or Bottom, depending on whether you want to see the highest or lowest values in the field. In the second control, enter a number larger than 0. In the last control, choose Items or Percent. For example, to see the lowest 20 percent of the scores in a column of test scores, choose Bottom, enter 20, and then choose Percent. The Top 10 filter only works with values: numbers, dates, and times.
EXPERT TIP
If you use a handful of filters frequently, consider saving filtered versions of the database as views. For information on views, see Creating Views in Chapter 13, “Using Excel 2002 to Present Information.”
Creating a Custom Filter When you filter using the drop-down criteria, you are looking for records that exactly equal specific criteria. Use custom filters to search based on a comparison other than equals: • Records with fields that are NOT equal to a criterion • Records that are greater than or less than a criterion • Records that meet one condition OR another
351
PART
IV Managing Data with Excel 2002
Filtering a Database
4002c12.qxd 7/18/01 1:15 PM Page 352
352
CHAPTER 12 • Using an Excel Database
To create a custom filter, choose Custom from the drop-down criteria list to open the Custom AutoFilter dialog box, shown in Figure 12.8. FIGURE 12.8 Set multiple criteria or filter for a range of values in the Custom AutoFilter dialog box.
Click the filter operation drop-down list to choose an operator. The list includes common logical operators like equals and is greater than or equal to, as well as complex operators to filter for records that do or do not begin with, end with, or contain a string.
The values drop-down list on the right is populated with the record entries in the field from the field criteria list. To find all records that are NOT in Lake County, for example, choose Does Not Equal as the operator, and select Lake from the drop-down list. You can also enter text in the criteria controls. Notice in the dialog box that you can use the wildcard characters * and ? to broaden the search string. To find all orders for Oakland and Ottawa counties, you could do the following: • Use the wildcard character and search for equals O*. • Use the Begins with type and search for begins with O.
4002c12.qxd 7/18/01 1:15 PM Page 353
The AND and OR options are used when you want to filter by more than one criterion in a column. AND is used to establish the upper and lower ends of a range and is almost always used with numerical entries: Quantity is greater than 100 AND Quantity is less than 201 leaves only the quantities from 101 through 200. OR is used to filter by two different criteria: Lake County OR Oakland County. If you use AND when you mean OR, you’ll often get a null set: no records. (There are no records in Lake County AND Oakland County—it’s one or the other.) If you use OR when you mean AND, you’ll get all the records. (Every record is either less than 201 or greater than 100.) If you print the database while it is filtered, only the filtered records will print, so you can quickly generate reports based on any portion of the information in the Excel database. The filter criteria drop-down arrows don’t print, so there’s no need to turn the AutoFilter off until you are done working with a database. Filtering appears as if it would be useful when you need to chart part of the data in the database. You could filter the records you want to chart, then select and chart the information as you would normally. This is true. Bear in mind, however, that when the filter criteria change, the chart will change. You may decide it’s easier to chart all the data and filter it as needed. When you filter the data, the chart is filtered as well. To turn the AutoFilter off, choose Data Filter AutoFilter.
NOTE If you need to create charts for specific filtered data sets or subtotals, see the following “Creating a Subset” section and the “Creating Subtotals” section later in this chapter.
Creating a Subset There are times when you want to work with or distribute a subset of the database. For example, we have a database with 5,000 records—but only 700 of them pertain to our current project. It’s easier to work with a smaller database that includes only the 700 records we need. We can quickly create a subset of the 700 records using copy and paste: 1. Filter the active database to display the records you wish to copy. 2. Select the filtered database, including the column labels and any other titles you wish to copy.
353
PART
IV Managing Data with Excel 2002
Filtering a Database
4002c12.qxd 7/18/01 1:15 PM Page 354
354
CHAPTER 12 • Using an Excel Database
3. Click the Copy button or choose Edit Copy. 4. Select the first cell where you want the new database to appear. 5. Press Enter to paste the database. Remember that this filtered data is not linked to the original database, so changes in the original aren’t reflected in the subset. Don’t invest time updating and maintaining this as a separate database. If you need to work with a subset that remains up to date, use Microsoft Query (see Chapter 16, “Using Excel 2002 with Other Databases”) to import records from the Excel database.
Using Advanced Filters to Extract a Subset Complex filters quickly outgrow the Custom dialog box. If you need to create subsets like the following, filtered by more than two criteria in a field or with a combination of AND and OR statements, you need the Advanced Filter: • Quantities over 10,000 for Lake and Genesee counties and quantities over 15,000 for Kalkaska county • All fir trees for Oakland and Lake counties, and Concolor Fir only for all other counties You create subsets with complex criteria by extracting the subset’s records from the database using Excel’s Advanced Filter. The Advanced Filter is more complex, but incredibly powerful: you establish a criteria range that includes the column labels from your database and one or more criteria that you enter directly below the labels. Excel filters the database through the criteria range to create the subset.
NOTE
The Advanced Filter feature isn’t just for extracting data; you can filter a list in place just as you do with AutoFilter.
The criteria range is the heart of advanced filtering. If the criteria range is incorrect, the extracted data will be wrong—so take your time with this. The column headers must be precisely the same as they are in the database, so begin by copying the column headers to another location in your workbook (a separate worksheet that you name Criteria is good). Then, type the criteria you want to establish. For example, if you want to extract records where the Quantity is over 10,000, enter >10000 in the cell just below the
4002c12.qxd 7/18/01 1:15 PM Page 355
Filtering a Database
PART
IV Managing Data with Excel 2002
Quantity column label. If you have more than one criterion in a single column (for example, County = Genessee OR County = Oakland), use one cell for each criterion:
355
There are two ways to filter for two criteria in separate columns, based on whether you want to use AND or OR. Enter criteria on the same row for an AND condition, as in this filter which will only return order in Oakland county that also cost over $30,000:
4002c12.qxd 7/18/01 1:15 PM Page 356
356
CHAPTER 12 • Using an Excel Database
Or place criteria on separate rows for an OR condition, as in this filter which will return all orders from Oakland county, and orders from any county that cost more than $30,000:
In this example, criteria are established to find quantities over 20,000 in Oakland County or over 10,000 in Lake County:
4002c12.qxd 7/18/01 1:15 PM Page 357
You can’t create this last criterion with an AutoFilter. You would need to create two sets of filters, one for each county. After the criteria range is set, click anywhere in the database and open the Advanced Filter dialog box (Data Filter Advanced Filter) shown in Figure 12.9. FIGURE 12.9 Select the database, criteria range, and location for the extracted data in the Advanced Filter dialog box.
Excel will automatically select your entire database for the List Range text box. Use the Criteria Range text box to identify your criteria range, including the column labels.
TIP You’ll refer to the database, criteria range, and extract range each time you use the Advanced Filter dialog box, so you might want to name them (Insert Name Define). If you name the criteria range Criteria and the database range Database, Excel will automatically use the ranges in the Advanced Filter dialog box. Choose whether you want to filter the records in their current location (as AutoFilter does) or extract the records by copying them to another location. If you choose another location, the Copy To text box will be enabled so that you can select the first cell of the range where the filtered records should be copied. The Copy To range must be on the active worksheet. If you want to extract the range to a worksheet other than the database’s worksheet, select that worksheet before you choose Data Filter Advanced Filter to open the dialog box. As with any copy operation, just select one cell—if you select a range, it must match exactly the range required by the extracted data. Be sure that there is room in the destination area for the incoming data. Finally, click OK and Excel will filter in place or extract data as you have indicated.
357
PART
IV Managing Data with Excel 2002
Filtering a Database
4002c12.qxd 7/18/01 1:15 PM Page 358
358
CHAPTER 12 • Using an Excel Database
When you use advanced filtering to filter in place, the filtered subset will have blue row numbers, just as in the original database, even though all records are displayed. To turn the filter off, choose Data Filter Show All.
Entering Criteria for Text Fields You can use the * and ? wildcards in text fields; with skillful use of quotes, the equals symbol, and wildcards you can build text criteria that will return precisely the records you’re looking for. Table 12.2 lists commonly and not-so-commonly used text criteria.
TABLE 12.2 Criteria
C r i t e r i a f o r Te x t F i e l d s Returns
B or B*
Records that begin with the letter B
BL*
Records that begin with the letters BL
< >B*
Records that begin with any character other than B
< >*B
Records that end with any character other than B
>B
Records that begin with the letters Ba through Z
=”=B”
Records that contain only the letter B
”Blue”
Records that contain only the string Blue
*Blue*
Records that contain the string Blue and may contain other characters before or after the string
< >*Blue*
Records that do not contain the string Blue
*Spruce
Records that end with the string Spruce
B*E
Records that start with B and end with E
B?E
Records that include a three-character string that starts with B and ends with E (like bee, bre, and ble)
=
Records that are blank
< > or =”< >”
Records that do not contain blanks
Text criteria are not case sensitive unless the criteria string is contained in quotes. The criteria blue spruce will return Blue Spruce; whereas “blue spruce” will not. For some criteria, the displayed contents of the cell do not reflect the criteria you enter. For example, if you enter =”=X” to return cells with the single letter X, the criteria in the cell is =X. Select the cell and check the formula bar to see the criteria entered in the cell.
4002c12.qxd 7/18/01 1:15 PM Page 359
Entering Formula-Based Criteria Formula-based criteria filter the database based on a calculation. The calculation is itself a criterion, and must return a value of TRUE or FALSE. In Figure 12.10, we’re using formula-based criteria and filtering the database in place to show sales where the quantity was below average. FIGURE 12.10 Use formula-based criteria to filter based on a calculation about the database.
To enter a formula-based criteria, we changed the column label for cell D4 to Below Avg; you can use any title other than those already used as column labels in the database. This is important: if you forget to change the column header, the filter won’t work. In cell D5, we entered the formula =D8TODAY(). After you have set up formula-based criteria, continue with the Advanced Filter as you normally would.
Using Advanced Filter to Eliminate Duplicate Records Suppose you’ve received a database with 10,000 records, many of them duplicate records. Don’t eliminate the duplicates manually. Set up a criteria range without criteria (column headings only) and enable the Unique Records Only check box to extract a list
359
PART
IV Managing Data with Excel 2002
Filtering a Database
4002c12.qxd 7/18/01 1:15 PM Page 360
360
CHAPTER 12 • Using an Excel Database
without duplicates. This is far easier to do in Excel than in Access. Before you start creating the queries to eliminate duplicates in Access, consider exporting the table to Excel to eliminate the extra records.
NOTE
Advanced filter eliminates records that are exact duplicates—that have the same information in every field. If you need to eliminate records based on duplication in one field or a few fields, use Access.
Creating Subtotals You can create subtotals for any field in the database. A subtotal is not necessarily a sum—it can be an average, count, minimum, maximum, or other calculation based on a group of records. Before subtotaling, you must sort the database on the field you wish to subtotal. For example, if you want to subtotal each month’s orders, first sort the database by month. Follow these steps to create subtotals: 1. Sort the database by the field you wish to create subtotal for. 2. Choose Data Subtotals to open the Subtotal dialog box, shown in Figure 12.11.
FIGURE 12.11 Create summary totals and averages in the Subtotal dialog box
3. In the At Each Change In control, choose the field that you sorted on in step 1. 4. Select a type of subtotal from the Use Function drop-down list: COUNT for text and date/time fields, or any of the functions listed for numeric fields.
4002c12.qxd 7/18/01 1:15 PM Page 361
5. In the Add Subtotal To box, select each field you want to subtotal. You can subtotal more than one field at a time, but you have to use the same function: average three fields, sum three fields, etc. 6. If necessary, change the settings for Replace Current Subtotals, Page Break Between Groups, and Summary Below Data. • Enable Replace Current Subtotals if you have subtotaled earlier and want to replace the former set with new subtotals. If you want both sets of subtotals to appear (for example, sums and averages), disable this check box. • If you are going to print the worksheet with subtotals and want each subtotaled set of records to print on a separate page, insert a Page Break between Groups. • Summary Below Data places a summary (grand total, grand average) row at the bottom of the database. If you disable this check box, the summary appears at the top of the database. 7. When you have entered the information for subtotals, click the OK button to generate subtotals, as shown in Figure 12.12.
FIGURE 12.12 The Traverse Tree Sales worksheet with subtotals
361
PART
IV Managing Data with Excel 2002
Creating Subtotals
4002c12.qxd 7/18/01 1:15 PM Page 362
362
CHAPTER 12 • Using an Excel Database
When you apply subtotals, Excel automatically applies an outline and displays the outline symbols as shown in Figure 12.12. Use the outline symbols to display the level of detail you wish to see or print.
If the outline symbols do not appear, choose Tools Options and enable the Outline Symbols check box on the View page of the Options dialog box.
NOTE
To display a specific level of the outline, click the appropriate Row Level Detail symbol. Click the Show Detail and Hide Detail symbols to display or hide details for a subtotal. The outline symbols do not print, but if you’ve added a couple of layers of subtotals, you may wish to turn off the outline symbols to regain the space they occupy at the left edge of the Excel window. To remove the outline symbols but retain the subtotals, choose Data Group and Outline Clear Outline. To remove subtotals from a worksheet, open the Subtotal dialog box again (Data Subtotals) and click the Remove All button.
How Excel Creates Subtotals When you use the Subtotals dialog box, Excel does at least three things: • Iterates through the database and inserts a row above each entry that does not match the previous entry in the At Each Change In column • Builds a formula in each new row for the columns being subtotaled • Creates a text entry to the left of the subtotal that’s a concatenation of the previous entry in the At Each Change In column and the name of the summary function set in the Use Function drop-down list The formula in each inserted row uses the SUBTOTAL function. The SUBTOTAL function has two arguments: a number that represents the summary function and the range of cells to subtotal. For example, the formula =SUBTOTAL(9,G5:G10) sums the values in G5:G10. See Table 12.3 for the numbers used to represent the 11 summary functions.
4002c12.qxd 7/18/01 1:15 PM Page 363
Creating Subtotals
N u m b e r s U s e d i n S U BTOTA L S Fu n c t i o n
PART
Number
Function
IV
1
AVERAGE
2
COUNT
3
COUNTA
4
MAX
5
MIN
6
PRODUCT
7
STDEV
Managing Data with Excel 2002
TABLE 12.3
363
8
STDEVP
9
SUM
10
VAR
11
VARP
There’s little point in manually creating formulas using the SUBTOTAL function unless you want to allow your user to choose the type of subtotal they want to create by selecting the type of summary from a list of items in a form control. (See Chapter 14, “Creating Workbook for Other Users,” for information on form controls.) Instead, use the regular worksheet function (AVERAGE, COUNT, etc.) shown in the second column of Table 12.3.
Copying Subtotals When you copy a filtered database, Excel only copies the rows that are visible. If you copy subtotals, even with the detail collapsed, Excel copies (and pastes) the hidden rows. You might want to copy subtotals so you can paste them elsewhere and chart the subtotals so the chart doesn’t rely on the subtotals being displayed in the database or to include the subtotals in a report while excluding the detail rows. There’s an easy way to copy subtotals, but you could spend the better part of a workday trying to find it. 1. Begin by collapsing the subtotals so that only the data you wish to copy is visible. Select the data you wish to copy.
4002c12.qxd 7/18/01 1:15 PM Page 364
364
CHAPTER 12 • Using an Excel Database
2. Choose Edit Go To to open the Go To dialog box.
3. Click the Special button to open the Go to Special dialog box.
4. Enable the Visible Cells Only option and click OK. 5. Click the Copy button to copy the visible cells to the clipboard. 6. Move to the first cell where you want to paste the copied selection, and click Paste to paste a copy of the subtotals. Or To paste the subtotals as links, choose Edit Paste Special to open the Paste Special dialog box. Click the Paste Link button.
4002c12.qxd 7/18/01 1:15 PM Page 365
Using Data Forms Data forms provide an easy way to enter or search for data. Because data forms have a portrait orientation, they’re particularly helpful when the columns in your database exceed the width of the screen. Using the form allows you to see all the database fields at once without scrolling horizontally. To create a data form, select any cell in a database and choose Data Form. The first record in the database will be displayed in the data form (see Figure 12.13). In the form, use the vertical scroll bar or the Up and Down arrow keys to browse the records. Use the Tab key to move between fields in the form; pressing Enter moves to the next record. If you’re an experienced Excel user, data forms may not look all that interesting. For the power user, data forms become more useful when you consider other users entering data in your workbooks. Data forms offer a nearly bulletproof way to let a less-accomplished user enter data. The contents of calculated fields (see the Bundles and Cost fields in Figure 12.13) are displayed without a text box, so form users can’t accidentally overwrite formulas. The formulas still work—if you change a value that a calculated field is based on, Excel will recalculate the field. FIGURE 12.13 A data form for the Traverse Tree Sales database
If your users are overwriting formulas in critical worksheets or getting lost scrolling across the screen, show them how to open the data form, give them a five-minute orientation to working with the form (see the next section), and turn them loose.
365
PART
IV Managing Data with Excel 2002
Using Data Forms
4002c12.qxd 7/18/01 1:15 PM Page 366
366
CHAPTER 12 • Using an Excel Database
NOTE
The data form provides minimal protection for your worksheet, no data entry assistance, and no data validation. See Chapter 14, “Creating Workbooks for Other Users,” for information on protection and validation, and Chapter 15, “Creating Forms,” for help creating more useful forms for data entry.
Adding and Deleting Records in a Data Form Click the New button or scroll past the last record of the database to open a New Record form. Enter each field in the appropriate text box. When you have entered information for the last field, press Enter or click the New button again to continue entering new records. Press the ↑ (up arrow) key or click the scroll bar to close the New Record form and move back into the database. To delete the record currently displayed in the data form, click the Delete button. A dialog box will appear, warning that the record will be permanently deleted. Pay attention to the warning—clicking Undo will not bring the record back. Click the OK button to delete the record’s row from the database.
NOTE
Excel’s AutoComplete and Pick from List features don’t work with the data form, so you have to type each entry fully.
Searching for Records You can use the data form to search for individual records that meet specific criteria. This is like filtering, but you view the records one at a time. This is a good way to locate specific records that you need to delete. Here’s how to search for records with the data form: 1. Open the data form if it is not already open. 2. Click the Criteria button to open the Criteria form, which looks amazingly like the data form.
4002c12.qxd 7/18/01 1:15 PM Page 367
Using Dfunctions to Summarize a Database
367
PART
Managing Data with Excel 2002
IV
3. Enter the search criteria for one or more fields in the text boxes. Excel joins the criteria with AND, so it will only find records that meet all criteria. You can’t search for records that meet either criteria (OR) in the form. If you want to erase the search criteria, click the Criteria button again. Click the Clear button to delete the criteria, then click the Form button to return to the form. 4. Click Find Next to find the first record that meets the criteria. Use Find Next and Find Prev to view the records that meet the search criteria. 5. Click the scroll bar to view all records in the database.
www
If Excel’s data forms make you long for the robust functionality of Access forms, cheer up. Excel 2002’s Access Links add-in, available on the Microsoft website, lets you create Access forms for your Excel database. After installing the add-in (Tools Add-ins, then select Access Links from the Add-ins dialog box), choose Data MS Access Form to create a form for your Excel database.
Using Dfunctions to Summarize a Database Excel’s database functions, or Dfunctions, are similar to the Advanced Filter command: they apply a criteria range to a database. As with Advanced Filter, you set up a criteria range and use it as one of the arguments of the function. The generic syntax for the Dfunctions is: =DFUNCTIONNAME(database range, column to search, criteria range)
4002c12.qxd 7/18/01 1:15 PM Page 368
368
CHAPTER 12 • Using an Excel Database
Whether you’re using statistical functions, the subtotals feature, or the Dfunctions, you’ll use the same set of 11 summarization methods that allow you to average, count numbers, count non-blank entries, sum, retrieve the minimum or maximum value, multiply the results (product), and determine the standard deviation and variance for a sample or a population. Use subtotals when you want to group records and use one of the functions to summarize them. Use Dfunctions when you want to apply a filter to summarize records that meet a criteria without rearranging or grouping the records. All the Dfunctions except the DGET function mirror Excel’s non-database summary functions. Use DSUM, DCOUNT, DAVERAGE, DMIN, and DMAX as you would use the SUM, COUNT, AVERAGE, MIN, and MAX functions. Construct a criteria range by copying and pasting the column headings in another area of your workbook. The database and the criteria range are used in every Dfunction, so it makes sense to name both ranges. In Figure 12.14, we’ve inserted rows and added a criteria range (A4:F5, named Criteria) directly below the worksheet titles and above the database in A7:F23 (which we named TreesData). Three formulas and corresponding labels were added to the right of the database: Total Quantity: =DSUM(TreesData,”Quantity”,Criteria) Total Orders: =DCOUNT(TreesData,”Quantity”,Criteria) Average Order: =DAVERAGE(TreesData,”Quantity”,Criteria) FIGURE 12.14 The Dfunctions summarize data in a column based on values—or lack of values—in a criteria range.
4002c12.qxd 7/18/01 1:15 PM Page 369
When there are no criteria in the Criteria range, the Dfunctions sum, count, and average all the records in the database as shown in Figure 12.14. In Figure 12.15, we’ve specified criteria in the criteria range; the three formulas using the Dfunctions summarize the data based on the criteria. FIGURE 12.15 Specify criteria to conditionally sum, count, and average.
Adding Dfunctions to a worksheet creates a useful tool for ad hoc reporting. Users can enter criteria and see results instantly as the functions calculate summary results. Table 12.3 describes the Dfunctions.
TABLE 12.3
Excel’s Dfunctions
Function
Returns (Based on Criteria)
DAVERAGE
Average of entries
DCOUNT
Number of entries that contain numbers
DCOUNTA
Number of nonblank entries
DGET
A single record
DMAX
Maximum value
DMIN
Minimum value
DPRODUCT
Multiplies the values in specified field
DSTDEV
Estimate of standard deviation based on a sample of entries
DSTDEVP
Standard deviation based on all records matching criteria
DSUM
Total
DVAR
Estimate of variance based on a sample of entries
DVARP
Variance based on all records matching criteria
369
PART
IV Managing Data with Excel 2002
Using Dfunctions to Summarize a Database
4002c12.qxd 7/18/01 1:15 PM Page 370
370
CHAPTER 12 • Using an Excel Database
In the DGET function, the criteria must be a unique value (for example, a social security number in a personnel database). DGET returns the single value that matches the criteria. DGET is often used to determine if a value occurs exactly once in a column. If no record matches the criteria, DGET returns #VALUE. If exactly one record matches the criteria, DGET returns the value. If more than one record matches the criteria, DGET returns #NUM!
Applying Conditional Formatting With conditional formatting, you can apply formats to selected cells based on a condition. Conditional formatting is not a database feature, but some of the most striking examples of conditional formatting are those used in databases. You can apply font attributes, borders, or patterns to cells based on whether the condition is true or false to highlight, for example, above average performance or dates outside a specified range. Conditional formatting is one of Excel’s more amazing features. Before conditional formatting, users would manually format worksheets, selecting, for example, each cell with a value over 200 and applying a fill or border. Of course, when the values changed, the user had to unformat some cells and apply formatting to others. With conditional formatting, the formatting is automatically applied or removed when the value changes. In Figure 12.16 all of the Quantity values greater than or equal to 25,000 are bold with a border and fill. FIGURE 12.16 Use conditional formatting to highlight values that meet a condition.
4002c12.qxd 7/18/01 1:15 PM Page 371
To apply conditional formatting to a selection, follow the steps below, which are explained in detail in the next section: 1. Select the cells you want to format. 2. Choose Format Conditional Formatting from the menu bar to open the Conditional Formatting dialog box, shown in Figure 12.17.
FIGURE 12.17 Set the condition and select formatting options in the Conditional Formatting dialog box.
3. Choose Cell Value Is or Formula Is. 4. Select a conditional operator. 5. In the Condition text box enter a value, cell reference, or formula. 6. Click the Format button. Set up a format for this condition, and click OK. 7. If you have additional conditions or formats, click the Add button and repeat steps 3–6 for each condition. You can specify up to three conditions for a range of cells. 8. Click OK to close the dialog box and apply conditional formatting.
Setting the First Condition Conditional formatting conditions, like all conditions in Excel, must evaluate to TRUE or FALSE. Use the controls in the Conditional Formatting dialog box to create the condition. From the first drop-down list (see Figure 12.17), choose Cell Value Is to base the formatting on the value in the cell or Formula Is to base the formatting on a formula that returns a value of true or false. Don’t let this confuse you; it doesn’t matter whether the cell contains a typed-in value or a formula. If you want the format to be applied based on the number or text that is displayed in a cell, use Cell Value Is. To format an entire row based on the value in one cell in the row, use Formula Is. In the second drop-down list, choose one of the conditional operators: • Between (specify two values) • Not Between
371
PART
IV Managing Data with Excel 2002
Applying Conditional Formatting
4002c12.qxd 7/18/01 1:15 PM Page 372
372
CHAPTER 12 • Using an Excel Database
• Equal To • Not Equal To • Greater Than • Less Than • Greater Than or Equal To • Less Than or Equal To. In the text box, either type a constant (like 300 or Florida), select a cell in the worksheet, or enter a formula (more on this in a few pages). Click the Format button to open an abbreviated version of the Format Cells dialog box. Some of the formats are disabled (like font type and font size), so you know you can’t use them for conditional formatting. You can, however, pile on font styles, borders, shading, and fill colors to make cells jump off the page.
EXPERT TIP The 56 fill colors used for conditional formatting are the workbook’s color palette. You can change palettes so you have more choices in fewer colors (for example, replace the oranges and reds with a wider range of blues and greens). Choose Tools Options to open the Options dialog box. On the Color tab, select a color you’re willing to get rid of and click the Modify button to select a replacement color. Don’t replace colors you’ve already used in the workbook. Choose the format options you want to apply when the condition is true, and then click OK to return to the Conditional Formatting dialog box. Click OK to close the dialog box, and the formats will be applied to the appropriate cells.
Setting Additional Conditions What if you want more than one conditional format? For example, you might want to show sales increases in blue and decreases in red. In this case, you need two conditions. Create the first condition in the Conditional Formatting dialog box, then click the Add button to add another condition. You can create up to three conditional formats for a range of cells. The formats are applied in the order in which they appear in the dialog box, so sequence is everything. In Figure 12.18, we’ve added two more conditional formats for the Quantity column. The results, however, will be the same as in Figure 12.17.
4002c12.qxd 7/18/01 1:15 PM Page 373
Applying Conditional Formatting
FIGURE 12.18 These conditional formats are in the wrong order; only the first format will ever be applied.
373
PART
Managing Data with Excel 2002
IV
Condition1 formats any cell with a value greater than or equal to 25,000, then proceeds to the next cell in the range. If a value meets Condition1, Excel never tests Conditions 2 and 3. And if a value fails the first condition, it won’t meet the second or third conditions. To apply these three formats successfully, we need to reverse their order, checking first for the condition >=35,000, then for >=30,000, and finally for values >= 25,000.
Deleting Conditional Formatting To delete a conditional format, select the formatted range and choose Formats Conditional Formatting. Click the Delete button at the bottom of the Conditional Formatting dialog box to open the Delete Conditional Format dialog box shown below. Check the formats you want to delete then click OK.
Using Cell References in Conditions You can create a condition that compares the value in a cell to the value in another cell in the worksheet. For example, you might select a cell that shows an average and
4002c12.qxd 7/18/01 1:15 PM Page 374
374
CHAPTER 12 • Using an Excel Database
apply a conditional format to all the numbers that are above that average. (You can also compare the value to a named range that includes a constant rather than a cell reference.) In this example, each cell you conditionally format will refer to the cell that contains the average, so you’ll use an absolute cell reference. When you’re in the process of specifying a condition in the Conditional Formatting dialog box, simply click on the cell with the average to place the absolute reference in the condition text box. If the worksheet doesn’t include a calculated average, don’t add one simply to use it for conditional formatting. See “Using Formulas that Include Functions” at the end of the next section to find out how to calculate the average as part of conditional formatting.
EXPERT TIP You don’t have to apply conditional formatting to all the cells in a range at once. Create one or more conditional formats for a single cell and tweak them until they’re exactly what you want, then select the entire range you want to format, including the formatted cell. Choose Format Conditional Formatting, and the dialog box will open, displaying the format you created. Just click OK, and the format will be adjusted and applied to the other selected cells.
Using Formulas as Conditions Now add one more flourish, very useful in databases: you can compare a cell to a formula. For example, in Figure 12.15 shown previously, we used a county in a criteria range to summarize data using the Dfunctions. By highlighting the rows that are being summarized, users can easily see the records that underlie the summaries, as shown in Figure 12.19. It’s slick and interactive; when the user enters a county name in the criteria range, the totals change and the records for that county are highlighted. Here are the steps we followed to modify the worksheet and add formula-based conditional formatting. We’re taking a slightly longer approach than necessary for clarity. 1. Create and format a two-cell range named Criteria in cells B4:B5. 2. Select the first record in the database (A8:F8). 3. Choose Format Conditional Formatting. 4. Select the Formula Is format type. 5. Enter the formula for this row: =$B8=$B$5, as shown in Figure 12.20.
4002c12.qxd 7/18/01 1:15 PM Page 375
Applying Conditional Formatting
FIGURE 12.19 Use formulas as conditions to format all the cells in a row based on the value in one cell.
375
PART
Managing Data with Excel 2002
IV
FIGURE 12.20 Enter a formula for the selected row.
TIP
The conditional format formula must start with an = symbol and return a value of TRUE or FALSE. When you create a conditional format, Excel automatically makes all references absolute references. We edited the first cell reference (using F4) to make the reference to B8 a mixed reference: $B8. If we make this a relative reference, only the cells in column A will be formatted; if it’s absolute, we can’t copy it to the other rows in the database.
6. Click the Format button and select a format. Click OK to close the Format dialog box. 7. Click OK to apply the conditional format to the first row.
4002c12.qxd 7/18/01 1:15 PM Page 376
376
CHAPTER 12 • Using an Excel Database
8. Select the first record. 9. Click the Format Painter button and apply the format to the other records in the database. Or Click Copy. Select the remaining records. Choose Edit Paste Special to open the Paste Special dialog box. Choose Formats and click OK. Or Click Copy. Select the remaining records and click Paste. Open the Paste Options menu and select Formatting Only.
Take the time to sort out the absolute and mixed cell references in the conditional formula—the payoff is worth it. This combination of conditional formatting and Excel’s Dfunctions creates a ruggedly useful worksheet.
TIP When you’re comfortable with the cell references, select the entire database in Step 2 and continue to create the cell references in the Conditional Formatting formula as if it was going to be copied from the first row to the remainder of the database. You’ll be finished at Step 7. Conditional formatting formulas can be very simple. For example, if you have students’ midterm number grades in column D and final grades in column E, the formula =E5>D5 conditionally formats those students whose grades improved between the middle and the end of the term.
4002c12.qxd 7/18/01 1:15 PM Page 377
Using Formulas that Include Functions The criteria formula can include functions. For example, you can create a condition that calculates the average on the fly and applies the conditional format to “above average” cells by including the AVERAGE function in the condition.
Substitute MAX or MIN for average to highlight the largest or smallest value in a range. The MAX or MIN record stands out because it’s the only row without the conditional formatting applied.
EXPERT TIP If you’re creating complex criteria, create the formula in a cell using the Function Arguments dialog box. Activate the cell, then select and cut the formula from the formula bar. Open the Conditional Formatting dialog box and use Ctrl+V or Shift+Insert to paste the formula.
Top N Conditional Formatting
You can simulate the Top N AutoFilter in conditional formatting by using the functions LARGE and SMALL and the OR function to create a complex formula. The LARGE and SMALL functions have two arguments: the range of cells and what value should be returned. For example, =SMALL(D5:D20,2) returns the second smallest value from the range D5:D20. To format the three smallest values in the range D5:D20. Here’s the criteria for the Conditional Formatting dialog box: =OR($D5=LARGE($D$5:$D$20,1), $D5=LARGE($D$5:$D$20,2), $D5=LARGE($D$5:$D$20,3))
NOTE
For more information on the OR and related AND functions, see Chapter 7, “Using Logical Functions.”
377
PART
IV Managing Data with Excel 2002
Applying Conditional Formatting
4002c12.qxd 7/18/01 1:15 PM Page 378
378
CHAPTER 12 • Using an Excel Database
Conditionally Formatting Dates
Use the TODAY function to format cells or database rows that contain the current date: =A5=TODAY(), where A5 is the first cell in the range of dates. Use other date and time functions to format dates within a range or a time period. For example, =YEAR(A5)=2001 formats all the dates in 2001; =MONTH(A5)=3 formats dates in March, regardless of the year.
Creating Cheap Greenbar
Use the information function ROW and the MOD function to format every nth row of a worksheet, creating a screen that looks a lot like green bar computer paper. Green bar was created to improve readability for long printouts, and it serves the same purpose on screen. ROW returns the ROW number, and MOD returns the remainder of a division problem. This criteria returns TRUE for every third row by checking to see if the remainder is 0: =MOD(ROW(),3)=0
Finding Conditionally Formatted Cells You can tell at a glance if a cell is bold, bordered, or filled. You can’t tell if the cell has a conditional format. Fortunately, there’s an easy way to select cells with conditional formatting. Choose Edit Go To to open the Go To dialog box. Click the Special button to open the Go To Special dialog box, shown in Figure 12.21. FIGURE 12.21 Use the Go To Special dialog box to select conditionally formatted cells.
Choose the Conditional Formats option and click OK. Conditionally formatted cells will be the only cells selected. To identify all the cells with the same conditional formatting, select a cell with the conditional format before opening the Go To Special dialog box. Select the Conditional Formats option and the Same option then click OK.
4002c12.qxd 7/18/01 1:15 PM Page 379
TIP
If you paste data into a cell with conditional formatting, the formatting is wiped out. If possible, you should protect the worksheet ranges that contain conditional formatting. See Chapter 14, “Creating Workbooks for Other Users,” for information on protecting worksheet and ranges.
Using the Conditional Sum Wizard The Conditional Sum Wizard is an Excel add-in that creates array formulas: nested formulas that combine logical and statistical functions to summarize information from a database. Array formulas embed the criteria in the formula rather than storing it separately as a criteria range. Just as the Dfunctions are best used when the user can change the criteria, array formulas are best used when there are multiple criteria that don’t change. In our example, we’ll use the Conditional Sum Wizard to total the cost for each county. While you can build array formulas using the Function Arguments dialog box, if you’re building an array formula that’s based on a condition, the Conditional Sum Wizard is much quicker. The Conditional Sum Wizard is not installed by default. Choose Tools Add-ins to open the Add-ins dialog box and install the Conditional Sum Wizard. (If you installed from CD, you’ll be prompted to insert it.) To use the wizard, select any cell in the database and choose Tools Conditional Sum. In the first step of the wizard, shown in Figure 12.22, make sure the database, including the header row, is selected. FIGURE 12.22 In the first step of the Conditional Sum Wizard, verify that the database is selected.
379
PART
IV Managing Data with Excel 2002
Using the Conditional Sum Wizard
4002c12.qxd 7/18/01 1:15 PM Page 380
380
CHAPTER 12 • Using an Excel Database
In the second step of the wizard, shown in Figure 12.23, select the column to be totaled based on the condition. Build a condition by selecting a column to search, an operator (Is), and a value. Click Add Condition to add the condition to the formula. Our goal is to total sales for each county, so we created a condition for a single county name. FIGURE 12.23 Select a column, logical operator, and value to build a condition.
You can add other conditions. The conditions are treated as AND rather than OR conditions, so we can’t, for example, choose County = Genesee and County = Lake. We could, however, choose County = Genesee and Bundles > 10. There are two types of array formulas: those that return a single value, and those that return an array of values. The Conditional Sum Wizard creates a single formula, but your answer to the question in Step 3 of the wizard shown in Figure 12.24 determines whether the formula can be easily copied to create an array of values. If, for example, we choose the first option (Copy Just the Formula to a Single Cell), then Excel will embed the value string (Genesee) in the formula: {=SUM(IF($B$8:$B$23=”Genesee”,$E$8:$E$23,0))}
If we choose the second option (Copy the Formula and Conditional Values), the wizard will copy the string Genesee to a cell that we specify, and include a relative reference to the cell in the formula so we can easily copy it: {=SUM(IF($B$8:$B$23=A25,$E$8:$E$23,0))}
4002c12.qxd 7/18/01 1:15 PM Page 381
Using the Conditional Sum Wizard
FIGURE 12.24 Choose to create a formula that can be easily copied.
381
PART
Managing Data with Excel 2002
IV
If you chose to copy just the formula, in the final step of the wizard you’ll be prompted for a location for the formula. If you chose to copy the formula and values, you’ll be prompted twice: once for the value and again for the conditional formula. Figure 12.25 shows our worksheet after placing the formula and conditional value. The formula is expanded. FIGURE 12.25 The worksheet with the conditional value and formula in place.
To copy the formula, first copy or enter the other conditional values below the value used in the formula, then fill the formula to the adjacent cells.
4002c12.qxd 7/18/01 1:15 PM Page 382
382
CHAPTER 12 • Using an Excel Database
In summary, here are the steps to create an array formula using the Conditional Sum Wizard: 1. Click anywhere in the database. 2. Choose Tools Conditional Sum. 3. In the first step of the wizard, make sure the database is selected. Click Next. 4. In the Column to Sum select the column to be totaled. 5. Select a column to search, an operator (Is), and a value to build a condition. 6. Click Add Condition to add the condition to the formula. 7. Repeat steps 5 and 6 to add all the conditions you wish to apply in this formula. Click Next. 8. Choose a Copy option. Click Next. 9. Enter a location for each conditional value (if selected in step 8). Click Next. 10. Enter a location for the formula. Click Finish.
TIP
Array formulas are enclosed in braces { }. When you edit an array formula, the braces are removed. Press Ctrl+Shift+Enter when you are finished editing to denote that you are entering an array formula and Excel will replace the braces.
Validation The best source for data is the person who knows whether or not the data is correct. If you type your business address or hourly rate incorrectly, you’re likely to notice it. Courter’s Rule of Data Entry (related to Murphy’s Law) is that the person entering data is often the person farthest removed from the reality the data represents. In some institutions, data entry personnel haven’t a clue about the data that they enter, as they have no first-hand experience about the data. But even when knowledgeable people enter data, mistakes occur. When you’re in a hurry, you don’t have time to check every number. Data validation allows you to build business rules into each cell so that grossly incorrect entries produce error messages. Business rules are the policies and procedures, formal and informal, that govern how a business operates. Examples of business rules include: no refunds after 30 days; no one ever works more than 80 hours in
4002c12.qxd 7/18/01 1:15 PM Page 383
a week; and all employees must be at least 16 years of age. Here are the steps to create a validation rule: 1. Select the cells you want to validate. Hold the Ctrl key to select noncontiguous cells. 2. Choose Data Validation to open the Data Validation dialog box. 3. To set a validation rule, on the Settings page set validation criteria for entries allowed, data, and minimum and/or maximum, as shown in Figure 12.26. Clear the Ignore Blank check box to require an entry in the cell.
FIGURE 12.26 Use the Data Validation dialog box to embed business rules in your worksheet.
4. To provide information when a user clicks on the cell, enter a message and optional title on the Input Message tab, shown in Figure 12.27. Make sure the Show Input Message When Cell Is Selected check box is enabled.
NOTE
People who use the same worksheet regularly get annoyed by input messages. To provide less intrusive help, create a separate validation entry for the column or row header that only includes an input message.
383
PART
IV Managing Data with Excel 2002
Using the Conditional Sum Wizard
4002c12.qxd 7/18/01 1:15 PM Page 384
384
CHAPTER 12 • Using an Excel Database
FIGURE 12.27 Input messages appear whenever a user selects the cell.
5. If you want to display a user message when invalid data is entered, choose a Style and enter an Error Message and optional title on the Error Alert tab, shown in Figure 12.28. Choose a style—Stop, Warning, or Information—based on the severity of the error. To display the message, select the Show Error Alert After Invalid Data Is Entered check box.
FIGURE 12.28 Enter an error message to help the user correct invalid data.
6. Click OK. 7. Test the input message, validation, and error message by entering invalid data in one of the cells you selected.
4002c12.qxd 7/18/01 1:15 PM Page 385
TIP
Input Messages can be great additions to worksheets and templates you build for other people to use, even if you don’t want to validate data. On the Settings page, leave the default Any Value setting, and then enter your message on the Input Message page.
You don’t have to include an error message or error alert as part of data validation. You might prefer to let users enter data and then have Excel show you or another user all the data that isn’t valid. If a person is entering data that they are familiar with, provide an error message so they can immediately correct invalid data. If the person entering data isn’t in a position to correct it, skip the error message by disabling the Show Input Message When Cell Is Selected and Show Error Alert After Invalid Data Is Entered check boxes. Then handle the validation afterward (see the next section). To remove Data Validation or Input Messages, select the cells, open the dialog box, and click the Clear All button to clear all three pages of the dialog box.
Using the Formula Auditing Toolbar to Check Validation The Formula Auditing toolbar includes the tracing tools from the Circular Reference toolbar, a Trace Error button to check the precedents for error codes, and buttons to circle or clear circles from entries that violate validation rules. The Formula Auditing toolbar is one-stop shopping for error checking in your worksheet. Turn on the toolbar by choosing Tools Formula Auditing Show Formula Auditing Toolbar from the menu bar.
If you don’t assign an error alert to your validation rules, there’s no visible indication when a user enters invalid data. To view invalid entries, click the Circle Invalid Data button on the Formula Auditing toolbar. Each invalid entry will be circled in red. Click the Clear Validation Circles button to remove the circles.
385
PART
IV Managing Data with Excel 2002
Using the Conditional Sum Wizard
4002c12.qxd 7/18/01 1:15 PM Page 386
This page intentionally left blank
4002c13.qxd 7/18/01 2:53 AM Page 387
13
CHAPTER
USING EXCEL 2002 TO PRESENT INFORMATION F E ATU R I NG
Outlining a worksheet
Creating pivot tables
Modifying pivot tables
Adding calculated fields and items
Creating pivot charts
4002c13.qxd 7/18/01 2:53 AM Page 388
his chapter focuses on presenting information in easily understood chunks, using outlines for formula-based worksheets such as budgets, and pivot tables and pivot charts for summarization of database and list data. What do the outlining and pivot tables features have in common? They are two of the most overlooked, underused presentation features in Excel. If you’ve added subtotals to a list, you have used the outlining feature, but many users aren’t aware that outlining is a separate feature that you can use even when you aren’t subtotaling. With outlining, you can create and print a budget overview in seconds, and expose specific areas of detail within an overview, presenting only the detail that users need to see. Outlining also makes it easy to navigate large worksheets. Most Excel users have heard of pivot tables, but don’t understand how to create or use them. (Sure, there’s a wizard, but in the case of pivot tables, it’s best to pay no attention to the paperclip behind the curtain.) Pivot tables present summary information in an accessible, useful format. In this chapter, we’ll demystify pivot tables and show you how to use this amazing feature to analyze your data.
t
Grouping and Outlining If you’ve ever worked with a large worksheet that contains subtotals and totals—for example, a large budget—you’ll appreciate Excel’s Group and Outline tools. What do we mean by large? You work with 5,000-row, 12-column budgets in your volunteer life. With that 5,000-row worksheet, outlining isn’t just useful, it’s a functional requirement.
NOTE
We’ll use smaller worksheets in our examples so you can read the print in the chapter figures. Outlining is a useful feature even in 20- or 30-row worksheets that include summary rows and columns.
Applying an outline adds outline symbols that let you quickly display or hide rows and columns of detail in a worksheet. Excel 2002 has two ways to outline: the quick and dirty AutoOutline command and manual outlining. Figure 13.1 shows a worksheet with an AutoOutline. Using the outline symbols on the outline bars above and at the left edge of the worksheet, you can quickly shift from displaying all the worksheet detail, as shown in Figure 13.1, to the detail for print expenses and subtotals for other expense areas as shown in Figure 13.2.
4002c13.qxd 7/18/01 2:53 AM Page 389
Grouping and Outlining
FIGURE 13.1 Outlining adds symbol buttons at each level of the worksheet. Use the symbol buttons to hide or display levels of detail.
389
PART
Managing Data with Excel 2002
IV
FIGURE 13.2 The worksheet shown in Figure 13.1, with the monthly details and line item details hidden except for the line items under Print Expenses.
An outline can have up to eight detail levels; the higher (or outer) levels of detail summarize the lower (inner) levels. The highest outline level—and the level which shows the least amount of detail—is level 1, the next outline level is level 2, and so on. Clicking the level symbols displays an outline level and all higher levels: click the level 2 button to the left of the row headings to display levels 1 and 2 and hide the third level of detail, as shown in Figure 13.3.
4002c13.qxd 7/18/01 2:53 AM Page 390
390
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.3 The worksheet with the two lowest levels displayed and the third level hidden.
The levels are based on the hierarchy of formulas in the worksheet. For example, in Figure 13.1, the row outline includes three levels. The lowest level, level 3 in this worksheet, is composed of rows of cells that contain values or contain formulas that don’t refer to cells in the same column. The cells in the range B7:D10 are at the lowest level of detail, as are the ones in B14:D16 and B20:D22. The second lowest level, level 2 in this worksheet, refers to rows of cells with formulas that use level 3 cells as arguments. Cell B11 with the formula =SUM(B7:B10) and the other cells with similar formulas in rows 11, 17, and 23 make up level 2. The highest level, level 1, refers to the rows that contain formulas that use level 2 cells as arguments. For example, the formula in B26 is =B11+B17+B23. Row 26 is level 1.
NOTE
This also means that there is no nearby row of summary formulas that refer to the cells in row 26. If there were such a row, row 26 would be level 2, not level 1.
The columns are outlined in two levels. The lowest level, level 2, is comprised of columns B, C, and D: columns whose cells contain either values or formulas that don’t refer to cells in the same row. Column E, which contains formulas like =SUM(B16:D16), is the highest level, level 1. There are three ways to create an outline: • Add subtotals to a list (Data Subtotals), and Excel 2002 automatically outlines the list, with grand totals (if you chose to include them) at level 1 and subtotals at level 2. • Auto Outline a worksheet that includes hierarchical formulas.
4002c13.qxd 7/18/01 2:53 AM Page 391
• Create the outline manually using Excel’s Group and Outline tools (see the next section). Use this method when your worksheet has no hierarchy, when the worksheet’s layout can’t be interpreted by Excel, or when you want to omit some outline levels.
Creating and Using an Auto Outline To automatically outline a worksheet, select a range to outline or click anywhere in the worksheet data, then choose Data Group and Outline Auto Outline. Excel analyzes the formula hierarchy and adds outline symbols outside the column and row indicators. To display a hidden level of detail, click the level symbol at the top left of the outline bar: level 1 to see the least detailed view, level 2 to show more detail, and so on. To display the detail for a specific outer level (in Figure 13.2, the detail rows for print expenses), click the show detail symbol (+) for that outer level instead of using the level symbols. Use the outline symbols to display the appropriate data before printing reports for users interested in specific parts of the worksheet.
If the outline symbols don’t appear, choose Tools Options and click the View tab. Enable the Outline Symbols check box, then close the Options dialog box.
TIP
The outline symbols do not print, and you can leave the outline on while you enter data in the worksheet. If you change the worksheet’s structure by inserting or deleting rows or columns or create or modify formulas, turn the outline off (Data Group and Outline Clear Outline), then turn it on again to include the new summary rows and columns in the outline.
EXPERT TIP In Figure 13.2 the titles in rows 1 through 4 are displayed even though the underlying columns B, C, and D are hidden. The titles are in a text box created with the Drawing toolbar. The text box was then formatted: the border line has been removed, and the object positioning (a Properties setting) has been changed to Don’t Move or Size with Cells so the text box size doesn’t change when the detail columns are hidden. Right-click on any worksheet object and choose Format Object to set the object’s properties. For more information on the drawing objects, see Chapter 11, “Using Drawing and Graphics Tools.”
391
PART
IV Managing Data with Excel 2002
Grouping and Outlining
4002c13.qxd 7/18/01 2:53 AM Page 392
392
CHAPTER 13 • Using Excel 2002 to Present Information
Reviewing Worksheet Structure for Outlining You can’t outline all worksheets. As with sorting and filtering databases, there are some structural requirements for outlining worksheets. Excel can’t Auto Outline worksheets that violate these rules, so non-compliant worksheets are candidates for manual outlining. Manual outlining takes more time, so before you manually outline a worksheet, review these rules and, if necessary, make a few structural changes to your worksheet or change Excel’s Group and Outline settings, and then apply an Auto Outline.
Arranging Columns and Rows for Outlining Excel 2002 assumes that subtotal formulas are in the same row or column as the detail that they summarize. If you offset subtotals and totals, as shown in Figure 13.4, Excel cannot interpret the hierarchy and automatically outline the data. The worksheet can still be outlined, but you must outline it manually. FIGURE 13.4 If you offset totals and subtotals, Excel 2002 can’t apply an Auto Outline to the worksheet.
Summary columns need to have a specific orientation relative to detail columns. For example, if three specific columns of detail—C, D, and E—are followed by a summary column F, then the summary columns must all follow (be on the right of) the detail columns. If column B is a summary of columns C, D, and E, then all summary columns must precede the detail columns. Either summary first or detail first is
4002c13.qxd 7/18/01 2:53 AM Page 393
acceptable—a mix of the two is not. If the relationship of summary columns to detail columns is not consistent, rearrange the columns in your worksheet. Excel’s default setting is that summary columns follow detail columns; if the summary column is to the left of the detail, you must change the Group and Outline Direction setting (Data Group and Outline Settings). The same rule applies to summary rows. You can, however, have summary columns on the left and summary rows below detail rows, and vice versa. For both rows and columns, the pattern applies to all levels. If, for example, you have detail rows followed by a subtotal row, the grand total row must follow all the subtotals: level 3 detail precedes level 2 subtotals; level 2 subtotals precede level 1 totals. If level 1 totals are shown at the top of the worksheet, level 2 subtotals come next, then level 3 detail.
Changing Excel’s Group and Outline Settings If your summary rows or columns are above or to the left of the detail rows and columns, choose Data Group and Outline Settings to open the Settings dialog box shown below. Change one or both Direction settings to describe the data in your worksheet. To apply an Auto Outline with the new Direction settings, click Create. To manually create an outline using these settings, click OK.
You can format outlines using the usual formatting tools or create and apply styles. To have the Group and Outline feature apply styles automatically, enable the Automatic Styles check box in the Settings dialog box. For other formatting options, see the “Formatting an Outline” section in just a few pages.
Manually Outlining a Worksheet When you manually outline a worksheet, you determine which sections are outlined. Follow these steps to manually outline a worksheet: 1. Select the first section of rows or columns that contain the lowest level of detail data. Do not select the summary row or column for this section of detail.
393
PART
IV Managing Data with Excel 2002
Grouping and Outlining
4002c13.qxd 7/18/01 2:53 AM Page 394
394
CHAPTER 13 • Using Excel 2002 to Present Information
2. Choose Data Group and Outline Group. 3. Continue selecting detail sections and repeating steps 1 and 2 for all sections of the lowest detail level that you wish to outline. 4. Select a section of rows or columns that contain the next level of detail, the rows and columns that contain formulas that use the lowest level of detail as arguments. 5. Choose Data Group and Outline Group to group the section. 6. Repeat steps 4 and 5 until the worksheet is completely grouped. You don’t need to select entire rows and columns in steps 1 and 4. If you select a range of cells rather than a row or column, in the next step you’ll be asked to identify whether Excel should outline the row or column.
Manually outlined ranges must follow the same structural rules as worksheets that are Auto Outlined (see the previous section, “Reviewing Worksheet Structure for Outlining”). To turn off an outline, choose Data Group and Outline Clear Outline.
Ungrouping Data An Auto Outline might be almost exactly the outline you’d create manually, but include groups that you don’t want to treat as a level. For example, in our worksheet (see Figure 13.3), we want to display the web expense detail in rows 7:10, even if we’re displaying the subtotals only (level 2) for printing and video/telecomm expenses. To ungroup, select the detail rows or columns (rows 7:10). Do not select the summary row or column for the group (row 11). Choose Data Group and Outline Ungroup to remove the group. If this is the only group in its level, the outline level button will also be removed. The group’s outline symbol is removed from the outline, and the rows are no longer a level 3 group. When you display level 2, hiding level 3 rows, rows 7 through 10 are also displayed, as shown in Figure 13.5. When you display level 1, however, rows 7 through 10 are hidden along with the level 2 subtotals.
4002c13.qxd 7/18/01 2:53 AM Page 395
Grouping and Outlining
FIGURE 13.5 Rows 7 through 10 have been ungrouped. Clicking the level 2 symbol does not hide the ungrouped rows.
395
PART
Managing Data with Excel 2002
IV
Select and ungroup rows 7:10 a second time, and the groups are removed from the outline. The level 1, 2, and 3 symbols only affect rows 13 through 26, as shown in Figure 13.6. FIGURE 13.6 Rows 7 through 10 have been ungrouped twice, removing them from the outline.
Formatting an Outline You can apply automatic styles either before or after you create an outline. In the outline illustrated in this section, Excel would use styles named RowLevel_1, RowLevel_2, and ColLevel_1 to format the subtotals and totals rows and the totals column. The RowLevel and ColLevel styles apply font styles and other text formatting to the summary rows.
4002c13.qxd 7/18/01 2:53 AM Page 396
396
CHAPTER 13 • Using Excel 2002 to Present Information
NOTE
The automatic styles are applied to the summary rows and columns each time you turn on Auto Outline. If the outline includes a new level, Excel 2002 creates a new style for that level’s summary row or column.
To apply automatic styles to an outlined worksheet, select the outlined range and choose Data Group and Outline Settings to open the Settings dialog box. Enable the Automatic Styles check box, then click the Apply Styles button to apply styles to the outline.
TIP
When you apply automatic styles, any existing formatting of the same type (number, alignment, font, border, patterns, or protection) is overwritten, and you can’t undo the formatting change. Therefore, it’s a good idea to save your workbook just before applying automatic styles so you can close the workbook without saving changes if you don’t like the formatting changes that were applied.
You can modify the RowLevel_n and ColLevel_n styles to add borders, fonts, number formatting, and protection. First, apply automatic styles to the outline. Then choose Format Style to open the Style dialog box, and modify the outline styles.
NOTE
For more information on styles, see Chapter 3, “Formatting Text and Worksheets.”
Automatic styles only affect summary rows and columns. For a more consistent restyling of the entire outline, use AutoFormats. Begin by selecting the entire outline or the range of cells you wish to format. Choose Format AutoFormat to open the AutoFormat dialog box. Choose a style, set any options you wish, then click OK to apply the format. In Figure 13.7, our worksheet has been formatted by applying an AutoFormat.
NOTE
For more information on styles and AutoFormats, see “Applying AutoFormats and Styles” in Chapter 3.
4002c13.qxd 7/18/01 2:53 AM Page 397
Creating Pivot Tables and Pivot Charts
FIGURE 13.7 Apply an AutoFormat to format the summary rows and columns and the lowest level of worksheet detail.
397
PART
Managing Data with Excel 2002
IV
Creating Pivot Tables and Pivot Charts Pivot table reports, Excel 2002’s equivalent of an Access cross-tab query, is a powerful data summarization tool. A pivot table summarizes the columns of information in a database in relationship to each other. A pivot chart is the graphical representation of a pivot table. When you need to present thousands of rows of data in a meaningful fashion, you need a pivot table. The Traverse Tree Sales database we used in earlier chapters (see Figure 13.8) is a small database, but it would still take several subtotal operations to answer the following questions: • How many trees of each type were delivered each month? • How many Blue Spruce were delivered in March? In April? • What was the total expenditure by tree type for each county?
4002c13.qxd 7/18/01 2:53 AM Page 398
398
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.8 The Traverse Tree Sales database is used to create the pivot tables in this section.
www
The Traverse Tree Sales database used in this section is available on the Sybex website at www.sybex.com. You could sort the list and then add subtotals to answer any one of these questions. Then, to answer any other question, you would have to sort and subtotal again. A single pivot table, shown in Figure 13.9, will allow you to answer all of these questions, and more.
FIGURE 13.9 This pivot table report of the Traverse Tree Sales database summarizes deliveries by type and month and can be filtered by county.
Not all databases are good candidates for pivot table analysis. Databases contain many different types of information. Pivot tables focus on two broad types: • Data fields that can be summarized like the Quantity, Bundles, and Cost fields in the Traverse Tree Sales database (Figure 13.8) • Text fields that describe the data (such as the County, Month, and Type fields)
4002c13.qxd 7/18/01 2:53 AM Page 399
Numeric data fields can be summarized using SUM, AVERAGE, MAX, MIN, and the other aggregate functions including COUNT, which can also be used to summarize text fields. While pivot tables are often associated with reporting data in two dimensions (for example, sales by month and county or registrations by term and academic major), you can create one-dimensional pivot tables, too. The pivot table shown in Figure 13.10 summarizes tree sales by county. FIGURE 13.10 A one-dimensional pivot table, reporting tree sales by county
You can easily extract this same information from the database using the Subtotals feature, but the pivot table has three distinct advantages over subtotals: • Subtotals require a database sorted on the field you wish to subtotal by. We didn’t need to change the sort order of the database to create the pivot table. If another user sorts the database, it won’t affect the pivot table. • The subtotals feature inserts rows in the database, which makes it temporarily useless as a data source for mail merges, queries, and analysis. The pivot table is created separate from the subtotals. • The most exciting aspect of pivot tables is that they are dynamic. After you create a pivot table, you can rearrange the columns and rows, add and remove data fields, and add calculated fields and items to glean more information from the data. You can pivot the summaries around the detail data, providing different points of view of the details—hence the name pivot table. Subtotals are static. Excel 2002’s PivotTable feature is a simple, and simply incredible, tool. So fasten your seatbelt, open a database, and let’s go to work.
Creating a Table with the Wizard Use the PivotTable and PivotChart Wizard to create an Excel pivot table. Select any cell in a database, and choose Data PivotTable and PivotChart Report to launch the wizard.
399
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 400
400
CHAPTER 13 • Using Excel 2002 to Present Information
Step 1: Identifying the Data Source and the Type of Report In the first step of the wizard, shown in Figure 13.11, select the type of data you want to work with: • Data in an Excel database • Data from an external source like Microsoft Access • Data that you want to consolidate from several worksheets or sources • An existing PivotTable
FIGURE 13.11 In Step 1 of the PivotTable and PivotChart Wizard, identify the type of data you want to summarize.
When you base a new PivotTable in a file on an existing PivotTable instead of basing it on the database, the result is a smaller file. After you’ve chosen a data location, specify whether you want a pivot table or a pivot table with a pivot chart. In this section, we’ll create a pivot table to analyze an Excel database. In the sections that follow, we will use the PivotTable feature to analyze other types of data. And we’ll also take a look at Pivot Charts in a later section, so just accept Excel’s default settings and click Next.
Step 2: Verifying the Data Range In the second step of the wizard, verify the range of the database, as shown in Figure 13.12. If there is no range selected or if the range is incorrect, select the correct range before clicking the Next button.
4002c13.qxd 7/18/01 2:53 AM Page 401
Creating Pivot Tables and Pivot Charts
FIGURE 13.12 In Step 2, make sure the database is selected.
401
PART
Managing Data with Excel 2002
IV
Step 3: Layout and Destination In the third step (see Figure 13.13), specify the destination, layout, and options. The default destination is a new worksheet. To place the pivot table in an existing worksheet, click Existing Worksheet and identify a cell address for the upper-left corner of the pivot table. For this walkthrough, we’ll place the Pivot Table on a new worksheet. FIGURE 13.13 In Step 3 of the PivotTable and PivotChart Wizard, set options and select a destination.
If you’re an experienced PivotTable Reports user and prefer to use the structured layout tool from Excel 97, click the Layout button to display the PivotTable and Pivot Chart Wizard Layout dialog box, shown in Figure 13.14. Each of the four pivot table areas has a corresponding layout area in the Layout dialog box. At the right side of the dialog box is a group of field buttons, one for each field name in the database. Design the pivot table layout by dragging the field buttons into one of the four sections of the layout area.
4002c13.qxd 7/18/01 2:53 AM Page 402
402
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.14 Designing a table’s Layout in the Layout dialog box.
If you’re new to pivot tables, skip the Layout dialog box and see the next section, “Changing PivotTable Layout,” to learn the best way to layout pivot tables in Excel 2002. The other button in the third step of the PivotTable Report and PivotChart Wizard is the Options button. While you can set options in the Wizard, it’s easier to determine the appropriate settings for some options while you’re working in the table. See “Setting Pivot Table Options” later in this chapter for comprehensive information on options. Click Finish to create the Pivot Table.
Changing PivotTable Layout When you complete the wizard, Excel displays the pivot table, the PivotTable toolbar, and the Pivot Table Field List, as shown in Figure 13.15. A pivot table contains four areas that are clearly labeled: the Page area, the Column area, the Row area, and the Data area. You create a table by placing fields in each of the areas. Use the Field List controls or drag and drop to place fields. In the Field List, either select a field in the Field List, choose an Add To location in the drop-down list, and click the Add To button; or choose an Add To location and double-click a field to move it there.
TIP
Drag the Field List to the left or right edge of the window to dock it as a task pane.
4002c13.qxd 7/18/01 2:53 AM Page 403
Creating Pivot Tables and Pivot Charts
FIGURE 13.15 Use the Pivot Table by dragging fields from the list to the Data, Row, Column, and Page areas of the report.
403
PART
Managing Data with Excel 2002
IV
Most users simply drag an item from the Field List and drop it in one of the four areas. The mouse pointer changes to reflect the area you are pointing at. The Field List is new in Excel 2002. In Excel 2000, field buttons appeared on the pivot table toolbar. Field names were often truncated to fit the buttons, so the Field List is a major improvement.
The Row and Column Areas Place text fields you want to compare in the Row and Column areas. For example, you might want to compare sales regions by month or compare types of trees sold by county. The Row and Column areas are somewhat interchangeable; however, your pivot table is easier to use if it isn’t too wide. When the table is created, Excel will examine the fields you’ve chosen. Each unique entry becomes a row or column heading—an item—in the pivot table. If one of the fields has fewer entries than the other, it’s a better candidate for the Column area. In the Traverse Tree Sales database, there are four different months, four different counties, and five different tree types. If you are comparing tree types by county, it doesn’t make much difference whether you drag Type to the row area and County to the column area or vice versa.
The Page Area While you can filter items in the Row area and Column area, the Page area is used specifically to filter the pivot table. If you need to create separate reports for values in one or more columns—tree types by county on a monthly basis, for example—drag their field buttons (the Month field, in this case) to the Page area.
4002c13.qxd 7/18/01 2:53 AM Page 404
404
CHAPTER 13 • Using Excel 2002 to Present Information
The Data Area Information in the Data area is summarized (SUM, AVERAGE, COUNT), so numeric fields are generally placed there. If you place a text field in the Data area, you can only COUNT the number of entries for each column and row. As you drop a field button into the Data area, Excel indicates the default summary type for the data at the upper left of the PivotTable, below the Page area. SUM is the default for values; COUNT is the default for columns that contain text entries, dates, or times.
EXPERT TIP
If a column of numbers includes text entries, you’re limited to COUNT, even if most entries are numeric—a good reason not to use text values like None or NA to indicate the absence of a value. Use Replace (Edit Replace) to replace text entries like NA with blanks; simply leave the Replace With textbox blank. Blanks are also easier to filter than the text entries used to indicate blanks. To quickly locate all the blank entries in a column, turn on an AutoFilter (Data AutoFilter) and choose Blanks from the list of values on the column’s filter list.
Removing and Adding Pivot Table Fields When you’re analyzing a database, you’ll often want to summarize it in a number of ways. What you learn from one pivot table raises questions that only another pivot table can easily answer. Rather than create a new pivot table, you can change the layout of an existing pivot table by dragging a field button to another area. Excel 2002 automatically updates the pivot table. To remove a field from the pivot table, drag the field button out of the pivot table area. A large X appears beside the button. Release the mouse button to drop and delete the field. To add a field to the pivot table, drag a button from the Field List and drop it in one of the four areas of the pivot table.
TIP The PivotTable toolbar and Field List are only displayed when you select one or more cells in a pivot table. If the toolbar does not appear, right-click any toolbar and select PivotTable from the list. If neither the toolbar nor Field List appears, click in the pivot table and choose Data PivotTable and PivotChart Report to open the last step of the wizard. Click Finish to close the wizard and display the pivot table tools.
4002c13.qxd 7/18/01 2:53 AM Page 405
You can place more than one field in each area to create a richer analysis. In Figure 13.16, for example, the Row Area contains both the County and Month fields, the Column Area contains the Type field, and the Data Area includes summaries for Cost and Quantity. The County field has been filtered to display only Lake and Kalkaska counties. FIGURE 13.16 The pivot table areas can include multiple fields.
Filtering Items To filter data displayed in the pivot table, click the filter drop-down arrow on the field button for the field you wish to filter to open a list of items in the field.
Select the items you want to display then click OK to close the list and filter the pivot table.
405
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 406
406
CHAPTER 13 • Using Excel 2002 to Present Information
TIP Do you want to include this filtered table in a report you’re creating in Word? Select and copy the filtered pivot table. Open the Word document and place your insertion point where you want to place the pivot table. Click Edit Paste Special, and choose Microsoft Excel Worksheet Object from the As list in the Paste Special dialog box. Click OK to embed the pivot table in the Word document. Double-click anywhere in the pivot table to turn on the Excel toolbars so you can format the table.
Grouping Items Grouping combines items and is usually used for date fields to combine them into months or years. When we drop the Date field from the Sales Log worksheet shown in Figure 13.17 into the row area of a pivot table, there are almost as many rows as there are in the original database. FIGURE 13.17 The Sales Log contains date data, which is often grouped in a pivot table.
4002c13.qxd 7/18/01 2:53 AM Page 407
That’s fine if the goal is a day-by-day analysis of sales information. To analyze by month, quarter, or year, we need to group the data in the Date field. To group a field, right-click the field and choose Group and Show Detail Group from the shortcut menu to open the Grouping dialog box, shown in Figure 13.18. FIGURE 13.18 Use the Grouping dialog box to group data by month or year.
The By list box in the Grouping dialog box is a multi-pick list; choose Month if you want to group by month regardless of year (if details from March 2000 and March 2001 should be combined into a single row). Choose both Month and Year (see Figure 13.18) if the same month in different years should be in separate rows. The pivot table, grouped by month and year, is shown in Figure 13.19. FIGURE 13.19 The Sales Log pivot table, grouped by month and year.
407
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 408
408
CHAPTER 13 • Using Excel 2002 to Present Information
Changing the Summary and Format for Data Fields To change the type of summary, click the Field Settings button on the PivotTable toolbar or double-click the field button in the Data area—in this example, the field button for the Month field in the Traverse Trees pivot table—to open the PivotTable Field dialog box. Choose the type of summary you want to use from the list box.
The default number format in a pivot table is General. Click the Number button in the Pivot Table Field dialog box to change formats or use the Formatting toolbar and Format Cells dialog box to format the completed pivot table. Click the Options button to extend the PivotTable Field dialog box to perform custom calculations (see “Using Custom Calculations in Pivot Tables,” later in this chapter). While you’re in the PivotTable Field dialog box, you can enter a new name for the field that’s less verbose than “Sum of Quantity” or “Count of Quantity.” You cannot give the pivot table field the same name as the underlying database field (Quantity in our example), but you can name it Quantity_ as shown in the dialog box. The underscore is almost invisible on the field button.
EXPERT TIP
You can rename fields in your pivot table without opening the PivotTable Field dialog box. Click the field button, overtype the name in the formula bar, and press Enter.
4002c13.qxd 7/18/01 2:53 AM Page 409
Setting Pivot Table Options Pivot tables are constructed objects. Unlike a regular worksheet, pivot table rows and columns are created and populated based on settings. The PivotTable Options dialog box is anything but optional; you’ll save lots of time if you know what you can change in this dialog box. Right-click anywhere in the pivot table and choose Table Options, or click the PivotTable menu on the PivotTable toolbar and choose Table Options to open the PivotTable Options dialog box, shown in Figure 13.20. If you’re going to create several pivot tables in a worksheet, name them. If you don’t name a pivot table, Excel will give it the default name: PivotTable1 for the first, PivotTable2 for the second, and so on. FIGURE 13.20 Name the pivot table and set options for totals in the Options dialog box.
The default settings for Format Options and Data Options are shown in Figure 13.20. Table 13.1 describes the pivot table formatting options.
409
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 410
410
CHAPTER 13 • Using Excel 2002 to Present Information
TABLE 13.1
P i v o t Ta b l e Fo r m a t O p t i o n s
Option
Description
Name
Name for the pivot table. The default name is PivotTablen.
Grand Totals for Columns
Places a row of grand totals at the bottom of the pivot table. Enabled by default.
Grand Total for Rows
Places a column of grand totals at the right edge of the pivot table. Enabled by default.
AutoFormat Table
Applies an AutoFormat to the pivot table. Enabled by default.
Subtotal Hidden Page Items
Includes hidden items in the Page area in the subtotals.
Merge Labels
Merges the cells for row and column labels to make the table more compact and readable.
Preserve Formatting
Retains user-applied formatting when the table is updated. Enabled by default.
Repeat Item Labels on Each Printed Page
Used to set row titles that appear on each page of a printed report.
Mark Totals With *
Displays an asterisk (*) after subtotals and grand totals to denote they may include hidden items. Only available for pivot tables based on an OLAP data source.
Page Layout
Order of printed pages when the width of the pivot table exceeds one printed page.
Fields Per Column
Number of page fields that should be displayed before Excel starts another row (or column) of page fields.
For Error Values Show
Value to display for pivot table cells that show an error, including division by zero errors.
For Empty Cells Show
Value to display for pivot table cells that are blank.
Set Print Titles
Used to set column titles that appear on each page of a printed report.
Two frequently changed options are the grand totals and the empty cells options. If you don’t want grand totals in your pivot table, this is the place to turn them off. Enable the Empty Cells check box to suppress the automatic display of zeros for empty pivot table cells, or provide text (like NA) for zero values. The pivot table data options determine how the data in a table is accessed and refreshed. Table 13.2 describes the pivot table data options.
4002c13.qxd 7/18/01 2:53 AM Page 411
Creating Pivot Tables and Pivot Charts
P i v o t Ta b l e D a t a O p t i o n s
PART
Option
Description
IV
Save Data With Table Layout
Creates a pivot table cache so the table can be more quickly refreshed.
Enable Drilldown to Details
Allows drilldown into individual items in the data area. Enabled by default.
Refresh on Open
Refreshes data each time the workbook containing the database is opened.
Refresh Every X Minutes
Specifies how often data from an external database is refreshed.
Managing Data with Excel 2002
TABLE 13.2
411
Save Password
Stores the password for the external database in the workbook.
Background Query
Runs the external database query in the background so you can continue working during refresh operations.
Optimize Memory
Reduces the amount of memory used during refresh operations.
Applying a Format There are 22 different AutoFormats designed specifically for pivot tables. The first 10 AutoFormats, captioned Report 1 through Report 10, are indented formats designed to resemble traditional printed database reports, which were, in turn, based on outlines used in text documents. These PivotTable Reports look very little like pivot tables and a lot like reports you’d spend a fair amount of time creating and formatting in Access or a reporting application. The indented levels allow users to read section values down a column, and clearly demarcate the breaks between values. Table 1 through Table 10 and the Classic Pivot Table formats resemble tables more than reports. To apply an AutoFormat, select the pivot table, click the PivotTable button on the PivotTable toolbar, and choose Format Report to open the AutoFormat dialog box, shown in Figure 13.21. Select a format and click OK to apply the format. If the results aren’t what you intended, click Undo.
4002c13.qxd 7/18/01 2:53 AM Page 412
412
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.21 Select an indented report format or traditional pivot table format for your table.
Using External Data Sources In applications other than Excel, pivot tables are often called cross-tab reports. If you’ve worked with cross-tab reports in Microsoft Access or with a reporting tool like Crystal Reports, you already appreciate the ease of use of Excel’s PivotTable Report feature. Both Crystal Reports and Access are great software, but neither compares to Excel for ad hoc cross-tabular reporting, particularly if you want to quickly change the report layout. The good news is that you can use Excel to create pivot tables for external data from other data sources, including the following: • Access databases • SQL Server databases • Oracle databases • Lotus 1-2-3 worksheets • Any ODBC database that you have a driver for There are two ways to retrieve external data for a pivot table: by opening an Office Data Connection (ODC file) or using Microsoft Query.
Using an Office Data Connection To use an Office Data Connection in Excel, open the data source by choosing Data Import External Data Import Data from the menu. Select the data connection, import the data, then start the PivotTable Report Wizard.
4002c13.qxd 7/18/01 2:53 AM Page 413
NOTE
For information on creating Office Data Connections, see Chapter 16, “Using Excel 2002 with Other Databases.”
Using Microsoft Query in a PivotTable Report If you want to use an existing query or any data source other than the current workbook or an Office Data Connection, use Microsoft Query. Microsoft Query is not installed during the typical Office XP installation, so have your Office XP CD on hand when you start the PivotTable and PivotChart Wizard: 1. Select Data PivotTable and PivotChart Report and choose External Data Source in the first of the three wizard steps. 2. In the second step of the wizard, click the Get Data button.
If Microsoft Query is not installed on your system, you will be prompted to install it from the Office XP CD. 3. After Microsoft Query is installed, the Microsoft Query Choose Data Source dialog box appears. If you’re unfamiliar with Query, refer to Chapter 16 for instructions on using Microsoft Query to pull data into Excel from other applications. 4. Return to the PivotTable Wizard after retrieving the data from Microsoft Query and proceed through the rest of the wizard as you normally would.
Creating a Pivot Table from Consolidation Ranges Consolidation allows you to combine two or more Excel databases with similar types of data into a single pivot table. Figure 13.22 shows one of three worksheets that can be consolidated and summarized. The worksheets, for years 1999, 2000, and 2001, have the same structure, row labels, and column labels.
413
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 414
414
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.22 The 1999 Annual Sales worksheet and the similar worksheets for 2000 and 2001 can be summarized in a single pivot table.
www
The Undiscovered Country Annual Sales worksheet is available on the Sybex website (www.sybex.com). Before you start the PivotTable Report and PivotChart Wizard, make sure that the ranges you wish to consolidate follow the rules for databases and these conditions: • Have row labels in the first column of the range. • Have column labels in the first row of the range. • Do not include blank rows or columns. • Separate ranges from other worksheet data by blank rows and columns. Data that is to be summarized together must be labeled the same way in all the consolidation ranges. If, for example, a row of automobile expenses is labeled Car Expense in one range and Auto Expense in another, the two rows will be not be combined.
TIP
You’ll identify the database ranges in the wizard, so naming each range saves time.
In the first step of the PivotTable Report and PivotChart Wizard, choose Multiple Consolidation Ranges as the data source for the report. In the second step of the wizard, 2a, shown in Figure 13.23, indicate how page fields should be created. Choose A Single Page Field to have Excel create one page field with a page field item for each range and a summary page field item (in our example, 1999, 2000, 2001, and All page items). Choose Multiple Page Fields to designate up to four different page fields or to create a consolidated pivot table without pages.
4002c13.qxd 7/18/01 2:53 AM Page 415
Creating Pivot Tables and Pivot Charts
FIGURE 13.23 In step 2a, indicate how page fields should be created.
415
PART
Managing Data with Excel 2002
IV
In step 2b, add each of the ranges you wish to consolidate to the list as shown in Figure 13.24. In the case of named ranges, you can simply enter the name of the range in the Range text box and click the Add button. If you haven’t named a range, navigate to the range and select it manually and then click Add. Repeat for each range you wish to consolidate. FIGURE 13.24 In Step 2b, add each of the ranges you wish to consolidate to the list.
In the final step of the wizard, set layout and options if you wish, then click Finish to create the pivot table. The unformatted Annual Sales consolidated pivot table is shown in Figure 13.25. Each year’s sales can be viewed separately by changing the filter in the Page area of the pivot table.
4002c13.qxd 7/18/01 2:53 AM Page 416
416
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.25 The Annual Sales pivot table summarizes information spanning 1999 to 2001.
Consolidating Worksheets Consolidation combines data from separate data ranges or worksheets to “roll up” data from multiple data sources into a single summary. If two or more worksheets have identical row/column layouts, you can consolidate them into another worksheet using summary formulas with 3D cell references. If worksheets have either the same row/ column layout or use the same row and column labels, there is another option: the Consolidate command on the Data menu. While the Consolidate command is on the data menu, it is most frequently used with worksheets that aren’t traditional databases. For example, you might consolidate all the payroll worksheets for a year into a single payroll summary or consolidate worksheets for regional sales offices into a national worksheet. First, create a copy of one of the worksheets. In the copy, remove the data but leave the labels. Select the upper left cell of the range of labels. Choose Data Consolidate to open the Consolidate dialog box.
4002c13.qxd 7/18/01 2:53 AM Page 417
Creating Pivot Tables and Pivot Charts
417
PART
Keeping the Pivot Table Updated A pivot table is dynamically linked to the database used to create the table. If you edit values within the database, simply choose Data Refresh Data or click the Refresh Data button, and Excel will update the pivot table to reflect the database changes. However, if you add columns to the database or add rows of data at the bottom of the database, you cannot simply refresh the data. You must return to the Pivot Table and PivotChart Wizard to identify the new range of records that should be included in the table. If you don’t, the pivot table values won’t include the added data. To update the range being used in the pivot table, choose Data PivotTable and PivotTable Chart Report from the menu or open the PivotTable menu in the toolbar and choose Wizard. Move to the second step of the wizard and reselect the database. Click the Finish button to close the wizard and return to the updated pivot table. Then click the Refresh Data button to include the new columns/rows.
IV Managing Data with Excel 2002
Select a summary function from the drop-down list, then add ranges to the list of ranges to consolidate, including the labels. Use the check boxes to determine whether Excel should use labels in the left column, top row, or both to identify parallel data in the ranges. To create a refreshable consolidation table, enable the Create Link to Source Data check box. Click OK to consolidate the ranges into the new worksheet.
4002c13.qxd 7/18/01 2:53 AM Page 418
418
CHAPTER 13 • Using Excel 2002 to Present Information
Using Custom Calculations in Pivot Tables Excel 2002 supports two types of custom calculations in pivot tables: you can change the summarization function and basis for a Data field or add a calculated field or item to a pivot table.
Changing the Summarization Function and Basis In the pivot table, double-click the field button in the data area for the field to open the PivotTable Field dialog box or select the field and then click the Field Settings button on the PivotTable toolbar. Click the Options button to expand the dialog box as shown in Figure 13.26, then choose one of the custom calculation methods listed in Table 13.3 from the Show Data As drop-down list. FIGURE 13.26 Refine summarization methods in the PivotTable Field dialog box.
TABLE 13.3
Fr e q u e n t l y U s e d A d v a n c e d P i v o t Ta b l e M e t h o d s
Method
Result/Use
Difference From
Shows the data in the data area as the difference from the value you specify for the Base field and item. Used to compare sales in dollars or units to a specific sales figure.
% Of
Displays the data in the data area as a percentage of the value you specify for the Base item. Used to show a percentage comparison between sales or revenues and a target figure, where sales that hit the target would be 100 percent.
4002c13.qxd 7/18/01 2:53 AM Page 419
Creating Pivot Tables and Pivot Charts
Fr e q u e n t l y U s e d A d v a n c e d P i v o t Ta b l e M e t h o d s ( c o n t i n u e d )
PART
Method
Result/Use
IV
% Difference From
Shows the difference, as a percentage of the base data, between the data in the data area and the value you specify as the Base item. Used to show how much sales exceeded or fell short of a target; sales that hit the target would be 0 percent.
Running Total In
Displays the data in the data area as a running total. Used to show cumulative progress (by month, week, or other time period) toward a goal.
% of total
Displays each data item as a percentage of the grand total of all the data in the PivotTable. Used to show each entry’s contribution to the grand total as a percentage.
Managing Data with Excel 2002
TABLE 13.3
419
Normal
Turns off the custom calculation.
Many custom calculations use a Base field and a Base item. Base fields and Base items are like filter criteria: the Base field is a column in your database, and the Base item is a specific value from that field. Use these summaries to compare, for example, sales of all tree types to the sales of Blue Spruce. You might not need to use the advanced PivotTable Field options frequently, but you should at least be familiar with them. The options are used to create specific types of summaries and will save you lots of time and effort if you need to present, for example, running totals or percentages of the values of the rows or columns as part of a summary report. For example, Figure 13.27 shows the PivotTable Field Options settings to create a running total and the resulting pivot table. FIGURE 13.27 Use the advanced field options to present a running total of sales by month.
4002c13.qxd 7/18/01 2:53 AM Page 420
420
CHAPTER 13 • Using Excel 2002 to Present Information
You can’t insert columns in a pivot table, so if you chose to create running totals by inserting columns of formulas rather than using the pivot table options, you would need to copy and paste the pivot table values elsewhere, then work with the copy. The pasted values are not updateable, so if data in the database changed, you would need to copy the database again, then insert the formula columns. Perhaps the most impressive use of the advanced field options is to present every value in the table as a percentage of a row, column, or the grand total. The resulting table makes it easy to compare values between columns and rows at a glance. With a bit of conditional formatting, high and low values jump off the page, as shown in Figure 13.28. FIGURE 13.28 Combine the % of Total summary with conditional formatting to analyze the best and worst performers in a product line.
Calculated Fields and Items The pivot table report includes data from the database. You can perform calculations on the data by inserting a calculated field in the data area or a calculated item in the columns or rows area. For example, we could add a field to our pivot table to calculate the profit on the tree deliveries summarized in the pivot table. Calculated fields perform calculations on the totals in the pivot table, not on the values in the individual records.
4002c13.qxd 7/18/01 2:53 AM Page 421
To insert a calculated field, follow these steps: 1. Select any cell in the PivotTable. 2. Open the PivotTable menu on the PivotTable toolbar. 3. Choose Formulas Calculated Field to open the Insert Calculated Field dialog box.
4. Type a name for the field in the Name text box. 5. Enter a formula for the calculated field in the Formula text box. Use the Fields list and Insert Field button to use a field in the formula. 6. Click Add to create the field. 7. Click OK to close the dialog box and return to the pivot table. The calculated field is displayed in the pivot table, as shown in Figure 13.29, and added to the pivot table field list. To change the order of the data fields in the table, right-click the field you wish to move, then choose Order from the shortcut menu and select from the menu choices, or use drag and drop to move the field as you would any other pivot table field.
421
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 422
422
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.29 Calculated fields are added to the PivotTable Field List, so you can use them as you would other pivot table fields.
Inserting a Calculated Item Calculated item formulas are calculated for each record in the database, and then they are summarized in the pivot table. We’ll return to Traverse Trees for an example. Traverse Trees has received complaints about the White Pine seedlings sold this year. Customers indicate that seedlings are failing to survive at an unacceptable rate. Traverse Trees is considering a 25 percent rebate on White Pine to maintain customer goodwill. A calculated item based on the White Pine type shows the anticipated rebate for White Pine seedlings only within the context of the total sales for each county:
4002c13.qxd 7/18/01 2:53 AM Page 423
Use the following steps to insert a calculated item: 1. Select the field or any item in the field that you want to create a calculation for. 2. Choose PivotTable Formulas Calculated Item from the PivotTable toolbar to open the Insert Calculated Item in X dialog box.
3. Type a name for the calculated item in the Name text box. 4. Enter a formula for the calculated item in the Formula text box. Use the Fields and Items list and Insert Field and Insert Item buttons to add fields or items to the formula. 5. Click Add to add the formula. 6. Click OK to close the dialog box and return to the pivot table.
Modifying a Calculated Item for Specific Items You modify formulas for calculated items in the formula bar. Select the cell that you wish to change (hold the Ctrl key and click to select additional cells). Edit the formula on the formula bar then press Enter.
Drilling Down in a Pivot Table If you need to see a summary and detail, pivot tables are the tool of choice. Even though the cells in the Data area of a PivotTable contain summary information, you can drill down into a pivot table to view all the detail that underlies an individual
423
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 424
424
CHAPTER 13 • Using Excel 2002 to Present Information
summary figure. Double-click any nonzero value in the Data area, and Excel opens a new worksheet to display the records that were used to create that cell of the summary.
If you can’t drill down in a worksheet, the option may be disabled in the Table Options dialog box. Right-click the pivot table and choose Table Options to open the dialog box.
TIP Disable the drilldown option to prevent users from seeing the underlying data in a table. Use this option when you want to present aggregate data without showing individual data (for example, employee attendance or student test scores while keeping the details about individual employees or students confidential).
Creating Separate Pivot Tables Rather than printing different departments’ or counties’ pivot tables on different pages, you might want to create a series of pivot tables—one for each department or county. You can do this quite simply: 1. Arrange the layout so that the field that you want to use to separate the tables is in the Page area. 2. On the PivotTable toolbar, choose PivotTable Show Pages. 3. Choose the field you want to create separate pivot tables for and click OK. Excel inserts new worksheets and creates a pivot table for each item in the selected field.
Creating Pivot Charts Pivot charts help users understand data in a way that conventional database reports cannot. You can base a PivotChart on an existing pivot table or a database. If you create a PivotChart based on a database, Excel creates an associated pivot table before creating the chart, so if you need to create a table and a chart, save a step by simply creating the chart. The default PivotChart type is a two-dimensional column chart, but you can switch to any of the chart types that are suitable for summary data.
4002c13.qxd 7/18/01 2:53 AM Page 425
You can rearrange the way the data fields appear in the chart, but the pivot chart will start out with the pivot table’s row fields assigned to the category axis (the horizontal, or x-axis) in the chart. Similarly, the column fields in the table become the series (the vertical, or y-axis) fields in the chart. Pivot charts also have optional page fields. Refer to the earlier section, “Creating a Table with the Wizard,” to decide what to drag onto the Category, Series, and Data areas of the chart. Here are the steps for creating a pivot chart: 1. Click anywhere in the database, then select Data PivotTable and PivotChart Report. 2. In the first step of the wizard, select PivotChart Report (with PivotTable Report) and click Next. 3. In the second wizard step, verify the correct data range is selected and click Next. If you have already created a pivot table with the selected data range, Excel prompts you to create a chart based on the existing pivot table. If you don’t intend to delete the existing pivot table, following Excel’s suggestion is a good idea. If more than one pivot table exists for the data, Excel will prompt you to pick the one you want to use. 4. In the third step in the wizard, choose a location for the associated pivot table. You can change the layout and other options here, as described in the “Creating a Table with the Wizard” section. Click Finish. Both PivotChart and PivotTable objects can be copied and pasted into documents in other applications. If you want to use your PivotChart in a PowerPoint presentation, create it in Excel as an object rather than on a new worksheet. Then select and copy the object, switch to PowerPoint, click the slide, and paste or paste link (Edit Paste Special). If you based your chart on an existing pivot table or visited the Layout dialog box in the wizard, your chart will have columns, labels, and a legend, as shown in Figure 13.30. If you did not set the layout in the wizard, you’ll see a blank pivot chart and the PivotTable toolbar with fields from the database. Drag fields from the toolbar onto the labeled chart areas to create the chart.
425
PART
IV Managing Data with Excel 2002
Creating Pivot Tables and Pivot Charts
4002c13.qxd 7/18/01 2:53 AM Page 426
426
CHAPTER 13 • Using Excel 2002 to Present Information
FIGURE 13.30 The Pivot Chart has many of the same options as the pivot table, including filter drop-down lists.
The chart fields have many of the same properties as pivot table fields. Use the filter drop-down lists to filter chart items, select a button to rename the field or doubleclick a data button to change the summarization method. Use the Chart toolbar and menu to modify the chart elements as you would any Excel chart. To use calculated fields in a pivot chart, add the fields to the associated pivot table. The field buttons will be available on the PivotTable toolbar in the associated pivot chart.
4002c14.qxd 7/17/01 1:10 PM Page 427
14
CHAPTER
CREATING WORKBOOKS FOR OTHER USERS F E ATU R I NG
Working with existing templates
Creating templates
Inserting comments in cells
Protecting worksheets and workbooks
Allowing users to edit ranges
Creating workbooks for nonusers
Adding hyperlink buttons
Turning off workbook features
4002c14.qxd 7/17/01 1:10 PM Page 428
xcel supplies powerful assistance for maintaining spreadsheet consistency throughout your workgroup, department, or organization. We’ll start with templates, which allow you to provide a uniform look for your worksheets, and worksheet and range protection to ensure your templates and workbooks survive your users. Then we’ll focus on creating Excel worksheets that are easy to use for people who don’t know anything about Excel.
e
Using and Creating Templates Templates are workbooks that are used to create other workbooks. Templates let you quickly construct workbooks that are identical in format, giving your work a standard look. Excel includes some templates; you can create others for your personal use or for users in your workplace that are unfamiliar with Excel or your organization’s standards for workbook formatting. Templates are a big time-saver when you need to periodically create workbooks with identical or similar features: much faster than copying an existing workbook and deleting the information you don’t want to keep. With a template, you determine the look and feel of data. If, for example, you have a number of clients that send you data, you can send them a template with data validation to ensure that the data is accurately entered in the proper columns with appropriate formatting. An Excel template can include text, numbers, formatting, formulas, and all the other features you already use. When you open a template, Excel opens a copy, so the original template is not altered. This protects the original from accidental changes—yet another reason to save workbooks as templates when they are created for others to use. There are several ways to distribute a template. You can set a template as the default template so it will be used for every new workbook. You can keep a template for your own use or store the template in a shared folder on a network or intranet so others can use it.
Working with Existing Templates Excel 2002 includes predesigned templates that you can use or modify, but the Office XP installation CD isn’t the only source for existing templates. There are templates on the Microsoft Office Update website, and third-party templates you can purchase on a variety of other websites. In many organizations, the IT department creates templates. Three factors motivate IT departments to create applications in Excel: with support for VB, development in Excel is relatively easy (notice we said relatively); Excel is a stable product with a large user base; and Excel templates provide a good way to enforce business rules. So the number and variety of Excel templates is large and
4002c14.qxd 7/17/01 1:10 PM Page 429
growing, limited in most organizations only by the vision and experience of the developers and Excel power users. The New button on the Standard toolbar opens an empty Excel workbook based on the default template, bypassing the task pane. To open a template, choose File New from the menu bar to display the New Workbook task pane.
Click the General Templates link to open the Templates dialog box. Most of the templates are on the Spreadsheet Solutions tab. Select any template icon to preview the template. To open a template, double-click the icon or select it and click OK. If the template is not installed, Excel will install it. You may be prompted for the Office XP CD.
NOTE
www
You can’t preview a template until you have installed it.
In the task pane, click Templates on My Web Sites to locate templates stored on a local intranet or an Internet site. To locate more templates, click Templates on Microsoft.com. Predictably, most templates on Microsoft.com are Word templates, but there’s an adequate selection of Excel templates in the Finance and Accounting and Business Forms categories. To preview a template, click the template link and agree to the license agreement. To download the template, click the Edit in Excel link on the preview page and save the template.
NOTE
Unlike the templates in Excel 2000, most Excel 2002 templates don’t have a separate Customize This Template worksheet. Instead, noncustomizable ranges are protected, and customization is done directly in the worksheet.
Entering Data The Sales Invoice template, shown in Figure 14.1, is a typical Excel template. The cells with standard text and formulas are protected; you can’t select, for example, the Total cells in column M.
429
PART
IV Managing Data with Excel 2002
Using and Creating Templates
4002c14.qxd 7/17/01 1:10 PM Page 430
430
CHAPTER 14 • Creating Workbooks for Other Users
FIGURE 14.1 The Invoice template is a typical Excel template.
Select a cell with an italicized placeholder—Insert Company Information Here—to view a screen tip. Some templates include comments; commented cells have a red triangular comment indicator. To view a comment, move the mouse over the cell.
Saving the Template If you’re going to use the template again, you should save the template again with a new name so you don’t have to enter the company information the next time you open it. Choose File Save As and choose Template from the Files of Type drop-down list. Change the file name—for example, Company Sales Invoice instead of Sales Invoice1—to indicate that the template has been modified by adding your company information.
Creating Templates for Personal Use Any workbook can be turned into a template, and your frequently created workbooks should be. Why create (or pay an employee to create) a new workbook that includes formatting, formulas, named ranges, charts, and other predictable elements each time
4002c14.qxd 7/17/01 1:10 PM Page 431
you do the same basic task? In our office, this theory has resulted in Training Proposal and Project Bid workbooks. Examine the Excel files on your drives to see how many of them are different variations on the same few workbooks. For example, you might track departmental payroll hours in Excel, with each week’s hours on a separate worksheet and a consolidating worksheet to track monthly totals for analysis: six sheets in all. Rather than constructing a new workbook each month, create a monthly payroll template; a weekly worksheet from our payroll template is shown in Figure 14.2. At the beginning of each month we create a new workbook from the template instead of copying and gutting an existing payroll workbook or, worse yet, starting from scratch. FIGURE 14.2 The payroll template serves as the basis of each month’s payroll reporting worksheet.
www
You can download the Train2K.com payroll template used in this chapter from the Sybex website at www.sybex.com. A template differs from a regular workbook in four specific ways: • The file is saved as a template (.xlt file extension) rather than a regular workbook (.xls) so that Excel opens a copy when you open the template. • The template is saved in the Office Templates folder or a shared folder for others to use. • The workbook contains only the text, formulas, and formatting that remain the same each month. • The template includes visual formatting clues and comments to assist users. You can skip this step if you’re the only user and never take vacation time.
431
PART
IV Managing Data with Excel 2002
Using and Creating Templates
4002c14.qxd 7/17/01 1:10 PM Page 432
432
CHAPTER 14 • Creating Workbooks for Other Users
You can create a template from scratch or base it on an existing workbook. If you’re using an existing workbook, first make sure that all the formulas work and that numbers and text are formatted appropriately. Remove the text and numbers that will be entered each time the template is used. Don’t remove formulas—although the results of the formula change, the formulas themselves remain the same. If you’re creating a template from scratch, you still need to enter (and then remove) values to test the template’s formulas before saving the template. When saving a template, be sure to follow these steps: 1. Click the Save button or choose File Save As. 2. In the Save as Type box, choose Template from the drop-down list. The Save In box will change to the default Templates folder. 3. Enter a name for the template in the File Name text box. 4. Click the Save button.
Creating Edit-Free Formulas If you stopped in the middle of the last paragraph and thought “Wait a minute—I have to change my formulas all the time!,” this paragraph is for you. Some of the work done in Excel is ad hoc data conversion. For example, you receive data and need to use text formulas or the Text to Columns feature to convert it into useable data. If the data format differs, then you’ll need different formulas, for if you can’t predict the form of the data you receive, you can’t easily create a worksheet to handle it. But we often find users editing formulas because the formula they’re using (and modifying with each use) is too wimpy to do the job. And because the formulas require user intervention, the workbooks aren’t worth saving as templates. For example, one of our users routinely edited formulas that calculated the average daily sales for each salesperson. The formulas divided the sales for the month by the number of weekdays in the month, which the user faithfully calculated by counting the Mondays, Tuesdays, Wednesdays, Thursdays, and Fridays for the month on his wall calendar. Modifying the formula to use Excel’s NETWORKDAYS function got him out of the calendar counting business and made the workbook functions powerful enough to handle the task when saved as a template. If a workbook contains predictable data, formulas shouldn’t change unless one or more business rules have changed. The next time you open a workbook or copy of a workbook and edit formulas, determine why you’re changing the formulas, then replace them with formulas that won’t require editing in the future.
4002c14.qxd 7/17/01 1:10 PM Page 433
Creating Templates for Other Users Presumably you know where you should and shouldn’t enter data in a workbook you use regularly. You’re familiar with the data to be entered. If you create a template for your own use, you don’t need to build in a lot of assistance. When you create a template for other users, you can’t assume that they know how to use it. Even if the folks using the template initially are experienced users, those who succeed them may know little or nothing about your organization, Excel, or your template. If you don’t invest the time required to create a solid template, you’ll get to be the trainer and help desk for your template when different employees use it. Build in the following features to make your template easier to use: Borders and Fill Color Lets users know where they should—and shouldn’t—enter text or other information. In the templates included with Excel, cells with a back color like pale yellow, pink, or green contain formulas; users enter data in cells with no fill. In our template, formula cells have a green fill and non-editable labels a pale yellow fill. See Chapter 3 for help with borders and fills. Comments Provides assistance where users might have questions about data entry. The Excel 2002 templates include few comments; err on the side of too many, rather than too few, comments. Our template includes comments in cells B4 and A7, nonvalidated cells where users enter a unique type of data for the first time. Choose Insert Comment from the shortcut menu to insert a comment in the active cell. Data Validation Provides input messages and error messages to guide data entry. Our template includes validation for the cells where users enter the hours worked each day. See the “Validation” section in Chapter 12. Remove Unused Areas Make sure the user of the template is focused by removing extra worksheets and ranges. In our template, we deleted extra worksheets, hid the worksheet used in lookups, and hid extra rows and columns. Protection Protect cells that shouldn’t be altered (see “Protecting Workbooks, Worksheets, and Ranges” later in this chapter). In the Excel templates and our template, formula cells are protected. When you’re finished creating the template, choose File Save As, and save the workbook as a Template. You can create folders within the Templates folder to hold your personal templates. Other than the General tab, tabs in the Templates dialog box represent subfolders in the Templates folder. The template will be included on the General tab (or the tab representing a folder you created) of the Templates dialog box. Save the template in a shared folder to make it accessible for other users.
433
PART
IV Managing Data with Excel 2002
Using and Creating Templates
4002c14.qxd 7/17/01 1:10 PM Page 434
434
CHAPTER 14 • Creating Workbooks for Other Users
WARNING
Don’t save templates in Exchange Server folders (Outlook’s Public Folders). When a user opens a template from a public folder, they open the original template, not a copy.
Editing a Template To modify a template, open the template from the Templates folder with File Open rather than File New. When you are finished editing, save and close the template. As you gain experience with Excel, you can add other features to templates, like command buttons and custom toolbars. Use Excel’s Help feature to find more information on template design and modification. Refer to Chapter 21, “Automating Excel 2002 with Macros,” for information on recording simple macros which you can attach to buttons or menu options.
EXPERT TIP The File menu includes a list of recently opened files. After you create a template, the list will include the template you just created. If you or another user open the template from the File menu, the template—not a copy of the template—will open. To clear the recently used file list from the menu, first save and close the template; then choose Tools Options to open the Options dialog box. On the General page, clear the Recently Used Files check box, then click OK to close the Options dialog box and clear the list. Reopen the Options dialog box and enable the check box, and Excel will resume displaying recently used files with the next files you save. Excel’s lookup functions can be used in any workbook, but they are particularly useful in templates. For information on lookups, see Chapter 7, “Using Logical Functions.”
Hiding Worksheets Your workbook may contain supporting data that you don’t want your users to edit or view. For example, you may have criteria ranges to support an advanced filter or data tables for lookup or validation. Place supporting data on a separate worksheet and hide the worksheet. Select the sheet(s) you wish to hide, and choose Format Sheet Hide to hide the worksheet.
4002c14.qxd 7/17/01 1:10 PM Page 435
Protecting Workbooks, Worksheets, and Ranges
PART
IV Managing Data with Excel 2002
To unhide hidden sheets in a workbook, choose Format Sheet Unhide to open the Unhide dialog box, shown below. Select the sheet you wish to display, and click OK to display the worksheet.
435
Seems too easy to unhide worksheets, doesn’t it? Keep reading, and we’ll show you how to protect hidden worksheets so they can’t be so easily unhidden.
Protecting Workbooks, Worksheets, and Ranges If it’s this easy to display the hidden sheets in a template, you’ll only be hiding the sheets from novices—better than nothing, but not enough. You also need to protect the workbook so users can’t unhide hidden sheets. You can protect workbooks, worksheets, and ranges in Excel 2002.
Protecting Workbooks To protect a workbook, choose Tools Protection Protect Workbook from the menu.
To protect the structure of a workbook so that worksheets can’t be hidden, unhidden, renamed, moved, inserted, or deleted, enable the Structure check box. To lock in the size and position of the workbook’s windows when the workbook is opened,
4002c14.qxd 7/17/01 1:10 PM Page 436
436
CHAPTER 14 • Creating Workbooks for Other Users
enable the Windows check box. To prevent other users from turning off the protection, type a password then click OK. Workbook passwords are case sensitive. You’ll be prompted to confirm the password by typing it again.
TIP
Protection without a password is no protection. Many users spend their first few minutes with any new program simply opening menus and choosing commands. This is scary, but true. Without a password, Tools Protection Unprotect Workbook turns the protection off.
www
If you lose your password, you won’t be able to turn off workbook protection. There are password recovery utilities for all the Office products, such as those developed by Elcomsoft (www.elcomsoft.com). Check with your employer before downloading or purchasing password recovery utilities; some organizations discipline or fire employees who have or use this type of program.
Protecting Worksheets and Ranges Each cell in a workbook has a Locked property, which is enabled by default. Although the cell is locked, the Locked property is only enforced when you protect the cell’s worksheet. Before protecting a worksheet, you must unlock all cells where you’ll want users to enter data. In Excel 2002, there are two ways to do this: • Unlock the range by turning off the cells’ Locked property. This unlocks the range for all users, so anyone who can edit any sheet in the workbook can enter, edit, or delete data in these cells. • Use the new Allow Users to Edit Ranges feature to provide specific users with permission to edit the cells. With either option, the remaining worksheet cells are locked only when you protect the worksheet.
4002c14.qxd 7/17/01 1:10 PM Page 437
Unlocking Ranges and Hiding Formulas To unlock cells, select the cells then choose Format Cells or right-click and choose Format Cells from the shortcut menu to open the Format Cells dialog box. On the Protection tab shown in Figure 14.3, clear the Locked check box. FIGURE 14.3 Disable the Locked property for usereditable ranges before protecting the worksheet.
If a user selects a locked cell in a protected worksheet, they can view the cell’s formula in the formula bar even though they can’t change the cell. If the formula includes information that you don’t want your users to see (for example, the markup charged to a client), enable the Hidden check box on the Protection tab. When you protect the worksheet, the formulas in hidden cells do not appear in the formula bar.
Allowing Users to Edit Ranges In prior versions of Excel, you could set two levels of password-based permission: read only and read/write permission. If a user could edit some cells, they could edit all cells. The new Edit Ranges feature provides two new types of security: user-based and range-based. Permission can be granted based on either passwords or network authentication, and different permissions can be granted for specific ranges of cells. For example, in a customer table, you might let one user edit customer address information and another user edit only customer discount data.
437
PART
IV Managing Data with Excel 2002
Protecting Workbooks, Worksheets, and Ranges
4002c14.qxd 7/17/01 1:10 PM Page 438
438
CHAPTER 14 • Creating Workbooks for Other Users
NOTE
The Edit Ranges feature is operating system–dependent and only works with Windows 2000.
To grant permission to edit ranges before protecting a worksheet, choose Tools Protection Allow Users to Edit Ranges to open the Allow Users to Edit Ranges dialog box, shown in Figure 14.4. FIGURE 14.4 Use the Allow Users to Edit Ranges dialog box to give users permissions for specific ranges.
Follow these steps to set permissions in the worksheet: 1. Click the New button to open the New Range dialog box.
2. In the New Range dialog box, enter a name for the range. 3. Specify the range in the Refers to Cells text box. Hold the Ctrl key to select noncontiguous ranges. 4. If users who aren’t on your network (including remote users) will be using the workbook, enter a password for this range. Users will be required to enter the password to edit cells.
4002c14.qxd 7/17/01 1:10 PM Page 439
Protecting Workbooks, Worksheets, and Ranges
PART
IV Managing Data with Excel 2002
5. If all users with edit permission will be logged onto your network, click the Permissions button to open the Permissions for Range N dialog box, shown in Figure 14.5.
439
FIGURE 14.5 Set permissions for network users in the Permissions dialog box.
6. Click the Add button to open the Select Users, Computers, or Groups dialog box, shown in Figure 14.6. Select users or groups from your network. When you have finished selecting users and groups, click OK to return to the Permissions dialog box. 7. For each user or group, confirm or deny editing rights without a password. Click OK to return to the Allow Users to Edit Ranges dialog box. 8. Click New to specify permissions for another range.
TIP To document the protection information, enable the Paste Permissions Information into a New Workbook check box in the Allow Users to Edit Ranges dialog box before you protect the worksheet. Excel opens a new workbook and pastes the range and user permission information.
4002c14.qxd 7/17/01 1:10 PM Page 440
440
CHAPTER 14 • Creating Workbooks for Other Users
FIGURE 14.6 Select users and groups you wish to set permissions for.
9. When you are finished setting password or network-authenticated permissions for users, click the Protect Sheet button to open the Protect Sheet dialog box, shown in Figure 14.7.
FIGURE 14.7 Specify the sheet features you wish to protect.
4002c14.qxd 7/17/01 1:10 PM Page 441
Enter a password (which you’ll need to know if you ever want to change permissions for the worksheet) and verify the worksheet actions that users are allowed to take in this worksheet after it is protected: Select Locked Cells (on by default) Select Unlocked Cells (on by default) Format Cells Format Columns Format Rows Insert Columns Insert Rows Insert Hyperlinks Delete Columns Delete Rows Sort Use AutoFilter Use PivotTable Reports Edit Objects Edit Scenarios Unless you allow users more permission than the default settings, they will only be allowed to select cells and enter or edit data using an input device or copy and paste. When you’re finished setting allowable actions, click OK to protect the worksheet.
Unprotecting a Worksheet To unprotect a worksheet, choose Tools Protection Unprotect Worksheet. You’ll be prompted for the password you entered in the Protect Sheet dialog box. After unprotecting the sheet you can modify or delete the settings for the sheet and ranges.
NOTE
Data validation, including input messages and error alerts, are useful additions in many templates and workbooks created for other users. See Chapter 12, “Building an Excel Database,” for information on validation.
441
PART
IV Managing Data with Excel 2002
Protecting Workbooks, Worksheets, and Ranges
4002c14.qxd 7/17/01 1:10 PM Page 442
442
CHAPTER 14 • Creating Workbooks for Other Users
Creating Worksheets for Nonusers Templates are designed for people who use Excel. They may be Excel novices or Excel power users, but they know how to open workbooks, enter data, and save the results of their work. They’re comfortable using basic Excel commands to accomplish a task. Some workbooks are created for a different audience: people who don’t work in Excel at all. This doesn’t mean they’re not computer users. Perhaps they use Outlook or are only comfortable using Word or a browser. Of course, everyone should know how to use Excel. It’s powerful software in any organization. If we were in charge of the world, all computer users would be Excel users. We’d probably take care of a few other things first like poverty, the environment, and racism, but mandatory Excel training would be right up there in the top 40. But we’re not in charge. The world we work in includes users who need information and who are not Excel users. The challenge is simplicity itself: create workbooks that are easy to understand and simple for people to use even if they’ve never worked in Excel. It’s easy to tell when we failed to meet the challenge—users are confused and frustrated, and we spend too much time one-on-one supporting the workbooks we’ve created. When we meet the challenge, users can access the information they need with minimal support. There’s one question we need to answer before we begin: If users can’t use Excel, what software can they use? If all our users were Microsoft Word power users, it would make sense to create workbooks that function much like Word. But it’s even easier to make Excel look and function like the most commonly used software: a browser. For workbooks designed for nonusers, our paradigm is to make every workbook function more like a page in a browser and less like an Excel workbook. Fortunately, this isn’t difficult. Some of the work is deconstruction, turning off or hiding features that define Excel and make it intimidating for nonusers: • Delete extra sheets and hide unused columns, as in the template • Hide row and column headings • Hide toolbars • Hide command bars When we add elements, we’ll add the kind of features users expect in a browser: • Hyperlinks for navigation • Buttons for user choices • Comments that provide help • Text boxes with additional information • Commands on the main menu rather than toolbars or shortcut menus
4002c14.qxd 7/17/01 1:10 PM Page 443
Finally, we’ll fire up a macro to push Excel into full screen mode just like a browser window. When we’re finished, our workbooks will look a lot like web pages viewed in Internet Explorer and very little like Excel workbooks, therefore less intimidating for browser users. Because we’ll rely on web functionality, the finished workbook can be saved as a web page for intranet use without compromise.
NOTE
For information on recording macros, see Chapter 21, “Automating Excel 2002 with Macros.” For information on command buttons and other form controls, see Chapter 15, “Creating Forms.”
Taking the Spreadsheet Out of Excel We’ll use three workbooks that appear elsewhere in this book as sample worksheets: the Payroll template used earlier in this chapter, the Employee Directory from Chapter 7, and a version of the Traverse Tree Sales database from Chapter 12. The Payroll template, shown in Figure 14.2 is already well on its way to a browserlike format. The workbook has no extra worksheets. Each of the five weekly payroll worksheets includes these formatting features: • Gridlines are only displayed in the areas where users enter data. • Unused rows and columns have been hidden. • Fills delineate areas where users should not enter data. • Comments provide useful information when the user points to a commented cell. But the worksheet in Figure 14.8 is even less like Excel and more like a web page. An Excel user will recognize it as an Excel document, but to a casual observer, it looks and operates like a web page. This worksheet is almost identical to the other four payroll worksheets in the workbook. They differ in only three respects: Sheet Names The sheet for the first week’s payroll is named Week1, the second Week2, and so on. Named Ranges Cell B6 is named Week1End in the Week1 sheet, Week2End in the Week2 sheet, and so on. Comments The comment for cell B6 refers to the week, so the comment is slightly different for each worksheet.
443
PART
IV Managing Data with Excel 2002
Creating Worksheets for Nonusers
4002c14.qxd 7/17/01 1:10 PM Page 444
444
CHAPTER 14 • Creating Workbooks for Other Users
FIGURE 14.8 This version of the Payroll workbook looks more like a web page because Excel features are hidden.
In the sections that follow, we’ll walk through the following changes in the worksheet shown in Figure 14.8: • Rows are inserted below the title to make room for buttons. • AutoShape buttons are added for navigation. • Row and column headings are hidden. • Both scroll bars, the sheet tabs, and the formula bar are hidden. • All toolbars are turned off. • Gridlines are turned off. • The worksheet is displayed in Full Screen view, which hides the application title bar.
4002c14.qxd 7/17/01 1:10 PM Page 445
Turning Off Excel Features Excel features like the scroll bars, formula bar, and sheet tabs are displayed or hidden using settings in the Options dialog box. The options apply only to the current sheet or selected sheets, so you may want to begin by selecting all the worksheets in the workbook. Choose Tools Options to open the Options dialog box. In the View tab, shown in Figure 14.9, clear the following options: • Startup Task Pane • Formula Bar • Page Breaks • Gridlines • Row & Column Headers • Horizontal Scroll Bars • Vertical Scroll Bars
FIGURE 14.9 Turn off screen features on the View tab of the Options dialog box.
We’ll return to this dialog box later to turn off the sheet tabs.
445
PART
IV Managing Data with Excel 2002
Creating Worksheets for Nonusers
4002c14.qxd 7/17/01 1:10 PM Page 446
446
CHAPTER 14 • Creating Workbooks for Other Users
Creating Navigation Buttons with Hyperlinks The navigation buttons at the top of each worksheet are designed to look like the navigation buttons used on web pages.
Each button is a hyperlink to the named range in B6 on the corresponding worksheet. We created the buttons with AutoShapes, but you can use pictures or create custom text buttons with WordArt if you prefer.
NOTE
For information on AutoShapes, WordArt, or pictures, see Chapter 11, “Using Drawing and Graphics Tools.”
Create the buttons, one for each cell or range a user will need to navigate to, then follow these steps to create hyperlinks: 1. Select and name each range that a user will click a button to navigate to. You can skip this step for any worksheet where the user navigates to cell A1. After all the ranges are named, you can turn off the Sheet Tabs in the Options dialog box (Tools Options). 2. Right-click on the first button and choose Hyperlink from the shortcut menu to open the Insert Hyperlink dialog box, shown in Figure 14.10.
FIGURE 14.10 Use the Insert Hyperlink dialog box to turn an AutoShape or picture into a hyperlink.
4002c14.qxd 7/17/01 1:10 PM Page 447
Creating Worksheets for Nonusers
3. Choose Place in This Document in the Link To bar. 4. Select the worksheet or named range from the list of places in the document.
PART
IV Managing Data with Excel 2002
5. Click the ScreenTip button to open the Set Hyperlink ScreenTip dialog box.
447
6. Enter text to use as a ScreenTip. This is not an optional step. If you don’t enter text for a ScreenTip, Excel displays the default hyperlink text: the full path to the workbook, the sheet name, and the range name. 7. Click OK to close the dialog box. Repeat steps 2 through 7 for each button on the worksheet. After the buttons have been created, select all the buttons, then right-click and choose Format AutoShape (or whatever object type you’re using). On the Properties tab, shown in Figure 14.11, disable the Print Object check box so the buttons won’t print when a user prints the worksheet. If you’re still rearranging worksheet elements, you might also choose the Move but Don’t Size with Cells option or the Don’t Move or Size with Cells option to make sure that your buttons don’t change size or location as you adjust rows and columns. FIGURE 14.11 Change the buttons’ properties so they don’t print or move.
4002c14.qxd 7/17/01 1:10 PM Page 448
448
CHAPTER 14 • Creating Workbooks for Other Users
After you’ve created one set of buttons, you can copy and paste them in the other worksheets.
Hiding the Title Bar The last change is completely cosmetic: hiding the application title bar. To do this, you need a macro that runs when the workbook opens. In the Visual Basic Explorer, choose This Workbook and create this simple macro that runs on the workbook’s On Open event: Private Sub Workbook_Open() ‘ ‘ Changes workbook view to full screen’ Application.DisplayFullScreen = True End Sub
NOTE
In the Visual Basic IDE, double-click This Workbook in the Explorer. Choose On Open from the drop-down list of events in the code window.
If the user’s security is set at Medium or High (which is recommended), they’ll be prompted to enable macros when the workbook opens unless you add a digital signature. If you don’t have a digital signature, don’t include the macro as part of the workbook.
NOTE If you’re not familiar with Visual Basic, see Chapter 21, “Automating Excel 2002 with Macros” for information on writing code in Excel. For information on hiding and displaying toolbars and using digital signatures, see Chapter 24, “Creating an Excel Application.”
4002c15.qxd 7/18/01 2:55 AM Page 449
15
CHAPTER
CREATING FORMS IN EXCEL 2002 F E ATU R I NG
Types of Excel forms
Creating printable forms
Understanding ActiveX and form controls
Adding form controls to worksheets
4002c15.qxd 7/18/01 2:55 AM Page 450
he word form can bring to mind anything from a paper-based form completed by hand to a Web form filled in on-screen and posted with a Submit button. In Excel, you can create five general types of forms:
t
• Printable forms for manual use • Worksheet forms that include controls for user input • Web forms used on the Internet or an intranet • Access forms created using the AccessLinks add-in • User forms created in the Visual Basic editor
This chapter focuses on the first two types of forms, form controls and ActiveX controls, and using form controls in worksheet forms. The last two types of forms are discussed in Part V, “Out of the Box with Excel 2002,” and Part VII, “Automating Excel 2002 with Macros and VBA.”
NOTE Excel’s web features, are discussed in Chapter 18, “Using Excel 2002 with the Web.” While you can create web forms in Excel, FrontPage is a better tool for creating web forms. See Chapter 16, “Using Excel 2002 with Other Databases,” for information on using Access forms with Excel. See Part VII, “Automating Excel 2002 with Macros and VBA,” for information on Visual Basic user forms.
Creating Printable Forms Create a printable form if you need to distribute a paper form to collect information from users or to create a worksheet for data collection that also creates a good looking hard-copy form when printed. Printable forms are focused primarily on layout. The printable form in Figure 15.1 is a service log page from a program that delivers services to preschool children and their families. This form is similar to forms you’ve used on websites in that they both use merged cells and borders to create the boxes where users enter data. The form in Figure 15.1 includes no formulas. The only validation is for the cells that contain dates, each of which must be after 8/30/2001 and cannot be greater than today. This form can be completed on-screen or filled out by hand. Many of the printable forms we create are then “printed” with Adobe Acrobat PDFWriter and posted on websites for user download.
4002c15.qxd 7/18/01 2:55 AM Page 451
Creating Printable Forms
FIGURE 15.1 The Enrollment Service Record is a printable Excel form.
451
PART
Managing Data with Excel 2002
IV
Forms like this printable form can be created in a variety of applications. Excel is one of four Office XP applications that can be used to create printable forms. In Access 2002, you can use reports or forms as printable forms. Printable forms can be created as easily in Word or Publisher as in Excel. Word forms are based on tables, so the tools used to create printable forms in Word and Excel are nearly identical. Publisher provides better layout tools than Word or Excel, so if your form doesn’t lend itself to a table layout because it contains a number of nonsymmetrical elements, consider creating the form in Publisher. With so many good tools to choose from, user preference often determines which application is used to create forms like the one in Figure 15.1. The network estimate form template, shown in part in Figure 15.2, is completed on-screen in Excel, then printed for internal use. The user enters part quantities and the estimated labor hours, and formulas calculate the materials cost, materials markup, labor cost, and total project cost. Two named constants, Markup and HourlyRate, are used to calculate the materials markup and labor cost.
4002c15.qxd 7/18/01 2:55 AM Page 452
452
CHAPTER 15 • Creating Forms in Excel 2002
FIGURE 15.2 The Network Estimator is filled out on-screen, then printed.
The Network Estimator uses many of the techniques used in other templates: fills for formula cells, protection for formulas, no gridlines, data validation, and user comments. The rounded rectangles used on the top of the form are drawing objects with the fill transparency set to 100 percent so the text in the cells they enclose is visible.
NOTE
For information on the drawing tools, see Chapter 11, “Using Drawing and Graphics Tools.”
Setting Up the Printed Page Unlike a screen form, a paper form doesn’t have scroll bars. All the content needs to be designed to fit neatly within print pages. Before you spend too much time on form layout, choose File Page Setup and set the page size and margins. Then preview the page (File Print Preview) to display the dotted lines that show the edges of each printed page.
Creating a Tool Collection If you’re creating a complex form or anticipate creating a number of forms in Excel, take a few moments and create a custom toolbar to put frequently used form-formatting tools at your fingertips. Right-click any toolbar and choose Customize to open
4002c15.qxd 7/19/01 2:16 PM Page 453
the Customize dialog box. On the Toolbars tab, click the New button, then type a name for your custom toolbar. Click OK to create the toolbar. To add buttons to the toolbar, click the Commands tab of the Customize dialog box, select a category, and drag commands, one at a time, to the new toolbar. The Print Forms toolbar, shown in Figure 15.3, is a custom toolbar with commands from the Format category. FIGURE 15.3 Create a custom toolbar like this Print Forms toolbar with commonly used commands.
NOTE
For more information on custom toolbars, see Chapter 21, “Automating Excel 2002 with Macros.”
Understanding ActiveX and Form Controls Controls are objects placed on a form, usually for user input or display. Controls include the following: Textbox Controls Used to collect or display data. Command Buttons
Used to run Visual Basic code, including macros.
Combo Box and List Box Controls data entry.
Check Box Controls
For user convenience and to ensure consistent
For True/False, On/Off, or Yes/No values.
453
PART
IV Managing Data with Excel 2002
Understanding ActiveX and Form Controls
4002c15.qxd 7/19/01 2:16 PM Page 454
454
CHAPTER 15 • Creating Forms in Excel 2002
Option Button Controls Groups of option buttons allow the user to choose one option from a set of options.
Label Controls
Identify or describe other controls.
Excel 2002 supports two different groups of controls: ActiveX controls and form controls.
ActiveX Controls The ActiveX controls are on the Control Toolbox toolbar. ActiveX controls are used for most forms and are always used when you need to take different actions based on the user’s interaction with a control. For example, you can write Visual Basic code (also known as a macro) that performs different actions based on the item that a user chooses in a combo box, list box, or option group. ActiveX controls are used with three programming languages in Excel 2002. Visual Basic is used for worksheet forms and VB user forms. User forms and the Visual Basic Editor are discussed in Chapters 22–24. ActiveX controls support two web scripting languages, JavaScript and VBScript. You create web scripts using the Script Editor that’s also included with Excel 2002. A form with ActiveX controls can be modified to replace the Visual Basic code with web scripts then published as an online form. ActiveX controls have customizable properties that affect the control’s appearance and behavior. You can set these properties in advance or change them with code at runtime (when the form is being used). This means, for example, that based on the choice that a user makes in a list box control, you can enable or disable other controls. You can see an example of this on the Number tab of the Excel 2002 Format Cells dialog box. When the category General is selected, the label General format cells have no specific number format is displayed, as shown in Figure 15.4. When the user makes another choice from the Category list (for example, Number), other controls are displayed as shown in Figure 15.5. Because Number is selected, the label is replaced with two list box controls and a check box control.
4002c15.qxd 7/19/01 2:16 PM Page 455
Understanding ActiveX and Form Controls
FIGURE 15.4 When General is selected in the Category list box, a label is displayed.
455
PART
Managing Data with Excel 2002
IV
FIGURE 15.5 When a category other than General is selected, Excel displays other ActiveX controls so the user can finetune their choices.
There are two types of worksheets that don’t support ActiveX controls: XLM macro sheets created in early versions of Excel and chart sheets. If you need to add controls to a chart sheet, use the Form controls discussed in the next section.
4002c15.qxd 7/19/01 2:16 PM Page 456
456
CHAPTER 15 • Creating Forms in Excel 2002
NOTE
Chapters 22–24, the Visual Basic chapters, discuss ActiveX controls and user
forms.
Form Controls Form controls are found on the Forms toolbar. Form controls are holdovers from previous versions of Excel and are more limited than the ActiveX controls. Form controls are designed to do two things: collect data and run macros. Form controls will probably disappear in one of the next versions of Excel as more users work with ActiveX controls. They’re included in Excel 2002 because of legacy sheets: XLM macro worksheets, Excel 5.0 Dialogs, and chart sheets—even those created in Excel 2002. If you don’t modify worksheets and forms created in Excel version 5.0, these first two reasons are pretty meaningless, so you can think of form controls as controls you must use on chart sheets and can choose to use in worksheets. The Hours and Expenses form in Figure 15.6 uses list box form controls. Each list box presents users with an appropriate list of values to choose from and stores the selected value in the worksheet cell behind the list box; the cell is used in a formula. FIGURE 15.6 The Hours and Expenses form uses form controls.
4002c15.qxd 7/19/01 2:16 PM Page 457
This form didn’t require ActiveX controls: there is no code in the worksheet, the form’s controls do not need to interact, and we knew we would not publish this form online. While we still could have created the form with ActiveX controls, form controls were a better choice for two reasons: Rapid Development The form was created to meet a short-term need while we tested several products that integrate with our accounting system. With form controls, we could create the worksheet in less than an hour. Maintenance The form could be maintained (during its short life) by staff members who are not programmers. Most form controls use values from the worksheet—for example, a list of values used to populate a list box—and store user choices in the worksheet. If a user chooses the second item in a list box control, the value 2 is written somewhere in the worksheet. If you want to do something specific to respond to the user choice, you need to either handle it in a formula or use another control to run a macro that takes an action based on the value in the worksheet cell. You can’t write a macro that completes an action based directly on the value in the list box control. Form controls have another disadvantage: they can’t be used to run JavaScript or VBScript web scripts. This means that forms created with form controls can’t be easily modified or edited for use on the Web. If you save a worksheet with form controls for the Web, the controls appear in the page, but only as graphic objects. When you click on the controls, nothing happens. To make a worksheet like this a useful web page, you must replace the form controls with ActiveX controls. Despite the disadvantages, form controls have their uses and dedicated users. You don’t need to understand Visual Basic to use form controls, so they provide an easy entry point to worksheet automation, even if you’ve never worked with programming languages or controls. Form controls can do fewer things than ActiveX controls, but that simplicity makes them easier to work with. And form controls are the only tools in the chart sheet control tool kit; if you want to automate from a chart sheet, you’ll become a form controls fan, too.
TIP
Embedded charts and chart sheets, like controls, are objects that can be manipulated with Visual Basic.
457
PART
IV Managing Data with Excel 2002
Understanding ActiveX and Form Controls
4002c15.qxd 7/18/01 2:55 AM Page 458
458
CHAPTER 15 • Creating Forms in Excel 2002
Adding Form Controls to Worksheets To add form controls to a worksheet, begin by displaying the Forms toolbar (View Toolbars Forms), shown in Figure 15.7. FIGURE 15.7 Controls on the Forms toolbar
Click a button on the Forms toolbar then click or drag in the worksheet to add the control to the worksheet. The controls are described in Table 15.1. Controls described as Excel 5.0 are only available if you are editing Excel 5.0 Dialog Sheets and cannot be used in Excel 2002 worksheets. They are included for backward compatibility.
TABLE 15.1
Fo r m C o n t r o l s
Control
Description
Label
Text that describes a control or worksheet feature
Edit box
Excel 5.0 only
Group box
Groups a set of related option buttons or check boxes
Button
Used to run a macro
Check box
Used for Yes/No choices
Option button
Used in a Group Box to collect one choice from a group of options
List box
Used to display a list of items; can support choice of one item or more than one item
Combo box
Used to display a list of items so the user can choose one item
4002c15.qxd 7/18/01 2:55 AM Page 459
Adding Form Controls to Worksheets
Fo r m C o n t r o l s ( c o n t i n u e d )
Control
Description
IV
Combination edit-list
Excel 5.0 only
Combination drop-down edit
Excel 5.0 only
Scroll bar
Scrolls through a list of values
Spinner
Used to increase or decrease a numeric value
The last four buttons on the toolbar are used to arrange, format, and run controls. When a control is selected, the Control Properties button opens the control’s Format Control dialog box. The Control Properties button is not enabled for all types of controls; however, when a control is selected, you can always open the Format Control dialog box from the Format menu or the shortcut menu. The Edit Code dialog box opens the Visual Basic Editor so you can add code to a control. If you’re going to add code to a control, you should move up a notch and use ActiveX controls. But if you want to add code to a form control, Excel allows it. The Toggle Grid button turns the gridline display on and off. The Run Dialog button only works with Excel 5.0 dialog sheets, where it runs the active dialog.
Using Command Buttons We’ll begin with the most frequently used control, the button. Command buttons are used to run macros. You can use an existing macro or record a new macro during button creation.
NOTE
See Chapter 21, “Automating Excel 2002 with Macros,” for information on recording macros.
www
PART
Managing Data with Excel 2002
TABLE 15.1
459
In Figure 15.8, we’ve enhanced the familiar Traverse Tree Sales worksheet by adding three buttons that sort the database by month, county, and type. The workbook, which includes the macros used in this chapter, can be downloaded from the Sybex website (www.sybex.com). If we place the command buttons in the worksheet, users don’t need to learn how to sort using the menu or the toolbar buttons. Even if we hide the Standard toolbar the user can still easily sort the database.
4002c15.qxd 7/18/01 2:55 AM Page 460
460
CHAPTER 15 • Creating Forms in Excel 2002
FIGURE 15.8 The Traverse Tree Sales worksheet includes command buttons to sort the database.
To create a command button, choose the Command Button button on the Forms toolbar. Click in the worksheet to create a standard-sized button or drag to create a custom-sized button. When you release the mouse button, the Assign Macro dialog box, shown in Figure 15.9, opens. Select the macro to run when a user clicks the button, then click OK.
FIGURE 15.9 Choose a macro for the command button in the Assign Macro dialog box.
4002c15.qxd 7/18/01 2:55 AM Page 461
The button is selected in the worksheet. If you clicked elsewhere in the worksheet and the button is not selected, hold the Ctrl key and click on the button to reselect it. A glance at the default text on the button face and you know you have more work to do. Right-click the button and choose Edit Text from the shortcut menu.
Or select the button text on the button. Enter new text to display on the button.
Moving and Sizing Controls While a control is selected, you can drag the control’s handles to resize it. Drag a selected control from any point other than a handle to move the control. For fine adjustment, hold the Ctrl key and use the keyboard arrow keys to move the control or use the Nudge menu on the Drawing toolbar (Draw Nudge).
NOTE
For information on the Drawing toolbar, see Chapter 11, “Using Drawing and Graphics Tools.”
When you have two or more controls, you can move and size them in relation to each other using the Align or Distribute menu on the Drawing toolbar. To keep a set of buttons like the set in Figure 15.8 together for move operations, hold the Ctrl key and select the buttons, then choose Draw Group from the Drawing toolbar.
TIP You can copy and paste an existing button to create an identical button. The Assign Macro dialog box does not open automatically for the copied button. Right-click the copy and choose Assign Macro from the shortcut menu.
Setting Button Properties To set other button properties, select the button and choose Format Control from the menu or right-click and choose Format Control from the shortcut menu to open
461
PART
IV Managing Data with Excel 2002
Adding Form Controls to Worksheets
4002c15.qxd 7/18/01 2:55 AM Page 462
462
CHAPTER 15 • Creating Forms in Excel 2002
the Format Control dialog box. The Font tab of the Format Control dialog box is shown in Figure 15.10. Table 15.2 describes the format properties for command buttons. The Web, Properties, and Protection settings are common to most of the form controls. FIGURE 15.10 Set the appearance of the command button in the Format Control dialog box.
TABLE 15.2
Command Button Control Properties
Tab
Property
Description
Font
Font Font Style Size Underline Color Normal Font Effects
Formats button text. Enable the Normal Font check box to use the default button text formatting.
Alignment
Text Alignment
Use to set horizontal and vertical text alignment.
4002c15.qxd 7/18/01 2:55 AM Page 463
Adding Form Controls to Worksheets
Command Button Control Properties (continued)
PART
Tab
Property
Description
IV
Alignment
Orientation
Rotates button text.
Alignment
Text Direction
Sets direction for rotation and alignment.
Alignment
Automatic Size
Sizes button to fit text.
Size
Size and Rotate Scale Lock Aspect Ratio
Manually size button or increase/decrease the size as a percentage of original size.
Margins
Automatic Left Top Right Bottom Alternative Text
Automatically or manually set internal margin (between button edge and button text).
Managing Data with Excel 2002
TABLE 15.2
463
Web
Specify alternative text to appear in a browser as the control downloads.
Properties
Object Positioning Print Object
Specify whether button should move, resize, or neither when surrounding cells are moved or resized and whether the button should appear in hard copy.
Protection
Locked Lock Text
Lock the button and/or button text to prevent changes when worksheet is protected.
To precisely size and align two or more controls, follow these steps: 1. Hold the Ctrl key and select all the controls you want to size and align. 2. Right-click and choose Format Object. 3. To size the controls, enter a Height and/or Width setting for all selected objects on the Size tab of the Format Object dialog box. Click OK to close the dialog box. 4. On the Drawing toolbar, choose Draw Align or Distribute to open the Align or Distribute menu. Select the appropriate alignment or distribution for the selected objects.
TIP
To copy font settings from one button to another, use the Format Painter.
4002c15.qxd 7/18/01 2:55 AM Page 464
464
CHAPTER 15 • Creating Forms in Excel 2002
Using List Controls Consistency may be the hobgoblin of small minds, but it’s also the key to accurate reporting. Database functions like sorting, filtering, subtotaling, and lookups only work when users enter data the same way. When they don’t, filters omit data and subtotals are inaccurate. One of our clients called with a typical reporting problem. Five different employees entered data in a worksheet used to track information about clients. The client’s employer was entered in one of the columns, and the data entry was very inconsistent. For example, the five employees had found seven different ways to enter Ford Motor Company: • Ford Motor Co. • Ford Motor Company • Ford • FoMoCo • Ford’s • Ford Motor • FMC The client needed to accurately report on the 16,000 records in the worksheet: an almost hopeless task with data this inconsistent. Ultimately, we imported the data into Access and used a wizard to remove the inconsistencies. We returned the cleaned data and a worksheet that used combo boxes to ensure consistency when data was entered. Combo boxes and list boxes present a limited list of choices that a user selects from. If there’s only one listing for Ford Motor Company, the user will find it rather than making up their own abbreviation. The combo box or list box is linked to a cell. When a user chooses an item from the control list, the ordinal number of the item is placed in the linked cell. For example, if a user chooses the third item, Excel writes 3 in the linked cell. There are two differences between list boxes and combo boxes. A user can only select one item in a combo box, while a list box’s properties can be set to allow more than one selection. Combo boxes are more compact, displaying only one item when they are not active. List boxes are often expanded so that a range of items (or all items) are visible even when the list box is not active, as shown in Figure 15.11.
4002c15.qxd 7/18/01 2:55 AM Page 465
Adding Form Controls to Worksheets
FIGURE 15.11 List boxes take up more space than combo boxes, but they display multiple choices even when the list box is not active.
465
PART
The additional control properties for list boxes and combo boxes are described in Table 15.3.
TABLE 15.3
Combo and List Box Control Properties
Property
Description
Input Range
The range of cells used to populate the list. For list and combo boxes.
Cell Link
The cell where the results of the user selection should be placed. For list and combo boxes.
3-D Shading
Formats the control borders to create a sunken appearance.
Selection Type
Determines if and how users choose multiple items. List boxes only.
Drop-Down Lines
Specifies how many items are displayed when the control is open. The user must scroll to view additional items. Combo boxes only.
To use a list box control, click the List Box button in the Forms toolbar then click or drag in the worksheet to place the control. Right-click and choose Format Control from the shortcut menu, choose Format Format Control from the menu, or click the Control Properties button on the Forms toolbar to open the Format Control dialog box. The Control tab is shown in Figure 15.12. The Input Range is a range of cells that contains the items that will be presented in the list box. If the input range is not on the same worksheet as the list box control, name the range. If you want the items presented in alphabetical order, sort the list in the worksheet.
Managing Data with Excel 2002
IV
4002c15.qxd 7/18/01 2:55 AM Page 466
466
CHAPTER 15 • Creating Forms in Excel 2002
FIGURE 15.12 Set the input and output ranges for a list box or combo box on the Control tab.
Choose a Cell Link: the cell that receives output from the list box. The cell link only matters if you choose a Single selection type. In the Selection Type options, choose from the following: Single Forces the user to choose only one item from the list. The number of the item is written to the Cell Link cell. Multi Allows the user to choose more than one item. When the user clicks a second item, both the first and second item are selected. Nothing is written to the Cell Link cell. Extend Allows the user to choose more than one item by holding Shift or Ctrl and clicking on additional items. Nothing is written to the Cell Link cell. If you choose the Single selection type, you can use the INDEX function (described in Chapter 7, “Using Logical Functions”) in a formula to return the item from the input range. In Figure 15.12, the input range is $O$10:$O$14. The cell link is $O$19. This formula returns the item that the user chose in the list box control: =INDEX($O$10:$O$14,$O$19).
TIP
If you use the Multi or Extend options, you’ll need to add code to work with the control output.
4002c15.qxd 7/18/01 2:55 AM Page 467
Using a Combo Box Combo boxes are a lot like list boxes, but their compact size makes them more useful in some instances. Create the combo box by clicking the Combo Box button on the Forms toolbar, then clicking in the worksheet. Open the Format Control dialog box. On the Control tab, set the Input Range and Link Cell. In the Drop Down Lines control, enter the number of lines that should be displayed before the user needs to scroll. If there are more than a dozen items on the list, eight drop-down lines works well. For lists of less than 13 items, set the control to display the entire list by setting the Drop Down Lines for the actual number of items. As with the list box control, Excel writes the number of the selected item in the Cell Link cell. Unlike the list box, a combo box is about the size of a worksheet cell, which allows you to work some real magic in a worksheet. In Figure 15.13, we’ve added combo box controls to the Type column in the Traverse Tree Sales worksheet. The combo boxes all use the same input range: a five-cell range named TreeTypeList on a hidden worksheet. Users choose a tree type from the constrained list, so everyone will enter Blue Spruce rather than Spruce or BS. FIGURE 15.13 In this version of the Traverse Tree Sales database, users select a tree type from the combo box.
The cell link is in column G, which is hidden. The real magic is in location of the formula, which sits in the cell directly underneath the combo box. For example, cell C6 has this formula: =INDEX(TreeTypeList,G6). For all the combo boxes, the Print Object property on the Properties tab is turned off, so when the user prints the worksheet, the combo boxes disappear, leaving the formula cells, as shown in Figure 15.14.
467
PART
IV Managing Data with Excel 2002
Adding Form Controls to Worksheets
4002c15.qxd 7/18/01 2:55 AM Page 468
468
CHAPTER 15 • Creating Forms in Excel 2002
FIGURE 15.14 The combo boxes’ Print Object property is turned off, so the underlying formulas print when the worksheet is printed.
When you have a number of nearly identical combo boxes to create, use copy and paste, then right-click and choose Format Control to change the properties (like Cell Link) that need to be different. Don’t worry about precisely placing the controls. Create them all, place the first and last controls, then select the controls and use the Align or Distribute commands on the Drawing toolbar to align them all. When you use controls in a worksheet that may be sorted, make sure that the Cell Link is to a cell in the same row as the control and that the Object Positioning property is set to either Move and Size with Cells or Move but Don’t Size with Cells.
Using Validation Instead of a List or Combo Box Excel 2002 includes one other way to limit users to a list of data entry items: validation. If your user can choose only one item from a list and you don’t intend to extend its functionality by adding code to a combo or list box, validation may be exactly what your worksheet requires.
4002c15.qxd 7/18/01 2:55 AM Page 469
Adding Form Controls to Worksheets
469
PART
On the Settings tab choose List in the Allow drop-down list. In the Source text box, specify the range of cells that contains the list items. Enable the In-Cell Dropdown check box to add a drop-down list, much like a combo box, to each selected cell.
NOTE
See the “Validation” section in Chapter 12 for more information on validation.
Using Scroll Bars and Spinners Spinners and scroll bars scroll through a range of values. The controls are similar: both move through a range of values, and they share common control properties described in Table 15.4. Use spinners for a narrow range of values where users don’t
IV Managing Data with Excel 2002
First, create and sort the single column list. Then select the range of cells where you want users to choose an item from a list. Choose Data Validation to open the Data Validation dialog box.
4002c15.qxd 7/18/01 2:55 AM Page 470
470
CHAPTER 15 • Creating Forms in Excel 2002
mind clicking once for each increment. Scroll bars, which allow users to increment a value in small units and larger chunks, are used for wider ranges of values.
TABLE 15.4
Spinner and Scroll Bar Control Properties
Property
Description
Current Value
Relative position of the control within the range of allowable values
Minimum Value
Lowest (smallest) value allowed for the control
Maximum Value
Highest (largest) value allowed for the control
Incremental Change
Amount the scroll box or spinner moves when the user clicks the arrow once
Cell Link
Cell that contains the current value of the scroll box or spinner
Page Change
Scroll bars only; the incremental change when a user clicks the scroll bar between the scroll box and either scroll arrow
With both spinners and scroll boxes, you probably don’t want to place the Cell Link in the cell directly underneath the form control. With a combo or list box, the current value is boldly displayed in the control. Spinners have no display area, and the display for a scroll bar is the relative position of the scroll box within the bar, which is only helpful if the user also knows the minimum and maximum values for the scroll bar. Typically, spinners and scroll bars are linked to a nearby cell, as shown in Figure 15.15. FIGURE 15.15 Spinners and scroll bars are used to select a value from a range.
4002c15.qxd 7/18/01 2:55 AM Page 471
Using Group Boxes, Option Buttons, and Check Boxes Option buttons, like combo boxes, are used for single, mutually exclusive choices. An option button can be used as a True/False button, but the Windows standards suggest check boxes be used for single True/False choices. Option buttons are generally placed in a Group Box control and are used as a set of options that represents the universe of choices; unlike a combo box or list box, a user must choose one option from the group box. Table 15.5 describes the Control properties for option buttons.
TABLE 15.5 Property
Option Button Control Properties Description
Value
Checked, Unchecked, or Mixed
Cell Link
Cell that contains the current value of the option button or option group
If an option button is used outside a group, the Mixed option sets the default button state to N/A to indicate it has not been enabled. In an option group, only one option button can be selected. Figure 15.16 shows an option group with five choices. All five buttons have the same Cell Link. The linked cell contains the number of the option selected. The first option button is numbered 1. FIGURE 15.16 The user must choose one option from the group.
To create option buttons, first create a group box. Then create an option button in the group box, and set the button’s Value and Cell Link properties. Copy the button to create additional options.
471
PART
IV Managing Data with Excel 2002
Adding Form Controls to Worksheets
4002c15.qxd 7/18/01 2:55 AM Page 472
472
CHAPTER 15 • Creating Forms in Excel 2002
Check boxes are used to represent a single Boolean choice: Yes/No, True/False, or On/Off. A check box has three possible values: TRUE, FALSE, or N/A. Set the default value on the Control tab of the Format Control dialog box. If you choose Mixed, the check box returns the value N/A until the user clicks the control. After the control has been clicked and its value changed, the only possible values in the linked cell are TRUE and FALSE.
4002c16.qxd 7/18/01 2:57 AM Page 473
PA R T
V
OUT OF THE BOX WITH EXCEL 2002 ◗
Using the Template Wizard with Data Tracking
◗
Using Access forms and reports in Excel
◗
Importing data
◗
Querying other data sources with Excel and Microsoft Query
◗
Creating and using OLAP cubes
◗
Converting, linking, and embedding
◗
Using Excel within Office XP
◗
Creating static web pages in Excel 2002
◗
Constructing web pages with interactivity
◗
Setting up automatic republishing
4002c16.qxd 7/18/01 2:57 AM Page 474
This page intentionally left blank
4002c16.qxd 7/18/01 2:57 AM Page 475
16
CHAPTER
USING EXCEL WITH OTHER DATABASES F E ATU R I NG
Using the Template Wizard with Data Tracking
Exporting Excel data to Access
Converting an Excel database to an Access database
Using Access forms and reports in Excel 2002
Importing data
Connecting to OLE DB data sources
Connecting to ODBC data sources
Using Microsoft Query to query data sources
Using OLAP cubes
4002c16.qxd 7/18/01 2:57 AM Page 476
n this chapter, we travel beyond the limits of Excel to work with Access and other databases. Excel is the most powerful data conversion tool on most user’s PCs: if you can’t open a data file in other applications, don’t give up until you’ve taken a shot at it with Excel. Excel opens a wide variety of files in their native formats, includes converters for other file formats, and has an import wizard to help you identify and map imported data. Add Microsoft Query to the mix, and you can work in Excel with live data from other sources including databases created in Access, Oracle, dBASE, FoxPro, as well as text databases with delimited or fixedlength records. Add an ODBC connection, and Excel’s reach extends to the vast majority of business databases. If you’re a corporate data creator or user, you’ll quickly appreciate Excel’s dominance as a data-analysis and presentation tool for a wide range of external data. We’ll begin with tools created to work with Excel and its companion database in the Office suite, Access 2002. Then we’ll explore data importing: a new feature with a recycled name in Excel 2002, importing creates a live connection to an external data source. We’ll follow importing with a more powerful tool, Microsoft Query, used to connect to data sources that need to be sorted or filtered prior to importing (such as databases too large for Excel to handle in total). Table 16.1 summarizes the data sources and acquisition methods detailed in this chapter.
i
TABLE 16.1
Importing and Querying in Excel
Item
Description
Import
Import refreshable data so you can manipulate it in Excel 2002. Data must be from a single source (table, view, or query) and must be a small enough source to fit in a worksheet.
Query
Use Microsoft Query to sort, filter, or relate data before bringing it into Excel for analysis.
Connection
ODBC or OLE-DB connection to a database or connection to an analytical processing server. The connection can be used by Microsoft Query or Excel to import data.
Data Source
Any data set that can be acquired directly with Import or by using a connection.
OLAP
Online analytical processing that is used to create 3D pivot tables.
This chapter is a guide to acquiring data from non-web sources so it can be analyzed, calculated, and reported using Excel 2002. Chapter 17, “Importing and Exporting from Excel 2002,” discusses interactivity with Excel and the other applications in the Office suite. In Chapter 18, “Using Excel 2002 with the Web,” we return to importing and exporting, focusing on Excel and the Web.
4002c16.qxd 7/18/01 2:57 AM Page 477
Using the Template Wizard with Data Tracking
477
Using the Template Wizard with Data Tracking Excel’s interactivity with external data is useful both externally and internally. The Template Wizard with Data Tracking creates templates that link cells in a workbook to fields in a database—an Access, FoxPro, dBASE, or Excel database. When a user creates a new workbook using the template, data entered in the linked cells is entered directly into the database. If you’re working with relational data, the Template Wizard gives you the best of both worlds. Users work in Excel, so you don’t need to create and distribute an Access front-end database or Visual Basic user forms. The data is collected in Access, so multiple users can enter data simultaneously.
The workbook is also saved, so the user has a record of the data they entered. However, the Access database contains data from different templates created by different users or by one user at different points in time. For example, in your time-tracking application, you want employees to enter hours for a task in an Excel worksheet, but you need to store and report on the hours for all tasks and all employees. Begin by creating a worksheet that employees use to enter their hours for one task, then use the Template Wizard with Data Tracking to create a template from the form and connect the form’s data ranges to an Access table. When employees enter their hours in the template, the information is automatically copied to create a single record in the database.
TIP
If you have existing data that should be included in the database, you can add it with the wizard when you set up the template.
PART
V Out of the Box with Excel 2002
NOTE The Template Wizard and AccessLinks add-ins were not yet available as this book went to press. The Excel 2002 versions of both add-ins will be available from the Microsoft Excel Download website in June 2001. Figures included in this section show the previous version of the Template Wizard and AccessLinks. We normally exclude features that we haven’t seen, even if Microsoft indicates they’ll be available, but we’re including these two add-ins anyway. We use them, they’re fabulous, and you need to know about them. Please forgive the inevitable minor discrepancies in appearance between the book’s illustrations and the final version of these two add-ins.
4002c16.qxd 7/18/01 2:57 AM Page 478
478
CHAPTER 16 • Using Excel with Other Databases
To use the wizard, first set up the Excel workbook. Open the workbook you’ll use as the basis for the Excel template. Enter labels for the data that a user will enter; the labels can be in a column to the left of the data entries or a row of column headings above the data. The labels will be used as field names in the database, so use labels that are acceptable field names in the database you’ll use with the wizard. The workbook you use can be a blank workbook or a workbook with a sheet that follows the format previously described.
www
NOTE
To install the Template Wizard with Data Tracking add-in, download the add-in from the Microsoft website at office.microsoft.com/Downloads/default.aspx. To install the add-in, choose Tools Add-ins to open the Add-Ins dialog box. Enable the Template Wizard with Data Tracking check box and click OK. If you installed Office from a CD, you’ll be prompted to insert it.
Format the worksheet so users know where to enter data. Remember that they can’t enter more than one record in a worksheet, so your completed worksheet will look like a single record form, not a grid. Delete extra sheets and select the cell that should be selected when the template opens. For more tips on appropriate formatting for templates and forms, see Chapter 14, “Creating Workbook for Other Users,” and Chapter 15, “Creating Forms.” Save the workbook, then choose Data Template Wizard to launch the Wizard. In the first step of the wizard, shown in Figure 16.1, choose the workbook from the list of workbooks. If you don’t see the workbook you want, select the Cancel button, then open the workbook and restart the wizard. In the text box, verify or change the template name. The filename and path in the wizard are the selected workbook name and the path to the default Office template folder. To store the template in a subfolder of the template folder or a workgroup template folder, edit the path.
TIP
If you want other users to access the template, you need to store it in a shared folder that they have permission to access.
In the second step of the wizard, shown in Figure 16.2, choose the type of database you want the wizard to create and type a name and path (the default path places the database in the same folder as the workbook). To use an existing database file, click Browse and locate the database. There’s more of a difference between these two choices than it would initially seem. The Template Wizard creates flat files—a single
4002c16.qxd 7/18/01 2:57 AM Page 479
Using the Template Wizard with Data Tracking
479
worksheet in Excel or a single table in one of the more robust databases. If you want to copy data from the wizard to multiple tables in a normalized Access database, you must create the database first, then select the database in this second step of the Template Wizard. FIGURE 16.1 Select a workbook and name the template that will be created from the workbook.
PART
NOTE
The drop-down list only includes the supported database types that have ODBC drivers installed on your computer. See “Creating a New Data Source” later in this chapter for more information.
FIGURE 16.2 Select a database type for a new database or locate an existing database to connect the template to.
Out of the Box with Excel 2002
V
4002c16.qxd 7/18/01 2:57 AM Page 480
480
CHAPTER 16 • Using Excel with Other Databases
In the third step of the wizard, shown in Figure 16.3, map the template to the database. In the Sheet or Table drop-down list, select the sheet or table you wish to use from an existing database. If you’re creating a database in the wizard, enter a name for the sheet or table. FIGURE 16.3 Select the table or sheet and map the cells in the template to the fields in the database.
Then identify each of the cells where users will enter data. Click in the Cell text box, click in the worksheet cell where the user will enter data, then click in the corresponding Field Name text box. If you’re using an existing database, the field names can’t be changed. If you’re creating a new database, you can change the field names using the specifications for naming fields in the database type you chose. In the fourth step of the wizard (see Figure 16.4), choose whether you wish to add existing data as a batch when the template is created. If the data in the existing Excel workbooks is located in the same cells on sheets with the same names, this works like a charm. FIGURE 16.4 Choose to import existing Excel data or skip to the next step.
4002c16.qxd 7/18/01 2:57 AM Page 481
Using the Template Wizard with Data Tracking
481
You only see the next part of this step of the wizard (also numbered Step 4 of 5), shown in Figure 16.5, if you choose to import existing data.
WARNING
If the cell locations or sheet names aren’t identical to those used in the template, don’t use the fourth step of the wizard to import existing data. Either cancel the wizard, rearrange the existing workbooks and launch the wizard again, or finish the wizard and then copy and paste or use the database’s import commands to import the data.
FIGURE 16.5 Select files with data you wish to add to the database. PART
Out of the Box with Excel 2002
V
Click the Select button and locate the first workbook that contains matching data that should be included to add it to the file list. Check the Table drop-down list to make sure the correct sheet in the workbook is selected. Then select the file in the Files to Convert pane and click the Preview button. If the field names and sheet names in the selected file match those in the template, the record that will be copied from the sheet appears in the preview section, as shown in Figure 16.5. If the workbook structure is not the structure used in the template, Excel will be unable to import the data and this message box is displayed:
4002c16.qxd 7/18/01 2:57 AM Page 482
482
CHAPTER 16 • Using Excel with Other Databases
This message doesn’t mean that there’s no data in the workbook—either the workbook’s data is not in the cells you identified in the template or the worksheet has a different name. In the last step of the wizard, you’ll see the names of the files created by the Template Wizard. There’s one more feature you can add at this point. When a user creates a new file based on the template, enters data, and then closes the file, you can automatically route the file to other users (or to yourself). Click the Add Routing Slip button to fire up Outlook and open the Routing Slip dialog box.
After you create (or choose not to create) a routing slip, click Finish to close the Template Wizard.
NOTE
For more information about routing, see “Routing Workbooks” in the “Working with Workgroups” section of Chapter 20.
The template appears on the General tab of the Templates dialog box (or another tab representing a folder that you specified in the first step of the Wizard). The template contains macros to copy data to the database, so the user will see the Enable Macros/Disable Macros message box when they open the template.
4002c16.qxd 7/18/01 2:57 AM Page 483
Working with Access and Excel
483
A database record is created when the user saves the file. If they change the record and save again, they’ll be asked whether they should create a new record, update the existing record, or continue without updating.
EXPERT TIP
Add-ins are loaded with the application. Remove unused add-ins to launch Excel more quickly. Choose Tools Add-Ins and disable the check boxes for addins you no longer use.
Working with Access and Excel Access 2002 and Excel 2002 have a special relationship: they use the same data engine and are designed to work together. From Access, you can easily move or copy Access data to Excel, import Excel data, or link to an Excel worksheet or range. From Excel you can copy Excel data into Access or convert an Excel worksheet to an Access database. With the installation of the AccessLinks add-in, you can create Access forms and use them in Excel or use Access Reports to provide consistent reports from Excel databases. And even without add-ins, Access data is only a step away from Excel. As you’ll see later in this chapter, you can query Access databases
PART
V Out of the Box with Excel 2002
The Template Wizard with Data Tracking is a useful way to create and distribute a system to replace a manual form: weekly payroll or expense sheets, equipment requests, and so forth. Create the worksheet, store the database in a shared folder, then use the features in the Wizard to send the template to the users who require it. If you’re using the Template Wizard for the first time, be patient. Before you assume that the template does not work, close and reopen the database a couple of times. The template can be used to create one record after another (if the user chooses Create a New Record), but only records created in the cells you selected are transferred to the database.
4002c16.qxd 7/18/01 2:57 AM Page 484
484
CHAPTER 16 • Using Excel with Other Databases
with Microsoft Query and work with the data in Excel where you have access to pivot tables and charts and analysis and presentation tools.
NOTE
Many of Excel’s Access features require the AccessLinks add-in, so this is a good time to install it. Download AccessLinks from the Microsoft site. Choose Tools Add-Ins to open the Add-Ins dialog box, then select the Microsoft AccessLinks Add-In check box and click OK.
Copying Data from Excel to Access To copy data from Excel to Access, the Excel worksheet columns must be in the same order as the fields in the Access table. You can rearrange the columns in Excel or open the table that you want to paste records into and rearrange the order of the columns in Access. Access database fields have constraints that aren’t normally included in Excel databases. Data fields are constrained by data type and length and may also include validation rules and required properties. Excel data that you want to copy must meet the requirements set in Access. For example, you can’t enter text in a field with a date/time or number data type in Access. Before copying data in Excel, check the data for these typical problems and correct the problem before proceeding: Text Entries in Number Columns Should not have None or NA in a number column rather than a blank cell or 0 value. Formatting
Merged cells anywhere in the Excel database should be unmerged.
Missing entries in required fields If a database field is required, every record in the Excel database must have an entry for the field. Access AutoNumber fields are incremented by Access. The first record is given the number 1, the second 2, and so on. You can’t import or paste values into an AutoNumber field. If the Access table includes a field of the AutoNumber data type, your Excel database must include an empty column for the AutoNumber field.
TIP To see the field properties in an Access table, select the table in the database window and click the Design button. In Design view, select a field to view its properties in the properties list at the bottom of the window.
4002c16.qxd 7/18/01 2:57 AM Page 485
Working with Access and Excel
485
When the Excel database meets the criteria specified in Access, including the field order, follow these steps to copy and paste data: 1. In Excel, select the data to be copied. Do not select the column headings. 2. Copy the data to the clipboard. 3. In Access, open the table where you want to paste the data. 4. On the Access menu, choose Edit Paste Append to paste the data.
Unique Values The Access table has a primary key field used to identify records— for example, a social security number. Values in this field must be unique. If the table already included a record with the social security number 381-22-2222, you can’t paste another record with the same number. If your Excel worksheet included two records with the same number, Access will paste the first and send the second to Paste Errors. Required Fields The primary key field is required, but other fields may also be required. Open the table in Design view and check the Required property of each field. Fill in any missing information in the Paste Errors records. Validation Errors Open the table in Design view and see if any of the table’s fields include validation rules. If so, correct any of the Paste Errors records that violate the rules. After you’ve made some (or all) the corrections to the records in Paste Errors, select the records from the Paste Errors table in Access, copy them, and append them again.
PART
V Out of the Box with Excel 2002
Access pastes the data, if it can be pasted, on a record-by-record basis. If some records cannot be pasted, they’re placed in a table named Paste Errors. Access reports the number of records that cannot be pasted and directs you to the Paste Errors table. How you handle the errors depends on how many there are. If Access couldn’t paste any of the records, there’s a structural difference that Access can’t resolve between the Excel data and the Access table. For example, the fields may be in a different order or you may be attempting to paste values in an AutoNumber field. Fix this problem by finding and correcting the mismatch, then try again following the four steps. If some, but not all records could be pasted, the problem isn’t structural. Examine the records in the Paste Errors table and correct these problems:
4002c16.qxd 7/18/01 2:57 AM Page 486
486
CHAPTER 16 • Using Excel with Other Databases
Converting an Excel Worksheet to an Access Database Here’s the typical Access conversion experience: you’ve collected a lot of data in an Excel worksheet, but your data is outgrowing Excel. You can outgrow Excel in a variety of ways: Worksheet Size Limitations more every day.
You have more than 65,535 records and are adding
Maintenance Requirements You use lookup functions, and the contents and size of the lookup ranges are changing, requiring you to rework the functions. Data Integrity and Security You need to protect the integrity of your data and limit the rights that users or groups have to change, add, or delete records. Related Data database.
You need to relate data from this database to records in another
When it’s time to convert your data, treat the conversion as a one-way street. After you convert an Excel database to Access, abandon the Excel data set and work with the data in Access. Rename or move the Excel data so that users don’t mistake it for the current database. You can still use Excel to manipulate and analyze the data, but do this by connecting to the Access version of the data (as you’ll see later in this chapter). When you convert the Excel data, you can place it in a new database or an existing database. If you choose an existing database, you can put the data in a new table or add it to an existing table. To convert an Excel database to Access, install the AccessLinks add-in then: 1. Save the workbook. 2. Select any cell in the database. 3. Choose Data Convert to MS Access from the menu to open the Convert to Microsoft Access dialog box.
4. To convert the data to a table in an existing database, choose the Existing Database option and click Browse to locate the database. Retain the default New Database option to create a new database.
4002c16.qxd 7/18/01 2:57 AM Page 487
Working with Access and Excel
487
5. Click OK to launch Access and start the Import Spreadsheet Wizard. 6. In the first step of the wizard, disable the check box if your data does not have column headings. Click Next. 7. In the second step of the wizard, shown in Figure 16.6, choose New Table or select an existing table for the converted data. Click Next.
FIGURE 16.6 In the second step of the wizard, choose new table or an existing table.
PART
Out of the Box with Excel 2002
V
8. In the third step, shown in Figure 16.7, select a field in the grid and change the name and index settings. You can change the column name (field name) to match an existing Access field name. If a field is a primary key, set the Index value to Yes (No Duplicates). You may also set a sorting index (Yes, Duplicates OK) for fields that are frequently used as a basis for sorting. Enable the Skip check box to omit an Excel field from the Access database. Repeat the process for each field. Click Next. 9. In the fourth step (see Figure 16.8), select a primary key field for the database. In a primary key field, each value must be unique: Let Access Add a Primary Key Access will add an AutoNumber field to the table, consecutively numbering the records. Choose My Own Primary Key your list of converted fields. No Primary Key
Select a field that contains unique values from
Don’t assign a key at this time; set a key later in Access.
4002c16.qxd 7/18/01 2:57 AM Page 488
488
CHAPTER 16 • Using Excel with Other Databases
FIGURE 16.7 Set the name and index properties for each field.
FIGURE 16.8 Set (or don’t set) a primary key for the table.
TIP In some tables, the primary key consists of two or more fields that, taken together, always have a unique value. The Import Spreadsheet Wizard only allows you to select one field as a key, so for multifield primary keys, choose No Primary Key in the wizard. After you’ve imported the worksheet, open the table in Access Design view and set the key.
4002c16.qxd 7/18/01 2:57 AM Page 489
Working with Access and Excel
489
10. In the last step of the wizard, enter a name for a table and click Finish to create the table and convert the data. Access will notify you if there are duplicate values in your key column. It won’t set a primary key, but will still create the table.
Using Access Forms and Reports in Excel With the AccessLinks add-in installed, you can create Access Forms and Reports for use with an Excel database. AccessLinks creates a link from the worksheet database to an Access Database, then launches the appropriate wizard to create a form or report. The forms and reports are stored in an Access database, but can be used directly in Access or launched from Excel. If you’ve longed for the functionality of Access forms in Excel databases, you’re probably ready to rock and roll.
Creating an Access Form Follow these steps to create an Access form in Excel: 1. Select any cell in the Excel database. 2. Choose Data MS Access Form. 3. In the Create Microsoft Access Form dialog box, select a new or existing database to house the form. 4. Indicate whether your database has a header row. Click OK. 5. Follow the instructions in the Access Form Wizard. You can modify the form in Access in the form’s Design view. Records added or edited in Access are added to the Excel database. In Excel, AccessLinks adds a View MS Access Form button next to the database. Click the button to launch Access and open
PART
V Out of the Box with Excel 2002
A different message box notifies you when the data has been imported successfully. If you created a new database, the database is given a name based on the name of the workbook. Close the database and rename it in the Windows Explorer. When you return to the Excel worksheet, you’ll quickly notice a large text box next to the Excel database, notifying users that the database has been converted to Access and displaying the path and name of the database.
4002c16.qxd 7/18/01 2:57 AM Page 490
490
CHAPTER 16 • Using Excel with Other Databases
the form. To reposition the button in the worksheet, hold the Ctrl key and click the button. Release the Ctrl key and drag the button to move it. The Access Form does not support Excel fields with formulas. One of the rules of database design is that you shouldn’t store calculations based on other fields in the table. For example, you can have fields for employee hours and employee pay rate, but the gross pay should be calculated on-the-fly (in a report or form) by multiplying the two, not stored in a separate field. There are two reasons for this: the fields take up system resources and they build in a place for error. If either hours or pay rate changes in a well-designed database, the user need only change the field that changed. In a database that includes a gross pay field, at least two fields need to be changed when either hourly rate or hours changes. You can add calculated fields to the Access form in Design view in Access.
Creating an Access Report To create an Access report in Excel, follow these steps: 1. Select any cell in the Excel database. 2. Choose Data MS Access Report. 3. If you’ve already used Access Links with this workbook, the report is created in the linked database file. If there are no Access Links in the workbook, select a new or existing database to house the report. Indicate whether your database has a header row. Click OK. 4. Follow the instructions in the Access Report Wizard. In Excel, AccessLinks places a View MS Access Report button next to the database. Click the button to view the report again.
WARNING If you make changes to the Excel database or add records, the changes won’t be reflected in the report. You’ll need to create a new report to reflect the changed data. Hold the Ctrl key and click the View MS Access Report button in the worksheet to select the button. Press the Delete key to delete the button (and report) from the workbook, delete the report from the Access database, then return to Excel and follow the preceding steps to create a new report.
4002c16.qxd 7/18/01 2:57 AM Page 491
Importing Data
491
Importing Data In Excel, the line between native data and all other data gets fuzzier with each version. It’s much easier to work with external data in Excel 2002 than in Excel 2000, which was a giant improvement over Excel 97. With Excel 2002, you can easily link to data from most data sources using the Select Data Source dialog box shown in Figure 16.9. Choose Data Import External Data Import Data to open a doorway to all the data that Excel 2002 can handle natively.
FIGURE 16.9 Import data from a wide range of sources in Excel 2002. PART
Out of the Box with Excel 2002
V
While Microsoft named this feature Importing in Excel 2002, the result isn’t an import in the traditional sense of data that’s copied and converted. The result of this type of import is a refreshable link to an external data source from files like these: • OLEDB data sources • ODBC data sources • Exchange Server folders • Web queries • HTML and XML files • SQL databases • Access databases
4002c16.qxd 7/18/01 2:57 AM Page 492
492
CHAPTER 16 • Using Excel with Other Databases
When you copy data and manipulate it in Excel 2002, the data is frozen in time: If you’re working with data you copied yesterday, the data set doesn’t include changes made today. Importing, as you’re about to see, creates a link or connection to the data, so that you can always retrieve the most current data. When you need to work with external data in Excel, start by attempting to import the data using the Import Data command. If the imported data does not meet your needs, or if you cannot import the data, proceed to the next sections on creating and using data sources.
NOTE
For “traditional” importing, which copies and converts data, see Chapter 17, “Importing and Exporting from Excel 2002.”
Understanding Data Sources Improved software and hardware for microcomputer access to mainframe data have radically changed the role of PCs in business, and Office XP continues the trend toward greater desktop access to hard-core corporate data with support for ODBC (Open Database Connectivity) as well as OLEDB. ODBC is an open standard for database access. ODBC was not developed by Microsoft, but it is often thought of as a Microsoft standard because Windows was the first operating system to support ODBC. Access and SQL Server are both ODBC-compliant, as are many other database programs. Widespread use of the ODBC standard means that you can query data from a variety of sources on your PC, whether or not the data was created on a PC. For example, you may want to create an Excel PivotChart to present information stored in an Oracle database. To do this, you will use a combination of software: • Microsoft Query to create a query • Excel 2000 to open the query • The ODBC Driver Manager, which is part of Windows • A specific ODBC driver, included with Office XP, designed to allow Query to “talk to” the Oracle database • The Oracle database The combination of a database and the ODBC driver to connect to it is called a data source. Office XP includes ODBC drivers for the following programs: • Microsoft SQL Server • Microsoft SQL Server OLAP Services 7.0 and later
4002c16.qxd 7/18/01 2:57 AM Page 493
Importing Data
493
• Microsoft Access 2000 and 2002 • dBASE • Microsoft FoxPro • Microsoft Excel • Oracle • Paradox • Text databases ODBC-compliant databases usually ship with their own ODBC drivers, and there are third-party drivers available. If you want to use Office XP to analyze information in a database that’s not listed here, first check with the database manufacturer to find out how to get a 32-bit ODBC driver; often, you’ll find that it was included with the software. You can also check the Microsoft website for ODBC drivers that were not included with Office XP. The driver will have a setup program to assist with installation.
PART
ODBC Drivers Before you can set up a data source, you must have the appropriate driver. There are two types of ODBC drivers: 16-bit and 32-bit. If you’re using Office XP you can use the 32-bit drivers. Use of the 16-bit drivers depends on your operating system. Windows NT Workstation supports both 16- and 32-bit drivers; only 32-bit drivers are supported under Windows 95/98 or Windows 2000. If you’re running Windows 95/98 and working with vendors to acquire an ODBC driver, make sure you specify that you require a 32-bit driver. The newest ODBC drivers have their own installation programs. Older drivers, which required setup through the Control Panel, are no longer supported in the version of ODBC that ships with Office XP.
If you’re new to data sources, don’t let the abbreviations and driver discussion intimidate you. The bottom line is this: the majority of databases that you’ll encounter support ODBC or OLEDB. If a database supports either, you can connect to the data, and then use the familiar and powerful tools in Excel to manipulate the data.
Out of the Box with Excel 2002
V
4002c16.qxd 7/18/01 2:57 AM Page 494
494
CHAPTER 16 • Using Excel with Other Databases
Differences between OLE DB and ODBC OLEDB and ODBC are two standards for data sources. You connect to both data sources the same way, but you’ll get different results with ODBC and OLEDB. Here are the key differences between the two standards: Editing OLEDB data sources include their own interface used to edit queries. If you connect to an ODBC data source, you’ll use Microsoft Query to edit your queries. Parameter Queries
ODBC supports parameter queries; OLEDB does not.
Reconnection If an OLEDB data source moves, you can locate the source and reconnect. With ODBC, you need to create a new connection. Save as Office Data Connection OLEDB connections can be programmatically saved as Office Data Connection (ODC) files using VBA; ODBC files cannot.
Using an Existing Data Source Excel handles a number of data types as native data: formats directly understandable by Excel. To retrieve data from a non-native source, you must either convert the data (to static Excel data) or use a “middle man”—an ODBC driver to interpret between Excel and the file created in a different application. A database and, if needed, a driver that can interpret it, are called a data source. Choose Data Import External Data Import Data from the menu to open the Select Data Source dialog box (see Figure 16.9). Select a data source for the data and choose a location for the imported data; if you choose a database, you’re first prompted to select a table from the database.
4002c16.qxd 7/18/01 2:57 AM Page 495
Importing Data
495
You may be prompted to provide more information. For example, if you select the Microsoft Network MoneyCentral Investor Stock Quotes web query, you’ll be prompted to supply a parameter list of stock ticker symbols separated by commas.
FIGURE 16.10 Imported stock information from MoneyCentral.
PART
V Out of the Box with Excel 2002
After you’ve entered symbols, Excel imports the data from the data source, as shown in Figure 16.10. The result is a web query that retrieves data from the Internet, so you must have an Internet connection to import data. You can refresh query data by choosing Data Refresh Data from the menu.
4002c16.qxd 7/18/01 2:57 AM Page 496
496
CHAPTER 16 • Using Excel with Other Databases
NOTE
For information on creating web queries, see Chapter 18, “Using Excel 2002 with the Web.”
Creating a New Data Source Creating a new data source is straightforward, but not particularly easy the first few times. Creating a data source is not the same as creating a database; when you “create” a data source, the data source file already exists, but needs a driver to allow it to communicate with other applications. ODBC and OLEDB data sources are the easiest to create, because you choose server names and file locations from drop-down lists. For databases for which you don’t have ODBC or OLEDB drivers, you must type the names of servers and file locations rather than selecting them from drop-down lists.
NOTE
See “Understanding Data Sources” earlier in this chapter for more information on ODBC and OLEDB.
If you’re not familiar with data files and ODBC/OLEDB drivers in your organization, invest a few minutes with your network administrator to get the information you’ll need: the locations and file types of the data that you need to connect to and where to find OLEDB or ODBC drivers for the file types if your organization has them on hand. Choose Data Import External Data Import Data from the menu to open the Select Data Source dialog box (see Figure 16.9). Click the New Source button or doubleclick Connect to New Data Source to launch the Data Connection Wizard. In the first step of the wizard, select the type of data source you need to create: • SQL Server • SQL Server OLAP (online analytical processing) Services • ODBC DSN (for databases and spreadsheets) • Oracle • Other/Advanced (Outlook and other sources) The next steps depend on the type of data source you selected in the first step. If, for example, you choose Other/Advanced, in step two, you select a specific data type, as shown in Figure 16.11, and connection information.
4002c16.qxd 7/18/01 2:57 AM Page 497
Importing Data
497
FIGURE 16.11 Choose an Other/Advanced data type in the Data Connection Wizard.
PART
If you chose ODBC DSN, select an ODBC data source type in the second step. Then you select the data source: the file of the type you selected that contains the data you want to import. Follow the steps to complete the wizard. In the last step of the Wizard, shown in Figure 16.12, enter a name for the data connection. The default save location for user-defined data sources is the My Data Sources folder in My Documents, but you can select another location. If you wish, enter a description and keywords that can be searched with Office Search. FIGURE 16.12 Enter a name, location, and description for the new data source.
Out of the Box with Excel 2002
V
4002c16.qxd 7/18/01 2:57 AM Page 498
498
CHAPTER 16 • Using Excel with Other Databases
Click Finish to close the Data Connection Wizard and return to the Select Data Source dialog box. Choose the data source and click Open to open the data source. In the Import Data dialog box, specify a worksheet location for the imported data. All the records from the data source are imported when you click OK. Click the Create a PivotTable Report link in the Import Data dialog box to immediately move to the last step of the PivotTable Wizard and create a pivot table with the imported data.
NOTE
See Chapter 13, “Using Excel 2002 to Present Information,” for information on creating PivotTable Reports and PivotCharts.
Retrieving External Data with Microsoft Query Excel 2002’s Import External Data feature will meet most, but not all of your data needs. If you need to preprocess query data, use Microsoft Query. You can use Query, an Add-In included with Office XP, to perform the following tasks: • Sort or filter rows or columns of data before importing • Create parameter queries • Join multiple tables Launch Query from Excel by choosing Data Import External Data New Database Query. If you select an external data source in the PivotTable Report Wizard, Microsoft Query is launched automatically. While you can use Query with other applications, there are several good reasons to work with Query data in Excel, including the number of users who are already familiar with Excel’s features. If you offer to create a Microsoft Query for a colleague, they’ll probably express some degree of gratitude. When you offer to help them access the data they need using Excel, you’ll generate some real excitement.
TIP
You can launch Query without Excel; you’ll find the msqry32.exe program in the folder where the other Office XP applications are installed.
Before you can use Query to import data, you must install Query and make sure the OLEDB driver, ODBC driver, or OLAP data source driver that you need is installed
4002c16.qxd 7/18/01 2:57 AM Page 499
Retrieving External Data with Microsoft Query
499
on your computer. Start the Office XP CD; Microsoft Query is on the list of Office Tools in the Microsoft Office XP Setup dialog box. The following is the sequence you’ll follow to use query results in Excel 2002: : 1. Fire up Microsoft Query. 2. Create a data source or select a source that you or someone else created. 3. Use Query to select data from the data source. 4. Return the Query data to your Excel workbook.
Selecting an External Data Source in Microsoft Query
PART
V Out of the Box with Excel 2002
From an Excel worksheet, choose Data Import External Data New Database Query to launch Microsoft Query. Query will display the Choose Data Source dialog box, shown in Figure 16.13. The Databases tab of the dialog box shows a mixture of existing data sources and drivers you can use to create data sources. The Queries tab has a list of queries you’ve previously created and saved. You’ll find out about OLAP Cubes (the third tab of this dialog box) later in this chapter. FIGURE 16.13 Select a data source for the query.
TIP
There are default folders that Query searches for data sources and queries. To add other folders to the list, click the Options button in the Choose Data Source dialog box.
Microsoft Query isn’t the only program that uses data sources, so if you’ve created data sources to use with programs like Seagate Crystal Reports, Cognos PowerPlay, or Cognos Impromptu, they’ll be listed on the Databases tab. If you’ve already created a data source for the database you want to query, simply select it from the list and click OK.
4002c16.qxd 7/18/01 2:57 AM Page 500
500
CHAPTER 16 • Using Excel with Other Databases
Setting Up a New Data Source To create a new data source, choose New Data Source at the top of the list on the Databases tab and click OK to open the Create New Data Source dialog box, shown in Figure 16.14. In the first text box, enter an easy-to-remember name for your data source; you can use the name of the database. In the second text box, choose the appropriate driver from the list of ODBC drivers, and then click the Connect button to launch the ODBC driver. FIGURE 16.14 Enter a name for the data source and select a driver.
Setting Up Your Database
The ODBC Manager displays the Setup dialog box for the driver you selected. Figure 16.15 shows the ODBC Setup dialog box for Microsoft Access; if you choose a driver for a different type of database, the dialog box you see may request different information to complete the ODBC connection.
FIGURE 16.15 Setting up an Access ODBC data source
4002c16.qxd 7/18/01 2:57 AM Page 501
Retrieving External Data with Microsoft Query
501
Click the Select button to choose an existing database in the Select Database dialog box. (You can click the New button to create a database, but we advise you to spend some time designing it first!) If the database is secured, use the second section of the dialog box to choose the system database that validates your login, and then click the Advanced button and enter your login name and password in the Set Advanced Options dialog box. If there is no security set for the database, leave the default System Database setting of None. (Contact your database administrator if you need more information about these choices.) Click OK to close the Select Database dialog box and return to the Create Data Source dialog box.
Limiting Access to Data Sources When you set up your data source, you can restrict access to it so that you’re the only user or so that only people who have access to your computer can use the data source. Access restrictions depend on the type of data source you create: User DSN (data source name), System DSN, or File DSN. User data sources are specific to the current user and are available only on the machine where they’re created. Create a user data source when you’re the only person who needs to use the data source. System DSNs are local to the machine but are not user-specific, so they can be shared with other people who use your computer. File DSNs are available to all users whose computers have the ODBC driver used to create the data source, so you can share them with other people in your department or workgroup. Some ODBC drivers only let you set up one or two of the types of data sources. For maximum control when creating data sources, use the ODBC Data Sources (32-bit) application in the Windows Control Panel.
PART
V Out of the Box with Excel 2002
Selecting a Default Table and Login If you’re going to create a number of queries based on the same table in the data source, you may want to set the table as the default table in the Create Data Source dialog box. If a default table is selected, it’s the only table displayed in the Query Wizard, which can really speed up creating queries in a large database with many tables. The check box at the bottom of the Create Data Source dialog box allows you to save your user ID and password as part of the data source so you won’t have to reenter them each time you connect to the data source. Click OK to create the data source. You’ll return to the Choose Data Source dialog box, where you can select the data source. Query includes a wizard that you’ll use to create simple select queries as you would in Access. For more complex queries you’ll use the Microsoft Query window. The Query Wizard is enabled by default. To turn it off, clear the check box at the bottom of the dialog box before you click OK to close the Select Data Source dialog box and open Microsoft Query.
4002c16.qxd 7/18/01 2:57 AM Page 502
502
CHAPTER 16 • Using Excel with Other Databases
Creating Queries with the Query Wizard The Query Wizard opens with a list of the views (database queries), tables, and columns (fields) in your data source. In Figure 16.16, the open data source is the Northwind sample database that is included with Office XP. The left pane works like the Windows Explorer. Tables and views have an expand symbol; click the symbol to display the table’s fields. FIGURE 16.16 Select fields or entire tables to include in your query.
The right pane displays the fields included in your query. Select a view, table, or individual column, and use the pick buttons to move the selection to the right pane. If you need a reminder about the contents of a field, select the field in the left pane, and then click the Preview Now button in the dialog box to display data from the field. You can select data from more than one table or view. When you have finished selecting columns, click the Next button. If you selected columns from more than one table, the Query Wizard will check to see if there are existing relationships between all the tables before proceeding. If any of the tables from which you included columns is not related to the other tables you selected, you’ll be dumped out of the Query Wizard and into Query so you can indicate the appropriate relationships. (If this happens, see the next section, “Defining Relationships in Query.”)
NOTE
The key to working with any data set is understanding the data. If you don’t understand the tables and fields in a database, spend time with someone who does or review the database documentation. If you have difficulty understanding relational databases, we recommend Database Design for Mere Mortals by Michael Hernandez, a guide to database construction that’s software independent. Hernandez is easy to read and easy to comprehend.
4002c16.qxd 7/18/01 2:57 AM Page 503
Retrieving External Data with Microsoft Query
503
In the next step of the Query Wizard, use the drop-down lists and text boxes to specify filter criteria if you want to restrict the results based on values in specific columns. Use the And operator between criteria when all conditions must be met; use Or when any of the conditions should place a record in the query result set. For example, use Or to see Customers in the U.S., Canada, or Mexico, as shown in Figure 16.17. You can add more than three filter criteria; after you’ve set three, a vertical scroll bar appears so you can add more criteria. After the filters have been set, click Next.
NOTE If you aren’t going to filter, sort, or join tables in a query, you should just use Excel’s Import Data feature (Data Import External Data Import Data) discussed earlier in this chapter. It’s easier and faster. PART
V Out of the Box with Excel 2002
FIGURE 16.17 Set one or more filter criteria in the Query Wizard.
In the next step of the Query Wizard, create a sort order. Choose a field to sort by, and select the Ascending or Descending order option. As with filters, a scroll bar appears so you can sort by more than three columns as shown in Figure 16.18. In the final step of the Query Wizard, shown in Figure 16.19, you can save the query as a query file which you can open directly from Excel next time by choosing Data Import External Data Import Data. The query definition is not automatically saved. Save it by clicking the Save Query button. After saving or not saving the query definition, choose one of three ways to work with your data.
4002c16.qxd 7/18/01 2:57 AM Page 504
504
CHAPTER 16 • Using Excel with Other Databases
You can return the data to Excel, work with it in Query, or create an OLAP cube. If you choose to return the data to Excel, you can use all the Excel tools you’re familiar with to work with the data. After choosing an option, click OK to close the wizard. FIGURE 16.18 Choose columns to establish a sort order.
FIGURE 16.19 Choose a destination for your result set in the final step of the Query Wizard.
4002c16.qxd 7/18/01 2:57 AM Page 505
Retrieving External Data with Microsoft Query
505
If you return the data to Excel, you’ll be prompted to select a location for the data.
To edit a query, choose Data Import External Data Edit Query from the menu to open the Query Wizard. The filter page is a bit tricky. Columns that are already used in a filter are bold, but the filter isn’t displayed automatically. To see the current filter, click the bold column name in the left pane. Change filtering or sorting criteria, then click Finish to return to Microsoft Excel where your query changes are immediately reflected.
Editing a Query
Sometimes Query makes you clean up relationships simply because you didn’t choose fields from enough tables. In the data set shown in Figure 16.20, we selected fields from Employees and Categories because we wanted to determine the total value of each employee’s sales in each category. The problem is, there isn’t a related field that appears in both the Employees and Categories tables, and Query lets us know about it.
Employees take orders, which have details about products, and products fall into categories. We need related fields from the Orders, Order Details, and Products tables to create the query, so when we click OK to close the message box, the Query Wizard closes and dumps the partially created query in the Query Window, shown in Figure 16.20.
V Out of the Box with Excel 2002
Defining Relationships in Query
PART
4002c16.qxd 7/18/01 2:57 AM Page 506
506
CHAPTER 16 • Using Excel with Other Databases
TIP In a well-built database, the fast way to find a relationship between tables is to see if the primary key of either table appears as a non-key field (called a foreign key) in the other table.
FIGURE 16.20 You know at a glance that the tables in the Query Window aren’t related because there’s no line connecting the two tables.
Don’t assume anything just because there’s data in the Query Window grid. The data is the result of a cross join (also called a full outer join), which returns every record in one table for each and every record in the other table: data in abundance, but generally not what you want. To get the data we need, we must relate the tables.
4002c16.qxd 7/18/01 2:57 AM Page 507
Retrieving External Data with Microsoft Query
507
To add another table to the grid, click the Add Tables button to open the Add Tables dialog box, select a table, and then click Add to add the table. Click Close when you’re finished adding tables.
PART
V Out of the Box with Excel 2002
When the tables you selected are all related, you’ll be able to follow the join lines from the first table to the last, as shown in Figure 16.21. FIGURE 16.21 Join lines connect related tables in a query.
How does Query do this? It joins fields with the same name, which means that the joins it creates may not be correct, particularly if the person who designed the database wasn’t consistent when naming fields. To delete a join, select it and press the Delete key on your keyboard. To create a new join, drag the field from one table and drop it on the field that represents the same data in the other table.
4002c16.qxd 7/18/01 2:57 AM Page 508
508
CHAPTER 16 • Using Excel with Other Databases
To edit a join, select it and double-click to open the Joins dialog box shown in Figure 16.22. Choose the join that best describes the data you would like to see in your query results. When you’ve finished adding tables and editing joins, choose File Return Data to Microsoft Excel to work with your imported data. FIGURE 16.22 Use the Joins dialog box to select data from related tables.
Working with Query Results in Excel In Excel, you can use the query result set as you would any native Excel data. You can, for example, add formulas, create totals or averages, and chart the information. The real charm of both Import and Query, however, is their ability to refresh data from the data source on demand. When the query results open in Excel, the External Data toolbar also opens.
NOTE
If the toolbar does not open, right-click any toolbar and choose External Data to display the toolbar.
4002c16.qxd 7/18/01 2:57 AM Page 509
Retrieving External Data with Microsoft Query
509
To view the latest data from a data source, click the Refresh Data button, and Query will rerun your query. The Refresh All button reruns all queries in the current workbook. If your queries are complex and take a long time to run or if you have a number of queries, you’ll appreciate being able to cancel a refresh or get refresh information at the click of a button. If you want to change the query design, click the Edit Query button to launch Microsoft Query and reopen the Query Wizard so you can add or delete tables and columns, or change filters or sort order.
TIP
If you rearrange the columns or change the sort order or filter criteria in Excel, Query uses the new layout when it refreshes the data. See “Setting Excel Data Range Properties” later in this chapter for information on retaining or discarding layout changes. PART
Creating Parameter Queries You can create a parameter query in Query as you would in Access. In the final step of the Query Wizard, choose the View Data or Edit Query in Microsoft Query option, and the Query window will open. (To add criteria to an existing query, edit the query.) If the Criteria grid is not displayed, choose View Criteria to display it. In the Criteria Field dropdown list, select the field for which you want to set a parameter. For example, to create a parameter query where users enter a country name (for example, Canada, Mexico) used in the query, choose the country field (for example, Country) as the criteria field. In the Value row just below the Criteria Field, enter a user prompt in brackets: [Enter a country name:].
Out of the Box with Excel 2002
V
4002c16.qxd 7/18/01 2:57 AM Page 510
510
CHAPTER 16 • Using Excel with Other Databases
Query will immediately create the message box with the user prompt. Tab out of the Value field to see it.
Enter additional Or criteria in the remaining rows. For example, to allow a user to return data from two departments, enter a prompt for the first department ([Enter the code for the first department], for example) on the Value line, and a similar prompt ([Enter the code for the second department]) on the Or line directly below. To create an And criteria, choose a Criteria Field and set criteria in the next column. For example, you can prompt twice, once for a Beginning Date and again for an Ending Date, then return all the records between the two. To return to Excel when you’re finished, choose File Return Data to Microsoft Excel from the Query menu. Creating a parameter query is particularly helpful when users need to change criteria frequently. In Excel, click the Query Parameters button on the External Data toolbar. This opens the Parameters dialog box, where you can change the source for a parameter to a cell in the workbook (or a fixed value). Choose the Get a Value from the Following Cell option to let users enter a value in, for example, cell C2. Click the Refresh Data button, and see the query results for the new value they entered.
4002c16.qxd 7/18/01 2:57 AM Page 511
Retrieving External Data with Microsoft Query
511
Setting Excel Data Range Properties One of the disadvantages of working with Query data in Excel is that users can forget to refresh the data and copy formulas in adjacent columns when more records are returned in the query results. Automated refresh settings are just one of the properties you can set for the range of data returned by Query. Begin by clicking the Data Range Properties button on the External Data toolbar to open the External Data Range Properties dialog box shown in Figure 16.23. These properties don’t affect the query that you saved (or didn’t save) in Microsoft Query. They determine how the query behaves in Excel: Name
The Excel name for the data range.
Save Query Definition On by default, saves the definition as part of the Excel worksheet so that it can be refreshed later without choosing Tools Get External Data and retrieving the saved query. PART
Saves the password you entered to open the query data source.
Enable Background Refresh Allows you to work on other tasks in Excel while data is being refreshed. If you disable this check box, you must wait for Query to refresh the data before continuing. Refresh Every X Minutes Ensures that the data range is refreshed at the interval you specify. Be careful with this, particularly when a query result set can grow or is accessed over a network with high peak volumes. You can become incredibly unpopular with colleagues who use this workbook if you refresh every 30 minutes and it takes 15 minutes for Query to refresh the data range. Refresh Data on File Open Launches Query and refreshes the data each time the workbook is opened rather than waiting for X minutes to refresh. This is a good option when data changes less frequently than users open the workbook. Many corporate data stores are refreshed once a day or once a week during off-peak hours, so a refresh when the file opens is probably adequate. With Refresh Data on File Open selected, you can choose the Remove External Data From Worksheet Before Saving option. When the file is saved and closed, the external data is dumped, which saves drive space. The next time the workbook is opened, the query is run again and the data refreshed. There are two types of Data Formatting and Layout options. The first two options on the left pertain to the external data source; the options in the right column relate to Excel. You can include field names or omit them if you want to create different column labels and include row numbers from the external data source.
V Out of the Box with Excel 2002
Save Password
4002c16.qxd 7/18/01 2:57 AM Page 512
512
CHAPTER 16 • Using Excel with Other Databases
FIGURE 16.23 Use the External Data Range Properties dialog box to set the refresh information for the query data.
When data is refreshed, Excel automatically adjusts column widths to fit the data unless you turn the third option off. Preserve Column/Sort/Filter/Layout and Preserve Cell Formatting are both enabled by default. With the default settings, if you rearrange columns in Excel and then apply a format to a column of query results, both the new arrangement and the format will be retained when the data is refreshed. The last time you ran your query, it returned 10 rows of data; if it returns 13 rows next time, how should Excel deal with the extra rows? Use the option buttons to choose the method you want Excel to use (cell replacement, row replacement, or both) when the number of rows changes on refresh. If you have other worksheet columns with formulas that rely on the external data range, enable the Fill Down Formulas in Columns Adjacent to Data check box to have Excel copy the formulas down to extra rows or remove formulas from rows that no longer have external data. When you’ve adjusted the properties to meet the needs of the workbook’s users, click OK to save the properties and close the dialog box.
3D Pivot Analysis with OLAP OLAP (Online Analytical Processing) is a natural extension of traditional Excel pivot tables. Pivot tables analyze data in two dimensions. For example, you can create a pivot table to analyze your company’s sales by area, by date, or by product. If you create a pivot table to summarize dates by quarter and sales by region, you can drill
4002c16.qxd 7/18/01 2:58 AM Page 513
3D Pivot Analysis with OLAP
513
down and view sales for a month or a particular day or you can look at sales for the states within a region. Until Excel 2000, the pivot table toolkit had a serious limitation: you couldn’t adequately analyze three or more dimensions (sales by region and date and product) simultaneously. OLAP is a three-dimensional data analysis tool for analyzing the multidimensional data that abounds in corporate databases.
NOTE
OLAP uses PivotTable Reports, Microsoft Query, and ODBC. Refer to Chapter 13, “Using Excel 2002 to Present Information,” for information on pivot tables; refer to the “Creating a New Data Source” and “Retrieving External Data with Microsoft Query” sections earlier in this chapter for help with ODBC and Microsoft Query.
An OLAP cube is a special type of query with data organized in the categories you use for analysis so you can quickly generate new analyses or reports based on the data. You create OLAP cubes from any ODBC data source with Microsoft Query, or you can attach to an existing data cube created by one of your coworkers or an OLAP provider. If cubes are well designed, you won’t need an abundance of them. One cube containing data on, for example, sales, can replace a plethora of queries and pivot tables created about specific aspects of sales information. An OLAP cube is organized in dimensions, and a given dimension may have two or more levels of information, ranging from the more inclusive and general to the more specific and detailed. In a PivotTable Report or PivotChart, a dimension is placed in a row, column, or page area. For example, a cube of data about sales might have these dimensions and corresponding levels: Sales dates
Years, quarters, months or weeks, days.
Geography
Country, state/province, city.
Products
Product category, product.
The lowest level of this cube, called a measure, would be the detail about sales: the quantity of each product sold. The measures are placed in the data area of a pivot report. People who use your cube will analyze data by expanding and collapsing dimensions and swapping dimensions to see the changes in the measures.
TIP
Dimensions are the Row, Column, and Page areas in a traditional pivot table. Measures are the fields used in the Data area and are summarized as they are in pivot tables.
PART
V Out of the Box with Excel 2002
Understanding OLAP Cubes
4002c16.qxd 7/18/01 2:58 AM Page 514
514
CHAPTER 16 • Using Excel with Other Databases
If you serve as an information technology person in your company or department (formally or informally), you’ll quickly realize that OLAP is a powerful feature. Rather than spending your time creating specific reports, you can create cubes to help your users analyze data, even if they know nothing about joins or queries. If you’re an end user, you’ll appreciate the power to robustly analyze and report on your data without asking for assistance.
Opening an Existing OLAP Cube There are three ways to access an existing OLAP cube. If the cube was already used in an Excel PivotTable or PivotChart, just open the Excel workbook. The workbook includes the information required to launch Microsoft Query and connect to the OLAP data source.
Using an Existing OLAP Query If the OLAP cube was saved in Microsoft Query but not in Excel, choose Data Import External Data Import Data and set the Files of Type to OLAP Queries/Cubes. Select the OLAP query. Excel will run the query and prompt you to choose a location for a pivot table.
Selecting an Existing OLAP Data Source If there is no query based on the OLAP cube but a data source using the cube exists, select the data source as you would for any query based on an external data source. Open Excel and choose PivotTable Chart/PivotTable Report from the Data menu. In the first step of the wizard, choose External Data Source. In the second step, click Get Data to open the Choose Data Source dialog box. Click the OLAP Cubes tab and select an OLAP data source; then click OK to connect to the data source and return to the PivotTable Wizard.
Creating a New OLAP Data Source If you need to create a new data source using a cube or OLAP server, begin by choosing the External Data Source option in step 1 of the PivotTable and PivotChart Wizard. Then click Next to move to step 2 and click Get Data. On the OLAP Cubes tab of the Choose Data Source dialog box, choose New Data Source and click OK to open the Create New Data Source dialog box, shown in Figure 16.24.
4002c16.qxd 7/18/01 2:58 AM Page 515
3D Pivot Analysis with OLAP
515
FIGURE 16.24 Create a new data source to connect to a cube or server.
PART
V Out of the Box with Excel 2002
Enter a name for the data source. Select OLE DB Provider for OLAP Services 8.0, which is included with Office XP, as the provider. Click the Connect button to open the Multidimensional Connection dialog box, shown in Figure 16.25. FIGURE 16.25 Choose a server or cube file.
If you’re connecting to an Analysis server, enter the OLAP server resource name provided by your system administrator or database administrator in the text box. To connect to a cube, choose the OLAP Cube option, and then enter the Cube file name or browse and select it.
4002c16.qxd 7/18/01 2:58 AM Page 516
516
CHAPTER 16 • Using Excel with Other Databases
NOTE
If you don’t have a cube or an analysis server, see the next section: “Creating a New OLAP Cube.”
Click Finish to connect to your server or cube and return to the Create New Data Source dialog box. Click OK to create the data source and add it to the list in the Choose Data Source dialog box. Click OK to return to the PivotTable Wizard.
TIP There are two ways that OLAP data is delivered to a desktop: from a relational database using Microsoft Query and ODBC or from an OLAP database. With an OLAP database, summary calculations are performed on the Analysis server and then sent over the network to Excel. Server-based queries run much more quickly than those based on relational databases that require Excel to receive all the detail data and then perform summary calculations on your workstation. Analysis servers allow users to analyze data sets that have too many records for Excel to manage. On the other hand, OLAP cubes created with relational databases give you a way to look at complex data even if your company doesn’t have an OLAP server. You can create the cube to filter the records returned from a database, allowing Excel to handle a larger number of records (without running out of system resources) than it would be able to if all fields were being retrieved by Excel.
Creating a New OLAP Cube If you can connect to an ODBC relational data source, you can create OLAP cubes by setting up a data source, creating a query based on the data source, and saving the query as an OLAP query. From Excel, choose Data Import External Data New Database Query. If necessary, create and then select a Database data source as discussed earlier in this chapter. In the illustrations that follow, we’re creating a cube using the Northwind database included with Office XP, the same database we used with Microsoft Query earlier in this chapter.
TIP This is a multistep process, but there are many places along the line where you can save your progress: in Microsoft Query, the OLAP query, or the completed OLAP cube. Queries take up little room, so don’t hesitate to save whenever you have a reusable definition. In the Query Wizard, choose the tables and fields that you need for your cube. Choose carefully: you can’t edit a cube, so if you omit a field, you have to create a
4002c16.qxd 7/18/01 2:58 AM Page 517
3D Pivot Analysis with OLAP
517
new cube. Choose liberally: you don’t need to use all the fields that you select. Select tables and fields that represent the levels, dimensions, and measures you’ll want to analyze in the cube. In the last step of the Query Wizard, select Create an OLAP Cube from This Query. If you think you may want to create a similar cube later with slightly different fields, click the Save Query button. Click Finish to launch the OLAP Cube Wizard.
TIP You’ll choose the measures that you want to summarize when you create the cube. If you want to summarize a field twice—for example, to count and total the values in the field—you need to add the field to the query twice. You can’t select a field more than once in the Query Wizard, but you can in Query itself. In the last step of the Query Wizard, choose View Data and Edit Query in Microsoft Query to return to Query, where you can drag additional fields into the query grid. After you’ve examined the query results, choose File Create OLAP Cube from the Query menu bar to launch the OLAP Query Wizard. PART
V Out of the Box with Excel 2002
The OLAP Cube Wizard opens with an explanatory page. Click Next to move to the first step of the wizard, shown in Figure 16.26. In this step, decide which of the fields you want to use as measures (data fields). The fields you select here will end up in the data area of your PivotTable Report in Excel. The OLAP Cube Wizard examines your data, checks the fields that may be measures, and assigns a summarization method: COUNT for text and primary key fields and SUM for other numeric fields. You need to select at least one data field and have at least one field that is not a data field when you’re finished selecting. The fields that you don’t select can be used in the next step as dimensions/levels. Of the fields selected by the wizard in Figure 16.26, we’ll keep two: OrderID and Quantity. To change the summarization method for a field, click in the Summarize By column and select the function (Sum, Count, Min, Max) you want to use. Edit the Data Field Name to change the display name for a field. For example, in the cube shown in Figure 16.26, you might choose to change the name Count of Order ID to Number of Orders or even simply Orders. You can also change field display names later in Excel; shortening the names creates easier-to-use field names in the task pane. Click Next to move to the second step, selecting dimensions and levels. The wizard does not select dimensions for you; instead, you begin with a blank screen. In your PivotTable Report, dimensions will be placed in the row, column, and page areas. Select the highest level in any dimension in the left pane, and drag and drop it on Drop Fields Here to Create a Dimension in the right pane to create a dimension, as shown in Figure 16.27. Add more dimensions the same way.
4002c16.qxd 7/18/01 2:58 AM Page 518
518
CHAPTER 16 • Using Excel with Other Databases
FIGURE 16.26 Select fields to be summarized in the OLAP Cube Wizard.
FIGURE 16.27 Select dimensions in the second step of the wizard.
4002c16.qxd 7/18/01 2:58 AM Page 519
3D Pivot Analysis with OLAP
519
Date fields create their own levels—years, quarters, months, weeks, and days—that you can choose to include or omit. (You can’t select both months and weeks to include, because weeks cross months.) For other dimensions, you’ll need to create your own levels. For example, to create a Products level within the Categories dimension, drop the Products field directly on Categories to create another level within Categories (see Figure 16.27). Similarly, drop Region on Country and City on Region to create a geographical dimension.
TIP To edit a level or dimension name, right-click and choose Rename from the shortcut menu. You can also remove, cut, and paste dimensions. When you remove a field or dimension, it moves to the bottom of the list in the left pane. You cannot copy a dimension.
FIGURE 16.28 Choose a save method for the cube.
PART
V Out of the Box with Excel 2002
The third step of the wizard, shown in Figure 16.28, offers three ways to save your OLAP cube. The correct choice depends on several factors: the system resources available to the people who use the cube, the amount of data the cube will contain, and how frequently users change pivot reports. If a cube will see heavy-duty use, you may want to create three identical cubes, saved three different ways, and test the response of each to determine which choice is best.
4002c16.qxd 7/18/01 2:58 AM Page 520
520
CHAPTER 16 • Using Excel with Other Databases
The first option stores the information required to generate the cube in your OLAP Query (and PivotTable Report in Excel). When you open the query, the cube is created and populated with the data for the fields currently used in the pivot table. Additional data is retrieved on demand. The limited initial data means that this is a good choice when users frequently look at the PivotTable Report based on this cube but don’t change the report very often. The second option stores the cube information the same way, but when the cube is opened in Query or Excel, all the data that might be required by the PivotTable is downloaded at once. This is a better choice when users often change the layout of the PivotTable, but it will, of course, take longer to load initially and it requires more memory than the first option. The third option creates a separate cube file (with a .cub extension) that includes all the data for the cube. If you’ve got disk space and memory in quantity and need to rearrange your PivotTables a lot, this is a great choice. It takes longer to save this file the first time, but it will open more quickly than the first or second options, because Query doesn’t have to recreate the cube.
EXPERT TIP
Use the third option to create an offline cube so you can work with the cube even when you can’t connect to the database it was created from. Refresh the data when you reconnect.
Select an option and click Finish. Immediately, Query opens a Save As dialog box to prompt you to save a cube definition (.oqy) file. This file is separate from the cube file or cube creation instructions you selected in the wizard. You can’t edit the cube directly, but you can create new cubes from the cube definition file. Open the cube definition file in Query and launch the OLAP Cube Wizard again to create a new cube. The.oqy file is added to the Queries tab of the Choose Data Source dialog box, so you can use it as you would any other query in Excel. Save the.oqy file, and Query will begin creating the OLAP cube. You are prompted to return the cube to Excel and begin analyzing your data. When you choose Yes, Excel prompts you for a location for the data table.
Working with a Cube in Excel In Excel, the OLAP cube dimensions and measures appear on the PivotTable task pane. It’s worth noticing a field’s icon; if the field is a summarized field, the icon has numbers. Dimensions have a lined icon. You can’t place dimensions in the data area or measures in the page, row, or columns areas of the table. Each dimension’s field
4002c16.qxd 7/18/01 2:58 AM Page 521
3D Pivot Analysis with OLAP
521
button includes all the levels you chose or added for the dimension, so dragging the OrderDate dimension into the PivotTable row area as shown in Figure 16.29 or the PivotChart x-axis brings along the years, quarters, and so on.
FIGURE 16.29 Drag dimensions into the page, column, and row areas and measures into the data area.
PART
Out of the Box with Excel 2002
V
Digging into Dimensions Dimensions are what separate a cube from a traditional pivot table. There are three ways to display more data in a dimension: drilling down a dimension, using the Show Detail and Hide Detail buttons on the PivotTable toolbar, or selecting from a tree view of the dimension. Drill down by double-clicking the level in which you want to see more detail. In Figure 16.30, for example, you could double-click 1996 to see the four quarters; double-clicking one of the quarters would expand the months or weeks.
4002c16.qxd 7/18/01 2:58 AM Page 522
522
CHAPTER 16 • Using Excel with Other Databases
FIGURE 16.30 Double-click on a dimension to see more detail.
Instead of double-clicking each entry to expand an entire dimension, use the Show Detail and Hide Detail buttons. Select the row or column button and click the Show Detail button on the Pivot Table toolbar to expand every entry one level. Click again to expand the detail by two levels. You can show or hide a selected item as well as an entire row or column. To expand, collapse, or filter a dimension, click the drop-down arrow on the dimension button to open a tree view of the dimension. Use the plus and minus icons to expand and collapse the display, and use the check boxes to show or hide levels and items in a level. Click once on a checked box to add a double check mark, which displays the data in that level and the next level of detail. Save your Excel workbook to save the information required to connect to the query and cube. The next time you need to work with this cube you can simply open the workbook and Excel will connect to the cube file.
4002c17.qxd 7/18/01 3:00 AM Page 523
CHAPTER
17
IMPORTING AND EXPORTING WITH EXCEL 2002 F E ATU R I NG
Converting workbook files to other Office formats
Linking and embedding objects
Working with embedded objects
Creating new objects
Importing data from non-Office applications
Parsing imported text with the Text Import Wizard
Using refreshable text importing
4002c17.qxd 7/18/01 3:00 AM Page 524
f you have Excel 2002, you probably use the entire Office XP suite. If you’re not, you should be. Excel is one member of a family of applications designed to work together so you can work efficiently. By switching between the Office XP tools, you maximize their effectiveness and save yourself a lot of work. If you find yourself recreating data or objects in Word that you’ve already created in Excel, or vice versa, you’re working way too hard. This chapter features a variety of ways to use Excel as part of the Office suite, including embedding, linking, and converting. We’ll also explore Excel’s tools for importing and exporting spreadsheet and text documents.
i
Converting, Linking, and Embedding Object Linking and Embedding, or OLE (pronounced o-lay), is a Windows protocol that allows applications to communicate with each other to create or update objects, data that can be embedded or linked in another application. Excel worksheets and charts, Word documents, Access tables, and PowerPoint slides are all examples of objects you can insert (embed or link). For example, if you need to use an Excel chart in a Publisher or Word document or a PowerPoint presentation, don’t recreate it—reuse it. You can also insert graphics, sounds, video, and virtually anything else you can select and copy to the Clipboard. OLE requires two applications to complete its mission: • An OLE server is a source application that can create an OLE object. For example, Excel is an OLE server because it can create a chart object. • An OLE client is a destination application that can accept OLE objects. PowerPoint is an OLE client because it can accept an Excel chart object. When you use OLE, you have three choices for how you access the external data. You can convert it, link it, or embed it. Each technique has advantages and disadvantages and depends largely on what you need to accomplish. Table 17.1 compares the three options. The following sections discuss each option in detail.
4002c17.qxd 7/18/01 3:00 AM Page 525
Converting, Linking, and Embedding
Converting, Linking, and Embedding Objects
Option
Result
Tools Available from OLE Server
Original File Location
Best Use
Converting
Pastes object into destination document in a format supported by the destination application; e.g., an Excel worksheet becomes a Word table.
None.
Irrelevant; converted object is a copy.
When the source application will be unavailable or when you want to use the destination application’s tools to format the object.
Linking
Maintains active link to OLE server. Changes can only be made in the source application and are reflected in the linked object.
All source application tools are available; double-clicking the object launches the OLE server.
Source file must be maintained in original location or the link is broken.
When the linked object should always reflect the most current data or to minimize size of the destination document.
All source application tools are available; double-clicking the object makes OLE server application tools available within the client application.
Irrelevant; object is a copy.
When you want to be able to edit the object with the tools used to create it, and either you won’t have access to the original file or you want to capture data at a specific point in time.
Embedding Object is copied to destination document and retains attributes from the OLE server application.
Converting Data When you convert a selection, it is translated from its native format (the format used by the application it was created in) to a format that can be used directly by the application in which you place the selection. Converting creates a copy, much like a snapshot. After the selection is converted, you use the tools in the destination application to work with it. You can change the converted data without affecting the original. The easiest way to convert—and embed or link—data in Excel 2002 and the other Office XP applications is to copy and paste. Open the source application that contains the text, picture, or other object you want to place in the destination application. Select the object and copy it to the Clipboard. In Figure 17.1, we’ve selected and copied a data range that we’ll use in the examples that follow. After you copy the data, you can close the source application. You may be prompted to retain the contents of the Clipboard (choose Yes!).
PART
V Out of the Box with Excel 2002
TABLE 17.1
525
4002c17.qxd 7/18/01 3:00 AM Page 526
526
CHAPTER 17 • Importing and Exporting with Excel 2002
FIGURE 17.1 In Excel, copy the data you want to use in another Office XP application.
Open the destination application and document and place the insertion point where you want to paste the selection. To convert the data, simply paste it into the document. In Figure 17.2, the data from Excel has been pasted into Word, which converted the Excel data into a Word table, converting all formulas to values as part of the conversion. You can use all the tools you normally use in Word tables to manipulate the converted table. None of the changes you make to the table, such as adding or deleting rows and columns, affect the Excel database. FIGURE 17.2 Simply pasting the Excel data into Word converts it to a table.
4002c17.qxd 7/18/01 3:00 AM Page 527
Converting, Linking, and Embedding
527
You can use all the tools you normally use in Word tables to manipulate the converted table. None of the changes you make to the table, such as adding or deleting rows and columns, affect the Excel database.
Choosing Paste Options The smart tags that you’ve seen in Excel are used in Word, too. Smart tags add flexibility to OLE because you can choose to reformat the converted object based on the formatting of the destination document or to link rather than convert the object. As soon as you paste an object, the Paste Options button appears in the bottom-right corner of the object. Click the down arrow to open the Paste Options menu, shown here and in Figure 17.2.
PART
The first option, Keep Source Formatting, retains the formatting of the original object—the formatting used in the Excel worksheet. Match Destination Table Style changes the formatting to the default formatting of the document. Keep Text Only removes all formatting and displays only text. We will cover the other paste options later in this chapter.
NOTE
To create a link to the worksheet data, choose either of the Link to Excel options from the Paste Options menu. Information on linking appears later in this section.
Other Conversion Options Converting the Excel data to a Word table is only one of several conversion possibilities. You can, for example, paste it as a graphic in Word and use Word’s drawing tools to position the graphic. Since the data you just copied is still on the Clipboard, you can see further conversion choices simply by choosing Edit Paste Special (in Word) to open the Paste Special dialog box, shown in Figure 17.3.
Out of the Box with Excel 2002
V
4002c17.qxd 7/18/01 3:00 AM Page 528
528
CHAPTER 17 • Importing and Exporting with Excel 2002
FIGURE 17.3 Use the Paste Special dialog box to convert, embed, or link.
The source for the object (the name and range of worksheet cells) is displayed at the top of the dialog box. In the list in the As box, select how the information should be pasted. For native Excel worksheet data pasted into Word, the choices include the following: Microsoft Excel Worksheet Object ded (see the next section). Formatted Text (RTF) Unformatted Text
Creates an object that can be linked or embed-
Converts the worksheet to a Word table.
Converts the selection to Word tabular columns.
Picture and Bitmap Convert the worksheet selection into a graphic that you can work with in Word using all the Word graphic tools. The Picture option creates a higher-quality graphic than Bitmap. Picture (Enhanced Metafile) Converts the selection into a Windows Metafile graphic like those found in Clip Organizer. HTML Format
Converts the Excel table to an HTML table.
Unformatted Unicode Text code text columns.
NOTE
Converts the entries in the cells to unformatted Uni-
Unicode is a standard for encoding characters that includes all the characters in the world’s major languages.
4002c17.qxd 7/18/01 3:00 AM Page 529
Converting, Linking, and Embedding
529
Of the choices listed, all but the first, Microsoft Excel Worksheet Object, convert the object into some other type of object. Choose a format and click OK to convert the selection and paste it into your document.
Embedding and Linking
NOTE
If you link to an Excel workbook that contains macros, the Excel macro security warning will appear when you open the linked file in the destination application.
Embedding an Object To embed an object, you must use the Paste Special dialog box. First, select and copy the object in its native application. In the destination application, choose Edit Paste Special to open the Paste Special dialog box, shown earlier in Figure 17.3. From the As list, choose the description that includes the word “object” (for example, Microsoft Excel Worksheet Object) and click OK. Figure 17.4 shows the Excel object embedded in the Word document. You can tell it’s an object because it has handles when selected. If you double-click the object to edit it, the Excel toolbars are displayed in the destination application window, as shown in Figure 17.4.
PART
V Out of the Box with Excel 2002
When you embed an object, a copy of the object that retains its native format is placed in the destination document. The Excel object is still “in” Excel, but it appears in the Word document. If you change the object pasted in Word, the original selection in Excel remains unchanged. With a link, a relationship is established between the selection in the native application and the pasted entry in the destination document. When you open the Word document, Word reloads the Excel selection directly from the worksheet. When you begin to edit the object, Word launches Excel, and you make your changes there. This ensures that the original data and the linked copy are synchronized; changes to the original data are reflected in the linked object. Linking has two advantages: it saves disk space and, more important, it is dynamic. If the source for the object changes, the change is reflected in all linked objects. This makes linking ideal if you’re working on a project in more than one application—for example, working on the Excel workbook and charts while you’re creating the PowerPoint presentation or Word report that uses the charts. When you’re finished working in Excel, the presentation and report will reflect your completed workbook.
4002c17.qxd 7/18/01 3:00 AM Page 530
530
CHAPTER 17 • Importing and Exporting with Excel 2002
FIGURE 17.4 Choosing Microsoft Excel Worksheet Object embeds the data and makes Excel’s tools available in the Word document for editing the object.
Use embedding when you want to be able to work with an Excel table or chart in Word using the Excel tools. For example, you might want to include an Excel spreadsheet in a PowerPoint presentation. If you simply copy and paste, all the formulas are converted to values. However, if you insert the worksheet as a Microsoft Excel object, it looks the same, but you can make changes to the values and be confident that the formulas will recalculate.
Creating a Link To link the selection rather than embed it, use Paste Special and enable the Paste Link check box in the Paste Special dialog box (Figure 17.3). You can link any of the converted or embedded file types listed. For example, if you copy an Excel worksheet range and choose Paste Link to link it into a Word file with the Microsoft Excel Worksheet Object option, you create a dynamic link to the range in the original worksheet. Any changes you make to the worksheet are reflected in the Word document. If you would like to create a hyperlink to another document, choose Edit Paste as Hyperlink. The text in the pasted object is formatted as a hyperlink. When you
4002c17.qxd 7/18/01 3:00 AM Page 531
Converting, Linking, and Embedding
531
click the hyperlink, Word launches Excel so you can work with the document in its native application. This is useful when you are creating a document that will be viewed online, but obviously, it is not much help in a printed document. If you are pasting Excel data into Word, you can also create a link by pasting the object normally and then choosing one of these options from the Paste Options Smart Tag menu: Keep Source Formatting and Link to Excel, or Match Destination Table Style and Link to Excel. With this type of link, the object converts to a Word table, but the data maintains its link to Excel. Changes you make to the Excel worksheet are shared with the table, but double-clicking the table does not open Excel. You can distinguish this type of link because when you click the table, the data appears shaded, as it does in Figure 17.5.
FIGURE 17.5 Use Paste Options to create a link that converts the table to a Word table and still maintains an Excel worksheet link, as this shading indicates.
PART
Out of the Box with Excel 2002
V
Linking and Embedding in Excel Worksheets Linking and embedding work the same way in Excel. If, for example, you want to place a PowerPoint slide in an Excel worksheet, select the slide in PowerPoint, copy, then paste it into the Excel worksheet. The slide will be converted to a picture—a very
4002c17.qxd 7/18/01 3:00 AM Page 532
532
CHAPTER 17 • Importing and Exporting with Excel 2002
large picture. To create a linked PowerPoint object or a hyperlink, choose Paste Special rather than Paste and select the appropriate options in the Paste Special dialog box.
Working with Embedded and Linked Objects To select a linked or embedded object, click it. Use the object’s handles to size it or press Delete to delete it. The real magic of OLE occurs when you double-click the object. After you double-click, wait a moment. If the object is embedded, the toolbars from the object’s native application are displayed in the destination application. With a linked object, double-click and you are transported to the source document to edit the object.
TIP
Sometimes when you double-click an object, you see a message that the source application cannot be opened (especially if the source application is already open). If the source application is installed on your computer, click OK to close the message box, and double-click again.
Automatic and Manual Updating When you create a link with Paste Special, automatic link updating is enabled. The object is updated each time the destination document is opened and each time the source document changes. You can choose to update links manually rather than automatically, giving you control over when a file is updated. This is particularly helpful when the source document is on a server and you don’t want to wait for network traffic to clear. To change to manual link updating, select the linked object and choose Edit Links to open the Links dialog box. As the Update Method, choose Manual. When you are ready to update links in the destination document, open the Links dialog box again and click the Update Now button, or right-click a selected object and choose Update Link from the shortcut menu.
WARNING
If you use manual linking, adopt a consistent method for updating so you don’t pass off last month’s information as the latest data.
Inserting and Linking Entire Files If you want to embed or link an entire file instead of a selection, it is often easier to insert the object or file into the destination document than to use copy and paste. In
4002c17.qxd 7/18/01 3:00 AM Page 533
Converting, Linking, and Embedding
533
Word and Publisher, you can insert Excel files directly from the Insert menu. In other applications, you can insert files by creating objects.
Inserting and Converting Excel Files in Word If you’re like many users, you use Word to pull together reports that include data from a variety of applications, including Excel 2002. Word is designed to let you convert files “on-the-fly” using the Insert command. To convert an Excel workbook, worksheet, or named range and insert it into a Word document, choose Insert File in Word to open the Insert File dialog box. Select All Files in the Files of Type dropdown list, select the Excel workbook, and click Insert. If the appropriate converters are not installed, Word prompts you to install them from the Office CD or other installation point. In the Open Worksheet dialog box, shown in Figure 17.6, choose Entire Workbook or a specific sheet. If you choose a sheet, you can then select a named range. PART
V Out of the Box with Excel 2002
FIGURE 17.6 Choose to convert and insert the entire workbook, a worksheet, or a named range into a Word document.
In Word 2002, you can insert a file and maintain a link to the original Excel workbook. To link to the workbook, click the down arrow on the Insert button in the Insert File dialog box, and choose Insert as Link.
When you create a link to a file using this method, you must update the link in the Word document manually. You cannot choose to have the link update automatically. If you make changes to the source document, right-click the linked document—the text should appear shaded—and choose Update Field, or choose Links from Word’s Edit menu and click Update Now.
4002c17.qxd 7/18/01 3:00 AM Page 534
534
CHAPTER 17 • Importing and Exporting with Excel 2002
TIP
If you want to insert only part of a selected Excel workbook, click the Range button in the Insert File dialog box and enter the range name before clicking the Insert button.
Embedding and Linking Other Types of Files If you want to insert any type of file in Excel, Word, or Publisher, there is another option: create an OLE object from an existing file. Choose Insert Object Create from File to open the Create from File tab of the Object dialog box, shown in Figure 17.7. FIGURE 17.7 Use the Create from File tab of the Object dialog box to embed or link an entire file.
www
Click Browse to locate the file you want to embed or link, select and open the file, and choose Link to File if you want to maintain a link between the source and destination documents. Choose Display as Icon to insert the object as an icon. Click OK to insert the object in the destination document. Some files are inserted as icons whether or not you choose Display as Icon (for example, media files). Double-click the icon to play the file. To insert or import sound or video files, you must have Windows Media Player installed on your computer. Media Player comes with Windows and can be found on the Programs menu (Start Programs Accessories Entertainment Media Player). You can download the latest version of the Windows Media Player, along with the Windows Media Player Bonus Pack with all kinds of cool add-ins, from www.microsoft.com\windows\windowsmedia.
4002c17.qxd 7/18/01 3:00 AM Page 535
Converting, Linking, and Embedding
535
When Linked Files Are Renamed or Moved Excel 2002 and the other Office XP applications can generally locate a linked file that has been renamed as long as it is still located in the same folder. When you move a linked file, Excel may or may not be able to find the file in its new location. If you move the source file to another folder on the same drive and typically within the same folder branch, a new link is established and everything should work as expected. However, if a linked file is moved to another logical drive or to a different folder branch, Excel, Word, and the other Office applications will no longer be able to find the file. For example, when we opened our Word document after moving the Excel workbook used earlier in this chapter, the following message was displayed: PART
Moving the linked file back to its original location will often repair the broken link. If you move a linked file successfully while the destination file is open, close the destination file, reopen it, and test the link again to make sure Office still knows where to find the linked file. If you prefer to leave the moved file where it is, you can repair the broken link. Just select the object and choose Edit Links. Click the Change Source button and locate the file you want to relink.
Creating New Objects You can use the Object dialog box to create a completely new object. For example, you may want to include an Excel chart in a Word document. You don’t have to open Excel and create the chart; you can create an Excel object directly in Word.
Out of the Box with Excel 2002
V
4002c17.qxd 7/18/01 3:00 AM Page 536
536
CHAPTER 17 • Importing and Exporting with Excel 2002
NOTE
Because new objects exist only in the destination document, they cannot be linked, only embedded.
Choosing Insert Object from the menu bar opens the Object dialog box. The list on the Create New tab, shown in Figure 17.8, displays the objects that can be created using applications installed on your computer. FIGURE 17.8 Create new objects using the Object dialog box.
Select the kind of object you wish to create from the Object Type list and click OK to launch the application used to create the object. The Object Type list on the Create New tab of the Object dialog box is amended as new applications are installed, but applications often remain on the list even if they have been removed from the computer. If you select an application that has been removed, the destination application provides an error message warning that it cannot find the application needed to create the object.
Using Excel in Office XP With Excel 2002 and Office XP, integration isn’t limited to OLE. In Chapter 16, “Using Excel 2002 with Other Databases,” we discussed the Excel features that are tightly integrated with Access. This section highlights other intra-application features of Excel 2002.
4002c17.qxd 7/18/01 3:00 AM Page 537
Using Excel in Office XP
537
Word When you need to create a new data source for a Word merge, Excel is the best application to use. If you or other Word users in your office create merge-data files in Word, just stop. There are lots of things that belong in Word, but data isn’t one of them. Excel’s database tools and text manipulation functions are far more powerful than anything Word can offer, and Word handles Excel data sources with ease.
Word Mail Merge with Excel
PART
V Out of the Box with Excel 2002
“Mergeable” Excel data follows the Excel database rules: use blank rows and columns to delimit the database, not within the database. For ease of use, make sure each column has a unique column heading; if the database worksheet has a title or other extraneous items, select and name the database range. To merge a Word main document with an Excel data source, choose Tools Letters and Mailings Mail Merge Wizard from the Word menu. In the third step of the Wizard, shown in Figure 17.9, choose the Use an Existing List option and click the Browse button. FIGURE 17.9 Choose an existing Excel data source for your Word merge.
With previous versions of Word and Excel, the Excel data source had to either be a named range or in the first worksheet in the workbook. With Word 2002, you don’t
4002c17.qxd 7/18/01 3:00 AM Page 538
538
CHAPTER 17 • Importing and Exporting with Excel 2002
need to rearrange your workbook to use Mail Merge. In the Select Data Source dialog box, select the workbook that contains the data you want to use in the merge and click Open to open the Select Table dialog box.
Select the worksheet or named range that contains the data you want to merge. Use the check box to indicate whether the first row of your data is a header row. Click OK to select the data source and return to the Mail Merge Wizard. Proceed through the rest of the steps as you normally would.
Opening Excel Workbooks in Word In Word 2002, you can open Excel workbooks directly in Word if you have installed the Microsoft Excel Converter. The converter is one of the text converters in the Converters and Filters group (under Office Shared Features) in Office XP Installation. In Word, choose File Open to display the Open dialog box. Change the Files of Type to Microsoft Excel Worksheet, select the file, and click Open to open the Open Worksheet dialog box. Select the workbook, range, or sheet you wish to open, and click OK to open and convert the file. This feature is both a blessing and a curse. If you need Excel data in Word, it’s a blessing. If you save the file and try to reopen it in Excel, you’ll curse. Although Word saves the file with the XLS extension, the file is no longer a valid Excel workbook.
4002c17.qxd 7/18/01 3:00 AM Page 539
Using Excel in Office XP
539
PowerPoint In case you didn’t get the news with Office 2000, PowerPoint supports animation of Excel charts, not just the funky charts created with Microsoft Graph. With animation, a chart can be presented in pieces: one pie slice at a time, or series charts by data point or data series. As folks who regularly present financial data to an audience of thousands, this was our favorite improvement in PowerPoint. Here are the steps to follow from Excel to PowerPoint to the big screen: 1. In Excel, copy the chart. 2. In PowerPoint, switch to Normal view. 3. Select the slide that will include the chart and click Paste to paste the chart, as shown in Figure 17.10.
FIGURE 17.10 Copy the chart in Excel and paste it on the PowerPoint slide.
PART
Out of the Box with Excel 2002
V
4. Use the chart object’s handles to move or size the chart as needed. 5. Choose Slide Show Custom Animation to open the Custom Animation task pane.
4002c17.qxd 7/18/01 3:00 AM Page 540
540
CHAPTER 17 • Importing and Exporting with Excel 2002
6. With the chart selected, click the Add Effect button and choose an Entrance or Emphasis effect from the menu.
7. In the list of animation effects in the task pane, click the down arrow on the chart animation and choose Effect Options.
8. On the Chart Animation tab of the dialog box, choose an option from the Group Chart drop-down list.
4002c17.qxd 7/18/01 3:00 AM Page 541
Using Excel in Office XP
541
TIP Some effects, such as transparency, can only be applied to an entire chart, not individual data series or data points. If As One Object is the only choice in the Group Chart list, choose a different effect. Bar and column charts let you animate by series or by element in a series. Pie charts are single series charts, so you can’t animate them by series.
Outlook Outlook’s Import and Export Wizard recognizes data from a wide variety of other applications and can export data in a number of useable formats.
Importing Outlook Items from Excel
NOTE
We’ve converted files from Quattro 97: we had to save the file in Quattro as a previous version, then open and convert it in Excel. The moral of the story? If Outlook doesn’t support the format of the file you’re importing, take it through Excel 2002.
If you want to import the external data into a separate folder before mixing it with your existing Outlook data, create a new folder in Outlook before starting the Import and Export Wizard. In Excel, name the range you wish to import, then save and close the workbook. In Outlook, choose File Import and Export to open the Import and Export Wizard. Follow these steps to import data: 1. In the first step of the wizard, shown in Figure 17.11, choose Import from Another Program or File, then click the Next button.
PART
V Out of the Box with Excel 2002
The Import and Export Wizard walks you through the steps to import data from a number of contact managers (including ACT!, ECCO, Lotus Organizer, and Sidekick) as well as Microsoft Excel. You can map data to specific Outlook fields, so you don’t need to worry about having all the data you need for a contact, task, or appointment. Using Excel and Outlook, you can import contacts from nearly any application. If, for example, you keep your contacts in a Lotus 1-2-3 spreadsheet, you can open the spreadsheet in Excel and save it as an Excel worksheet. Are your contacts in a table in Word? Copy and paste the table into Excel, which automatically converts the Word table to an Excel format.
4002c17.qxd 7/18/01 3:00 AM Page 542
542
CHAPTER 17 • Importing and Exporting with Excel 2002
FIGURE 17.11 Use the Import and Export Wizard to import contacts from another file format.
2. In the second step of the wizard, choose Microsoft Excel, then click Next.
WARNING
If the Import/Export file converters for Outlook are not installed, you are prompted to install them after second step of the wizard. To continue, you must have access to the Office XP installation files either on CD or on your network.
3. In the third step of the wizard, select the file you want to import. Either enter the path and filename or click the Browse button and select the file in the Open dialog box. 4. Before you click Next, you need to choose one of three options for dealing with duplicates—data you’ve entered in Outlook 2002 that also exists in the file you’re importing. Unless you are importing an Outlook personal folder, you can’t select records to import. The Duplicate options are designed to deal with these three possible scenarios: • If you haven’t entered any data in Outlook or if all the information in the Excel worksheet is more correct than the Outlook information, choose Replace Duplicates with Items Imported. • If you’ve already entered some data into Outlook and kept them up-to-date, you may have correct information in both Outlook and Excel. For example, if you’re importing contact information, Outlook may have Jane Smith’s new e-mail address at work, but her home phone number is only in the
4002c17.qxd 7/18/01 3:00 AM Page 543
Using Excel in Office XP
543
Excel database you want to import. In this case, choose Allow Duplicates To Be Created. All the contacts in the Excel file are added to the existing contacts in Outlook. You’ll have to check the information in both of Jane Smith’s Contact forms, copy either the e-mail address or the home phone number to one of the two forms, and delete the other. • If the information in Outlook is the most recent information for each contact, choose Do Not Import Duplicate Items. If a contact already exists in Outlook, it won’t be imported from the Excel worksheet. Only data that are missing in Outlook will be added. 5. In the next step of the Import and Export Wizard, select the destination folder for the external data. 6. In the next step, choose the worksheet or range that contains the data you wish to import.
FIGURE 17.12 Use the Map Custom Fields dialog box to assign imported fields to Outlook contact fields.
PART
V Out of the Box with Excel 2002
7. Outlook opens the Map Custom Fields dialog box, shown in Figure 17.12. The left pane of the dialog box shows the field names from the Excel worksheet. The right pane of the dialog box shows fields in Outlook, and the name of the imported field that will be used to fill the Outlook field. For example, the Last Name field from the Excel database will be used to fill the Name field in Outlook. Click the plus sign in front of the Name field, and it expands to show the components of the field.
4002c17.qxd 7/18/01 3:00 AM Page 544
544
CHAPTER 17 • Importing and Exporting with Excel 2002
If you’re not familiar with the data shown in the sample record, use the Previous or Next button to move to another record in the import file. To map a field, drag the field name from the left pane, and place it next to the correct Outlook field in the right pane After you’ve made sure all the fields are mapped correctly, click OK to close the Map Custom Fields dialog box. 8. Click Finish to import the data from Excel and create new Outlook items. While Outlook converts the data, a message box appears to show you Outlook’s progress. You can’t cancel the import, but don’t worry, it doesn’t take long. You can import hundreds of rows of Excel data in two or three minutes. When Outlook is finished importing records, the dialog box disappears. Your Excel data is now available for you to use in Outlook.
What If My Fields Don’t Match Outlook’s Fields? When Outlook maps the import file, it looks for field names that are similar to those used in Outlook: Name, Address, Department, and so on. If you can change the field names in Excel, you won’t need to spend as much time mapping custom fields. You don’t need to replace the current names: just insert a couple of rows, type new names in the row immediately above the data, then select the new column labels and data and name the range. When you’re finished importing, delete the inserted rows. Only mapped fields are imported. Combined fields don’t import well. For example, if the import file lists first and last name in a single field, and middle initial in a second field, you’ll need to separate the first and last names into two fields in the import table before you can import the data. Parsing data like this is most easily accomplished using Excel’s Text to Columns feature, regardless of the application used to create the data. (See Chapter 6, “Manipulating Text and Dates,” for more information.) If you have fields you don’t wish to import, click the Clear Map button in the Map Custom Fields dialog box to start with a fresh map in the right pane. You can use the four extra fields for imported data that doesn’t have a corresponding Outlook field. User 1, User 2, User 3, and User 4 appear at the bottom of the list in the right pane of the Map Custom Fields dialog box.
4002c17.qxd 7/18/01 3:00 AM Page 545
Importing Data from Other Applications
545
Exporting Outlook Data to Excel Most Excel users are Office power users, and most Office power users use Outlook to the max. If you have to create a report about your Outlook activities, conduct an analysis of your time, or use a list of contacts in Excel, it makes sense to export the data from Outlook. The Import and Export Wizard works as easily copying data from Outlook to Excel as it does importing Excel data. To export data, follow these steps: 1. Choose File Import and Export. 2. In the first step of the Wizard, choose Export to a File. Click Next. 3. Select Microsoft Excel as the type of file you want to create. Click Next. 4. Choose the Outlook folder you want to export. You can only export one parent or subfolder at a time. Click Next.
6. Enable the Actions list check box, then click Map Custom Fields to make sure that the data is mapped correctly (refer to Importing Outlook Items earlier in this chapter for more about mapping). If the incorrect fields appear in the To column, click Default Map to replicate all the fields in the From column. 7. Click OK to close Map Custom Fields dialog box, and click Finish to export file.
TIP To skip fields in the export, open the Map Custom Fields dialog box and click Clear Map. Drag the fields you want from the From column to the To column. When you export the data only, the fields you mapped will appear in the Excel workbook.
Importing Data from Other Applications Excel works with a wide range of file types, so Excel users often need to import data stored in files created with other programs. It’s easy to import data files from other Microsoft Office applications, but getting the stuff from non-Office programs can be more challenging. Fortunately, Excel readily opens files saved as plain text, and most programs can save files in this format. Formatting doesn’t import well. Be prepared to reformat columns, reapply fonts, and apply other formatting changes that are lost during an import operation.
PART
V Out of the Box with Excel 2002
5. Enter the name of the file you’re creating with the exported data. Click Browse to open a dialog box to help you locate the folder and enter a file name. Click OK to close the dialog box and Next to move to the next step of the wizard.
4002c17.qxd 7/18/01 3:00 AM Page 546
546
CHAPTER 17 • Importing and Exporting with Excel 2002
TIP Excel 2002 supports HTML and XML as native formats, so markup language files open as readily as Excel workbooks. See Chapter 18, “Using Excel 2002 with the Web,” for more information on working with HTML and XML documents in Excel 2002. Here are the steps to open a non-native file (a file created in another application) in Excel: 1. Select File Open. In the Files of Type list box, leave the Files of Type default of All Microsoft Excel Files or select the relevant source file type (for example, XML, Text, or an earlier version of Excel). Locate and select the file, and click Open. 2. If your file opens, begin working with it. If it does not open or looks very garbled in Excel, open it in the original application and save the file as an Excel file or save it as a text file and use the steps in the next section to get it into Excel. In some instances, an attempt to open a file results in a “file not valid” error message. There are two possible reasons for this message: Excel doesn’t support the file type or the type is supported but the converter is not installed. Excel supports a number of file formats, including Lotus 1-2-3 and Quattro Pro. The Lotus 1-2-3 converter is installed by default; the Quattro Pro converter is only installed in a custom installation. If the file type you wish to open isn’t supported by Excel, return to the original application, save the file as a delimited text file, and reopen it in Excel with the Text Import Wizard, described in the next section.
EXPERT TIP
Most files can be imported if you have access to the file’s native application or an application that can convert the document. If you’re familiar with the file formats that each of your applications supports, you’ll often be able to find an application to use as a translation tool to move from one format to another. For example, Excel imports WordPerfect tables poorly. However, with the appropriate converters installed, Word opens WordPerfect documents and appropriately displays WordPerfect tables. And you can copy and paste data directly from Word to Excel. To move data from WordPerfect to Excel, then, either save the WordPerfect document as a Word document or open the WordPerfect document in Word and save it as a Word document. Copy the table, and paste it in the Excel worksheet.
4002c17.qxd 7/18/01 3:00 AM Page 547
Importing Data from Other Applications
547
Parsing Imported Data with the Text Import Wizard When Excel can’t open an imported file directly, you can use the Text Import Wizard to open the file and parse it into an Excel spreadsheet. When you parse a file, Excel examines it, converts text items to appropriate data types, and places the data in rows and columns. In order to be parsed successfully, a text file must already resemble a spreadsheet or table, with each paragraph corresponding to a record or row and with a consistent character, usually a comma or tab, used to mark the column breaks. Here’s how to open a text file, parse its contents, and import it using the Text Import Wizard: 1. Select File Open and select Text Files in the Files of Type list box. 2. Locate and select the file. Click Open. The first step of the Text Import Wizard appears, as shown in Figure 17.13. PART
FIGURE 17.13 In the first step of the wizard, indicate whether the file is delimited or fixed length.
Out of the Box with Excel 2002
V
3. The wizard attempts to determine what type of text file it is opening. Set or verify the data type option: Delimited Text files where data fields are separated by commas, tabs, or another consistent symbol or character. Fixed Width Nondelimited files in which each field is a specific length; space between fields is padded with zeros or spaces.
4002c17.qxd 7/18/01 3:00 AM Page 548
548
CHAPTER 17 • Importing and Exporting with Excel 2002
4. Use the Start Import at Row box to skip titles or blank rows at the beginning of the file. The row you select should contain column headings if the file contains them or the first row of data. 5. If you are importing a Mac or DOS file rather than a file created in a Windows application, select the appropriate operating system from the File Origin dropdown list. Click Next to move to the second step of the wizard. 6. Excel adds the column boundaries (see in Figure 17.14). If the columns aren’t correct, change the symbol used as the delimiter. When you have selected the correct delimiter, each column will contain data from one field. Click Next.
FIGURE 17.14 Check the column boundaries in the second step of the wizard.
TIP This is your only chance to correctly separate the data into fields. If you’ve tried each of the delimiters and the columns are still incorrect, your file may have fixed width fields or consecutive delimiters. Click Back to return to the first step to set the Fixed Width option. Enable the Treat Consecutive Delimiters as One check box in the second step to have Excel disregard consecutive delimiters. 7. In the final step in the Text Import Wizard, shown in Figure 17.15, choose the format for each of the newly defined columns. Select a column and choose the format. (Double check the formats for date columns, which Excel often assumes are Text.) Select the Do Not Import option to skip the selected field. The default format setting is General. The format used in the column appears in
4002c17.qxd 7/18/01 3:00 AM Page 549
Importing Data from Other Applications
549
the header. If you want all of the columns to have the same format, but something other than General, hold Shift and click on each column until all are selected. Choose a format from the options in the Column Data Format area.
TIP
Eurodata alert: click the Advanced button to choose separators if you’re importing data that uses decimal and thousands separators other than the period and comma.
8. Click Finish when the formats have been set.
FIGURE 17.15 Set each column’s format in step 3 of the Text Import Wizard
PART
Out of the Box with Excel 2002
V
TIP You can use Excel’s internal parsing tool to, for example, separate a column of full names into first and last names. To parse a column of data into two columns, first insert a blank column to the right of the existing column. Select the column of data, then choose Data Text to Columns.
Using Refreshable Text Importing If you will be updating the original text file containing the data you plan to import, you can establish a link to this source file so that every time it is changed, those mod-
4002c17.qxd 7/18/01 3:00 AM Page 550
550
CHAPTER 17 • Importing and Exporting with Excel 2002
ifications will appear in the Excel file, too. This process, known as refreshable text importing, uses the Text Import Wizard, too, but accesses it through a different menu command. To implement refreshable text, use these steps: 1. Select the first cell where you will place the imported data. 2. Choose Data Import External Data Import Data from the menu. 3. Select the file and click Open to launch the Text Import Wizard.
NOTE Refresh the data by selecting Data Refresh Data, selecting the appropriate text file in the Import Text File dialog box, and clicking Import. If you only want to import a portion of the text file as refreshable text, construct a query using the Microsoft Query tool, discussed in Chapter 16, “Using Excel 2002 with Other Databases,” where you’ll also find information on Excel’s External Data Range tools.
4002c18.qxd 7/17/01 12:42 PM Page 551
18
CHAPTER
USING EXCEL 2002 WITH THE WEB F E ATU R I NG
Working with Web Folders
Publishing Excel data on the Web
Using AutoRepublish
Opening XML files in Excel
Saving Excel workbooks as XML
Creating web queries
Using the camera
4002c18.qxd 7/17/01 12:42 PM Page 552
very version of Excel since Excel 95 has included some new web functionality, and Excel 2002 is no exception. The web features received a major overhaul for Excel 2002. The ease of use of the web queries feature, for example, is incredible. What were web components in Office 2000 have become web parts in Excel 2002, ready for inclusion in digital dashboards. Like the other Office XP applications, Excel natively supports HTML. If you’re a developer or have been keeping up with Microsoft’s .NET initiative, you won’t be surprised at the native format support for XML as well in Excel 2002. Using Excel’s web tools, you can publish static and interactive spreadsheets, charts, and pivot tables. Interactive Web pages let users add formulas, sort and filter data, analyze data, and edit charts. In this chapter, we’ll show you how to create web queries, save and open XML files, publish workbooks and worksheets as web pages, and add Excel components to make your pages even more valuable.
e
Working with Web Folders One of the goals of the Office development team was to standardize access to remote folders, making it as easy to save and retrieve information from a web server or network server as from a local drive. Their solution is Web Folders—also known as Network Places in Windows 2000 and Millennium—shortcuts to folders on web servers and file transfer protocol (FTP) servers that you use as if they were local folders. You access Web Folders from the Excel Open and Save As dialog boxes just as you access local folders. Whether you want to download or upload to an FTP site or save the web pages created in Excel to a web server, it’s easier if you create a Web Folder.
Creating a Web Folder Shortcut in Windows 2000/Me To create a Web Folder shortcut in Windows 2000 and Windows Me, use the Add a Network Place Wizard. In Excel click the Add Network Place link in the New Workbook task pane. If you already have the Open or Save As dialog box open, choose My Network Places in the Places bar on the left side of the dialog box, then double-click the Add Network Place icon to launch the wizard. In the first step of the wizard, shown in Figure 18.1, choose Create a Shortcut to an Existing Network Place to create a shortcut to an existing folder.
4002c18.qxd 7/17/01 12:42 PM Page 553
Working with Web Folders
553
FIGURE 18.1 Open the Add Network Place Wizard from the Save As or Open dialog boxes.
PART
FIGURE 18.2 Type or browse to locate the web or FTP folder.
V Out of the Box with Excel 2002
In the first step of the Add a Network Place Wizard, choose Create a Shortcut to an Existing Network Place. Click Next. If you know the full URL (Uniform Resource Locator) for the Web Folder, enter it in the Location text box (see Figure 18.2). Or click the Go to Web button to open your browser and check the web for the folder location. Type a friendly name for the Network Place in the Shortcut Name text box. Click Next.
4002c18.qxd 7/17/01 12:42 PM Page 554
554
CHAPTER 18 • Using Excel 2002 with the Web
If you’re using a dial-up connection, you’ll be prompted to connect to the Internet. If the web or FTP folder is secured, you’ll be prompted to enter a username and password:
After the Network Place is created, you’ll return to the Open or Save As dialog box.
Creating a Web Folder Shortcut in Windows 98/NT 4.0 In Excel 2002 or any other Office XP application, follow these steps to create a Web Folder shortcut: 1. Open the Open or Save As dialog box. 2. In the Places bar, choose Web Folders. 3. Double-click the Add Web Folder icon. 4. Choose the Create a Shortcut to an Existing Web Folder option. Click Next. 5. Type the URL of the Web Folder. 6. Enter a friendly name for the Web Folder. Click Finish. If the folder is secured, you’ll be prompted to enter a username and password before you can access the folder.
Saving Files in Web Folders You save workbooks in Web Folders as you would save them in a folder on a local or network drive: an easy way to share workbooks with Excel users who aren’t on your network. You can even create links to workbooks in Web Folders as you would create a link to a workbook on your network. Copy the cells you want to link to in
4002c18.qxd 7/17/01 12:42 PM Page 555
Publishing Excel Documents on the Web
555
the workbook in the Web Folder, then choose Edit Paste Special and click the Paste Link button. To create the link without copying and pasting, type an equal symbol and enter the full path to the cell you want to link. For example, to link to cell B10 on the YTD2001 sheet in the sales.xls workbook saved in the support folder on the Retro Lunch website, enter =’http://www.retrolunch.com/support/[sales.xls] YTD2001’!B10.
Publishing Excel Documents on the Web
TIP
In Excel 2002, saving pages and publishing pages are not synonymous. Saving always creates noninteractive pages. Interactive pages must be published.
Saving a Static Page To create a noninteractive (static) web page, open the workbook you want to save for the Web. To save the entire workbook, select any cell in the workbook. To save a worksheet for the Web, select any cell in the worksheet. To save a range of cells, select the range. Then choose File Save as Web Page to open the Save As dialog box, shown in Figure 18.3.
PART
V Out of the Box with Excel 2002
Excel 2002 is well equipped to work with the Web. Not only can you save Excel worksheets as web pages, you can open HTML files directly from Excel and drag and drop HTML tables from your browser directly into Excel worksheets. When you save or publish Excel 2002 worksheets as web pages, the pages you create are either interactive or noninteractive. Noninteractive pages are simply static pages that users can look at to examine data, like those you could publish in Excel 97. Interactive pages include the Office Web Components, which empower users by letting them work directly with Excel data in their browser using Excel tools, turning Internet Explorer into a decent ad hoc report and analysis tool.
4002c18.qxd 7/17/01 12:42 PM Page 556
556
CHAPTER 18 • Using Excel 2002 with the Web
FIGURE 18.3 In the Save As dialog box, you can create a static or interactive web page from your worksheet.
Use the Places bar and Save In drop-down list to choose a location for the web page. In the Save options, choose Entire Workbook or the selected sheet or range. The default file name is the workbook name with an .htm extension. You can edit the name to remove spaces. The Title appears in the browser title bar when the page is displayed. Click the Title button to open the Set Page Title dialog box and enter a title for the page.
Click Save to create the web page and close the dialog box. A web page without interactivity is shown in Figure 18.4. The web page can be edited in FrontPage 2000 or 2002, Access 2000 or 2002, or any other application that can edit HTML. You can open the web page in either Excel or Internet Explorer. Excel 2002 provides native support for HTML. But HTML doesn’t provide native support for all the functionality of Excel. When you reopen this web page in Excel, some of the features may be missing. Views, scenarios, and shared workbook information are all discarded when a file is saved as HTML.
4002c18.qxd 7/17/01 12:42 PM Page 557
Publishing Excel Documents on the Web
557
FIGURE 18.4 The noninteractive web page is suitable for use on the Internet.
PART
Publishing an Interactive Page Excel 2002 includes three Office Web Components, and each supports specific kinds of interactivity. They’re called Office Web Components (OWCs) instead of EWCs because they can be used in web pages created with other Office applications, but the functionality is all Excel. The following are the components: • The Spreadsheet component inserts a spreadsheet where users can add formulas, sort and filter data, and format the worksheet. Use the Spreadsheet component to present unsummarized data. • The Charting component is linked to data in the Spreadsheet component so that the chart can display changes when the data in the spreadsheet changes. • The PivotTable component lets users analyze database information using most of the sorting, filtering, grouping, and subtotaling features of PivotTable reports. There’s actually a fourth component, but it works in the background: the Data Source component, which is the data retriever for the PivotTable and chart components.
Out of the Box with Excel 2002
V
4002c18.qxd 7/17/01 12:42 PM Page 558
558
CHAPTER 18 • Using Excel 2002 with the Web
Understanding Office Web Components The Office Web Components is a set of ActiveX components that are included with Office XP. With the components, you don’t need to learn Java to create the slick interactive interface your users are asking for. The Office Web Components are supported by applications like Excel 2000 and 2002, Access, and Internet Explorer 4.01 and 5. The Office Web Components are only interactive if the user’s browser supports ActiveX components. If a user has an older browser, they’ll still see the spreadsheet, chart, or pivot table, but they will not be able to manipulate it in their browser. The Office Web Components have another requirement: your user must have a Microsoft Office 2002 license to use the components. Server versions of the components are available, but they’re generally regarded as a second-class substitute. The Office licensing and browser requirements make the OWCs a better choice for an intranet, where they were intended to be used, rather than the Internet.
To create an interactive page, open the workbook that contains the worksheet. If the workbook or worksheet are password protected, change the password to no password (blank); you can’t publish password-protected ranges. Select the sheet, range, or chart that you want to publish. Choose File Save as Web Page to open the Save As dialog box (see Figure 18.3). Use the Places bar and Save In drop-down list to choose a location for the web page. In the Save options, choose the selected sheet or range. Edit the file name if you wish. Click the Title button to open the Set Page Title dialog box and enter a title for the page.
Enable the Add Interactivity check box, then click the Publish button to open the Publish as Web Page dialog box, shown in Figure 18.5.
4002c18.qxd 7/17/01 12:42 PM Page 559
Publishing Excel Documents on the Web
559
FIGURE 18.5 Use the Publish as Web Page dialog box settings to add interactivity to your web page.
PART
If you have enabled interactivity, choose the component you wish to use from the drop-down list by selecting the kind of functionality you want users to have: spreadsheet, chart, or PivotTable. Chart is only an option if you selected a chart object before opening the Save As dialog box. In the Publish As section of the Publish as Web Page dialog box, click the Change button to designate a page title. Click Browse to find the Web Folder you want to publish in. In Excel 2002, enable the AutoRepublish Every Time This Workbook Is Saved check box to take the hassle out of remembering to republish the worksheet every time you make a change. (See “Automatically Republishing Web Pages” later in this chapter for more information.) If you want to immediately view your page in Internet Explorer, select the View in Web Browser button before you click Publish. When you are ready to publish, click the Publish button. Excel creates the web page, including any interactivity you have specified.
NOTE
If you’re going to create interactive web pages in Excel, your default browser should be IE 5.0 or better.
The completed web page in Figure 18.6 is the same worksheet as we saved as a noninteractive web page, shown in Figure 18.4.
Out of the Box with Excel 2002
V
4002c18.qxd 7/17/01 12:42 PM Page 560
560
CHAPTER 18 • Using Excel 2002 with the Web
FIGURE 18.6 An interactive web page using the spreadsheet component
Office Web Components: The Spreadsheet Component The spreadsheet component includes about as much spreadsheet functionality as you can pack into a browser window. With the static page, the user had one report available in the browser. With the interactive page, they have a report tool with sorting, filtering, and formatting capabilities. Changes that the user makes are retained during the browser session so they can switch from the browser to other applications (like Excel) while they work with the spreadsheet component. Excel users will immediately know how to use most of the buttons on the spreadsheet component toolbar, shown in Figure 18.7, although the Excel 2002 testers in our office were disappointed that the AutoSum button doesn’t have a drop-down list! FIGURE 18.7 The spreadsheet component toolbar provides spreadsheet functionality in a browser window.
4002c18.qxd 7/17/01 12:42 PM Page 561
Publishing Excel Documents on the Web
561
Most of the toolbar buttons are familiar. There are two additions: the Export to Excel button and the Commands and Options button. The Export to Excel button creates the Excel worksheet in a user-specified folder so the user can manipulate it as much as they wish. The Commands and Options button opens the Commands and Options dialog box with additional user tools, shown in Figure 18.8. Use this dialog box to change the format of a worksheet, work with formulas in the sheet, find worksheet data and change worksheet and workbook options.
FIGURE 18.8 Users can change the format and other properties of component cells. PART
Out of the Box with Excel 2002
V
The Spreadsheet component does not support the level of functionality that Excel 2002 does. Table 18.1 describes worksheet properties and features that are not supported by the component.
TABLE 18.1
Fe a t u r e s a n d Fo r m a t t i n g N o t S u p p o r t e d i n S p r e a d s h e e t C o m p o n e n t
Feature
Description
Comments
Discarded.
Conditional formatting
Not supported. Cells in component are formatted as they were displayed when the page was published.
Graphics
Not displayed.
Group and outline symbols
Not supported.
Indented text
Not supported. Displayed without indents.
Links to other worksheets, workbooks, and web queries
Discarded. Cells displayed with values when page was published.
4002c18.qxd 7/17/01 12:42 PM Page 562
562
CHAPTER 18 • Using Excel 2002 with the Web
TABLE 18.1
Features and Formatting Not Supported in Spreadsheet Component (continued)
Feature
Description
Outlined ranges
Collapsed rows are hidden.
Precedent and dependent arrows
Discarded.
Print settings, including rows to repeat, columns to repeat, and print area Rotated text
Discarded.
Not supported. Text is reset to horizontal.
Shared workbook information
Discarded.
Validation rules and error alerts Discarded. Text wrapping
Not supported. Wrapping is turned off and columns adjusted to same width.
Because data values persist through a browser session, another good use of a spreadsheet component is to create a small application that collects values from a user and performs a few calculations. The application is spunky because all the calculation is performed using the client-side OWC. The Loan Amortization worksheet from Chapter 8, “Using the Financial Functions,” makes a nice online application, as shown in Figure 18.9. FIGURE 18.9 The Loan Amortization web page uses the spreadsheet component.
4002c18.qxd 7/17/01 12:42 PM Page 563
Publishing Excel Documents on the Web
563
Office Web Components: PivotTable Component The PivotTable component is underutilized. We run into hundreds of intermediate Excel users who don’t create pivot tables, often because they don’t know where to begin. If you create the pivot table and publish it as a web page, they’ll figure out how to use it. And if, by chance, they make a serious mistake, they can close Internet Explorer, fire it back up, and start again. The web page in Figure 18.10 is the web component version of the Traverse Tree Sales pivot tables from Chapter 13, “Using Excel 2002 to Present Information.” The component works like the Excel PivotTable report with areas for rows, columns, pages, and data. FIGURE 18.10 The PivotTable component lets users interactively analyze data.
PART
Out of the Box with Excel 2002
V
To create the web page, create the pivot table in Excel. Set the table and field options. Select the table, then choose File Save as Web Page to open the Save As dialog box. Click the Publish button, and set your options in the Publish as Web Page dialog box, shown in Figure 18.11.
4002c18.qxd 7/17/01 12:42 PM Page 564
564
CHAPTER 18 • Using Excel 2002 with the Web
FIGURE 18.11 Publish the pivot table, not the entire worksheet.
You don’t need to include every field from the data source in the pivot table. The toolbar in the published component includes a Field List button. Clicking the button opens the PivotTable Field List dialog box, shown in Figure 18.12, so the user can add and remove fields from the table just as they would in Excel. The published pivot table should include the default fields—the fields you want the users to see when the page initially loads in the browser.
FIGURE 18.12 Use the PivotTable Field List dialog box to add and remove table fields.
4002c18.qxd 7/17/01 12:42 PM Page 565
Publishing Excel Documents on the Web
565
The pivot table component does not support every PivotTable Report feature. Table 18.2 describes the features that are not supported. Fe a t u r e s N o t S u p p o r t e d i n t h e P i v o t Ta b l e C o m p o n e n t
Feature
Description
Background refresh settings
Discarded.
Calculated fields
Not supported. Converted to summary functions.
Calculated items
Discarded
Custom calculations
Discarded.
Custom number formats
Discarded.
Custom sort orders
Discarded.
Error value and empty cell options
Discarded. Both errors and empty cells are displayed as blanks.
Indents
Discarded.
Numeric formatting of individual table cells
Discarded.
Print settings
Discarded.
Office Web Components: Chart Component The Chart component displays both the chart and the underlying data (see Figure 18.13). Users manipulate the data to change the chart, just as they would in Excel. To publish a chart with interactivity, select the chart area before choosing File Save as Web Page. Don’t spend a lot of time formatting your chart before publishing it. Most chart features are supported, but drawing objects (such as callouts and other annotations) and the placement of chart elements is not. If, for example, you’ve neatly positioned the title and data labels and then resized the plot area, you’ve wasted your time. They’ll all snap back to their default positions in the chart component. Table 18.3 describes the chart options that are not supported by the Chart component.
PART
V Out of the Box with Excel 2002
TABLE 18.2
4002c18.qxd 7/17/01 12:42 PM Page 566
566
CHAPTER 18 • Using Excel 2002 with the Web
FIGURE 18.13 The Chart component reflects changes in the underlying data.
TABLE 18.3
Fe a t u r e s N o t S u p p o r t e d i n C h a r t C o m p o n e n t
Feature
Description
Surface charts
Not supported; returns an error.
Graphics and drawing objects in chart
Discarded.
Semitransparent fills
Discarded.
Series lines
Discarded.
Chart element placement
Titles, legend, and other elements return to their default locations.
Plot visible cells only
Ignored. All data is plotted.
Error bars based on a calculation
Discarded.
4002c18.qxd 7/17/01 12:42 PM Page 567
Publishing Excel Documents on the Web
567
Appending to an Existing Web Page If you already have a published spreadsheet and you’d like to add another web component (such as a chart or a pivot table) to it, you can append the data to the existing page. To place a second component to a page, choose File Save as Web Page and then click Publish to reopen the Publish as Web Page dialog box. Enter the existing HTML file in the File Name text box. When you click Publish, you’re prompted to replace or add to the page. Choose Add to File to display more than one component on the page.
PART
If you change data used to create a web page, you can resave or republish the data to keep the web page up-to-date. To have Excel automatically republish data when you save changes to the original workbook, check the AutoRepublish Every Time This Workbook Is Saved check box in the Publish as Web Page dialog box. When you save the workbook, Excel asks if you want to republish. Normally you’ll select the second option, Enable the AutoRepublish Feature. If you choose this option, you can also instruct Excel to bypass the human element in the future by enabling Do Not Show This Message Again.
“Do Not Show This Message Again” is Microsoft-speak for “Click Here and You’ll Never Find This Option Again.” There may be times that you will not want to
V Out of the Box with Excel 2002
Automatically Republishing Web Pages
4002c18.qxd 7/17/01 12:42 PM Page 568
568
CHAPTER 18 • Using Excel 2002 with the Web
automatically republish a file. For example, AutoRepublish is very inconvenient under the following conditions: • You’re working offline with a file that has been saved as a web page. • You just entered totally incorrect data or an incredibly sensitive piece of information that’s not supposed to be published yet and saved the Excel workbook. On the other hand, if you don’t enable the check box, you’ll always be prompted to approve the republish operation. If you choose the first option, Disable the AutoRepublish Feature while This Workbook is Open, you won’t be prompted to republish again until you close, reopen, and save the workbook. To turn off AutoRepublish choose File Save as Web Page, then click Publish to open the Publish as Web Page dialog box, shown in Figure 18.14. In the Choose dropdown list, choose Previously Published Items. FIGURE 18.14 To turn off AutoRepublish, open the Publish as Web Page dialog box.
Select the previously published item that you want to disable AutoRepublish for and clear the AutoRepublish check box. Close the dialog box and save the workbook.
4002c18.qxd 7/17/01 12:42 PM Page 569
The L’s: Excel, HTML, XML, and MHTML
569
Creating Web Parts A digital dashboard is a montage of different types of data that provide an overview of one or more aspects of your organization in one or more web pages. For example, a single-page digital dashboard in a sales department might display month-to-date and year-to-date sales for different regions or product lines, news about customers, and links to product information pages. Each section of data on a digital dashboard is presented in a component called a web part, and the dashboard itself is served by a collaboration server such as Exchange 2000 or SharePoint Portal Server.
The L’s: Excel, HTML, XML, and MHTML Excel 2000 included native support for Hypertext Markup Language (HTML), the language of the World Wide Web invented by Tim Berners-Lee in 1989. The web pages created earlier in this chapter were HTML pages, editable with a wide range of programs built to work with HTML. Standards for HTML are set by W3C, the World Wide Web Consortium, but compliance with the standards is voluntary. Every browser supports special features that aren’t included in the standard, which explains why the same web page looks and behaves differently (or not at all) in different browsers.
XML In 1998 the W3C posted goals for a new language that would facilitate data transfer between computers and systems. The new Extensible Markup Language (XML) would meet very specific criteria. The XML draft document describes a standard language with optional features “kept to an absolute minimum,” resulting in easy-to-create, human-readable
PART
V Out of the Box with Excel 2002
The Office Web Components make dandy web parts. To create a web part you need the URL of the digital dashboard (for example, http://myserver/myteam/dashboards/ salesdash.htm). In the Publish dialog box, enter the URL for the digital dashboard as the File Name. After you click Publish, you’ll be prompted to enter properties for the web part.
4002c18.qxd 7/17/01 12:42 PM Page 570
570
CHAPTER 18 • Using Excel 2002 with the Web
documents. In less than four years, XML has moved from a set of goals to a language that has undergone frequent and rapid revision. Excel 2002 includes native support for XML, as does Access 2002 and SQL Server 2000. Smart tags can be created in XML (see Appendix D, “Creating Simple Smart Tags in Excel 2002”). One thing is clear: if you’re a programmer or an aspiring programmer, you can’t ignore XML. XML is a language used to describe data as a hierarchy: a company has departments, departments have employees, employees have first names and last names, and so on. The following simple XML file describes one “record,” an e-mail message:
[email protected] [email protected] [email protected] 06/01/01 Structure and Services When will this appear on the agenda? On the surface, XML’s form looks much like HTML. Each element (MESSAGE, TO, CC) has a start tag and an end tag, and content is sandwiched between the two. The start tag is enclosed in and the end tag in . The element name can be in uppercase or lowercase, but it must be the consistent. Unlike HTML, you can’t get sloppy with end tags in XML. They are required. Every XML document has a root element (also called a document element) that is the highest level of the hierarchy. The last closing tag in the XML document closes the root element (in our example, the MESSAGE element). Anything that precedes the start tag for the root element is part of the file’s prolog: file type, processing instructions, and so on. An XML document that has matching start and end tags for every element and conforms to the hierarchy is called well-formed XML. The preceding XML code is well formed. If you open the document in IE, it will be displayed. But there’s no way to know if it’s correct. It could be missing elements or have elements included that should not be. The real standard for XML is validity. A valid XML document includes or references a definition that describes the structure of the data. The XML is only valid if the data in the XML document complies with the definition.
4002c18.qxd 7/17/01 12:42 PM Page 571
The L’s: Excel, HTML, XML, and MHTML
571
NOTE
XML doesn’t handle all data well. It is not designed to handle large sets of complex data and binary objects (such as graphics), and it, of course, was not designed to work with proprietary data formats.
Opening XML Files in Excel 2002
Excel reads the structure of the file and parses it appropriately. You can edit and save the file, or you can manipulate the data in Excel 2002.
PART
Saving Excel Files as XML
Out of the Box with Excel 2002
So where does Excel fit in all of this? Excel reads and writes XML. Choose File Open, and XML documents are displayed in the files pane alongside the XLS files. Here’s what the XML file listed earlier looks like in Excel 2002:
To save a spreadsheet as XML, choose File Save As or Save and choose XML Spreadsheet in the Save as Type drop-down list. When you save a small Excel workbook as XML, the resulting XML file is bulky—lines and lines of text. The Company Sales workbook has a single worksheet, 24 cells of which have contents, shown in Figure 18.15. FIGURE 18.15 The Excel workbook contains only this much data.
Unlike a text file or .csv file, the XML file contains all the information it needs to recreate the Excel workbook. The file begins with the standard “I am XML” processing instruction: This is followed by 23 lines of code describing the application (Excel), the document properties, workbook protection, and the position of the application window
V
4002c18.qxd 7/17/01 12:42 PM Page 572
572
CHAPTER 18 • Using Excel 2002 with the Web
on the screen. Thirteen more lines describe the document template and format in detail. Finally, we arrive at the worksheet: Each column width is precisely described: …. And each row element has its cell elements, which have contents: Company Sales Staff Unique Products Market Share ABC.com 27 12 0.19 …. The file ends with another two-dozen end tags to close the row, worksheet, protection, and so on: nearly 100 lines to describe the contents of 24 cells. With XML, the beauty is not in brevity, but in precise detail. If you open the XML file in Excel, it will look exactly as it did before you saved it as XML. The other reason Excel is a powerful application for XML is that you can run Visual Basic code to actually do things with an XML file: to ignore the elements you don’t need and use those that you require.
MHTML When you save an Excel worksheet as a web page, you often end up with parts and pieces. The pivot table we saved earlier generated three files: an HTML page and a folder that contains two XML files. Web archives save all the pieces of a website into a single file. Choose File Save As and choose MHTML as the file format. The resulting MIME HTML (MHTML) document can be e-mailed and received with all its parts intact. Your message recipient will need IE 4 or higher to open the file.
TIP
Internet Explorer also supports web archives. To save an entire web page as one file, choose the Web Archive Single File file type.
4002c18.qxd 7/17/01 12:42 PM Page 573
Creating Web Queries
573
Creating Web Queries XML is coming, but web queries are here today in Excel 2002. With Excel 2002’s Web Query feature you can retrieve data from any accessible table on an intranet or the Internet. Web query is just the implement you need to harvest the fields of data available on the Web. You can retrieve data as static data or create a refreshable web query. To quickly create a static web query from Internet Explorer, follow these steps: 1. Locate the data you want to work with. 2. Select and copy the data.
4. Paste the data. 5. Before you deselect the pasted range, click the Paste Options button to open the options menu. 6. To create a static web query, choose Keep Source Formatting or Match Destination Formatting. 7. To create a create a refreshable web query, choose Create Refreshable Web Query, which opens the New Web Query dialog box, shown in Figure 18.16.
FIGURE 18.16 The New Web Query dialog box “maps” the tables on the web page.
PART
V Out of the Box with Excel 2002
3. Switch to Excel 2002.
4002c18.qxd 7/17/01 12:42 PM Page 574
574
CHAPTER 18 • Using Excel 2002 with the Web
Starting in Excel If you start in Excel rather than IE, make sure you’re connected to the Internet or a network intranet and choose Data Import External Data New Web Query. The New Web Query dialog box opens, displaying the home page from your browser. To navigate to the page that contains the data, enter a URL or select a page from the Address drop-down list. The list comes from your browser history.
TIP
If you need to create many web queries, you can save time by clearing the browser history, then visiting each of the pages in your browser before creating web queries.
Each importable table is marked with a yellow arrow icon. HTML supports nested tables, so many pages have lots of tables (see Figure 18.16). Point to an icon to highlight the corresponding data in the table; the icon in the upper-left corner selects all the importable data on the page. Click the icon to select the table; the icon changes to a green check mark. Select the tables you wish to import, then click the Import button to return the data to Excel.
NOTE
Click the Save button before importing to add the query to your list of data
sources.
Setting Web Query Options Click the Options button to open the Web Query Options dialog box, shown in Figure 18.17, and set the options described in Table 18.4. FIGURE 18.17 Set formatting and import options in the Web Query Options dialog box.
4002c18.qxd 7/17/01 12:42 PM Page 575
Using the Camera
We b Q u e r y O p t i o n s
Option/Setting
Description
Formatting: None
The default.
Formatting: Rich Text
Excel-like formatting, but without hyperlinks or merged cells.
Formatting: Full HTML
Full formatting including merged cells and hyperlinks.
Import Blocks Into Columns
Enable to use the delimiters in preformatted sections to determine how to parse the data into columns. Disable to place each row of preformatted data in a separate worksheet cell.
Treat Consecutive Delimiters as One
Disable to treat delimiters as you would in a text data file; enable to ignore consecutive delimiters.
Use the Same Import Settings for the Entire Section
Enable to apply the Treat Consecutive Delimiters setting to all preformatted blocks on the page; disable to specify treatment for individual blocks.
Disable Date Recognition
Turn on to ensure that numbers similar to dates (part numbers, for example) are not converted to dates in Excel.
Disable Web Query Redirection
Enable to prevent redirection of the query if the data source moves.
In Excel, you can use the query result set as you would any native Excel data, adding formulas or creating charts. For more information on working with query results, see “Working with Query Results in Excel” in Chapter 16.
Using the Camera The camera is not a new feature in Excel 2002, but it’s well hidden, so not many Excel users even know it exists. Camera creates a picture that links to a worksheet range (like an internal, continuously refreshing query tool that comes in handy in some very specific situations). For example, imagine you have data on two separate worksheets, and that data needs to stay on two worksheets. The problem: you want to present the data on one worksheet for an online report, printed report, or web page. The solution? You could create a worksheet of formulas that link to the ranges in the two worksheets, but you can solve this problem in much less time using the camera.
TIP a chart.
The camera only captures cells. You can’t use the camera to capture an image of
PART
V Out of the Box with Excel 2002
TABLE 18.4
575
4002c18.qxd 7/17/01 12:42 PM Page 576
576
CHAPTER 18 • Using Excel 2002 with the Web
The camera captures an image of the data. The image is linked to the source cells, so as the data changes the image is updated, but you can place and size the image in the worksheet as you would a chart or graphic. In Figure 18.18, we’re using a camera object as a data table for a chart. You can’t do much to format a data table. There’s far more flexibility with an image of the source data. FIGURE 18.18 Use the Camera to place images of ranges anywhere in a workbook.
Before you can use the Camera, you need to add it to a toolbar or menu. Rightclick any toolbar and choose Customize from the shortcut menu. On the Commands tab, shown in Figure 18.19, choose the Tools category. Camera is near the bottom of the Commands menu. Drag the Camera command from the dialog box and drop it on a toolbar. Close the Customize dialog box.
NOTE
For more information on customizing toolbars and menus, see Chapter 21, “Automating Excel 2002 with Macros.”
Camera creates a picture, so before you start snapping the shutter, make sure the cells appear as they should. You can format the cells, but not the picture. If you don’t want grid lines in the picture, turn them off. Select the cells, chart, or other worksheet object you want to create an image of and click the Camera button. A flashing line appears around the selection. Switch to the worksheet where you want to paste the image. Click to place the upper-left corner of the image in the worksheet, as shown in Figure 18.20. Use the handles to move and size the image.
4002c18.qxd 7/17/01 12:42 PM Page 577
Using the Camera
577
FIGURE 18.19 On the Commands tab of the Customize dialog box, find the Camera and drag it to a toolbar.
PART
FIGURE 18.20 Click to place the camera image in the worksheet.
Out of the Box with Excel 2002
V
4002c18.qxd 7/17/01 12:42 PM Page 578
578
CHAPTER 18 • Using Excel 2002 with the Web
Bringing It Full Circle One final thought: At the beginning of this chapter, we saved a non-interactive web page. Static pages aren’t one of the most celebrated features in Excel 2002, but they’re useful for data that changes infrequently or on a predictable basis, such as data that’s acquired as the result of a batch operation at the end of each month. Put non-interactive pages together with web queries, and you have another way to deliver interactive information to Excel users. Instead of interacting in a browser, users can interact directly in Excel. First, create the non-interactive web page. Then create a new web query and return the data to Excel. In Figure 18.21, we’re querying a static page of data that changes only once a year: population figures and projections for the United States based on gender. Republishing the page annually isn’t a burden. And unlike pages with interactivity, users can easily query this page, making it part of their worksheet. FIGURE 18.21 Post non-interactive pages and users can query them using the web query feature.
4002c18.qxd 7/17/01 12:42 PM Page 579
Bringing It Full Circle
579
Figure 18.22 shows the query results in Excel 2002. When the page is republished, users have the most current data simply by clicking the Refresh button on the query toolbar. Charts based on query data are updated automatically, too. FIGURE 18.22 The query results are easily refreshed when the data on the page is updated.
PART
Out of the Box with Excel 2002
V
4002c18.qxd 7/17/01 12:42 PM Page 580
This page intentionally left blank
4002c19.qxd 7/18/01 3:02 AM Page 581
PA R T
VI ANALYSIS AND COLLABORATION WITH EXCEL 2002 ◗
Creating data tables
◗
Using Goal Seek to solve business equations
◗
Using Solver to find optimal solutions
◗
Saving scenarios
◗
Auditing worksheets
◗
Routing workbooks
◗
Using Send for Review
◗
Tracking and updating changes
◗
Using SharePoint Team Services in Excel 2002
4002c19.qxd 7/18/01 3:02 AM Page 582
This page intentionally left blank
4002c19.qxd 7/18/01 3:02 AM Page 583
19
CHAPTER
SOLVING BUSINESS PROBLEMS USING THE ANALYSIS TOOLS F E ATU R I NG
Creating data tables
Using Goal Seek
Using Solver
Creating scenarios
Merging and summarizing scenarios
Creating and printing reports
Adjusting views
4002c19.qxd 7/18/01 3:02 AM Page 584
n this chapter, we’ll examine Excel’s analysis tools. You already know how to use many of the business analysis tools: Excel’s functions and formulas. For more advanced work, Excel includes specialized forecasting tools often referred to as What If tools that are used in What If analysis: data tables, Goal Seek, and Solver. (Using What If tools is sometimes called wiffing, short for What-Ifing.) Then we’ll focus on Excel’s reporting features, including views, the Scenario Manager, and the Report Manager.
i
Creating Data Tables Data tables are used to show the results of changing either one or two variables used as arguments in a formula. The Loan Payment Calculator worksheet in Chapter 8, “Using Financial Functions,” and shown in Figure 19.1 was created using formulas that were filled, but it’s an ideal candidate for the data table feature. The values in the shaded area (B8:F17) change based on the values in column A and row 6. The formula in cell B8, which was copied to the other cells in the shaded area, is =PMT(IntRate/12,$A8*12,-B$6). FIGURE 19.1 The Loan Payment Calculator worksheet is a data table. The payment amount changes based on the principal and length of the loan.
NOTE
Anything you can do with a data table can also be done with a series of formulas. Some users would always create this table with formulas, as we did in Chapter 8. Others prefer data tables to complex formulas with absolute cell references.
4002c19.qxd 7/18/01 3:02 AM Page 585
Creating Data Tables
585
First, we’ll create a data table that uses a single variable. The worksheet in Figure 19.2 will use the square root function (SQRT) to return the square root of a series of values. The syntax of the function is =SQRT(value). To create a single variable data table, enter the series of values in a row or, as shown in Figure 19.2, in a column. The data table feature uses an input cell to temporarily store each value from the data series as it calculates results—a scratch pad of sorts for Excel’s use while creating the table. Excel changes the value of the input cell as it creates the table, so the input cell should be an empty cell. Rather than creating nine formulas that refer to cells A4 through A12 (or creating and filling a formula), you create one formula that refers to the input cell, as shown in Figure 19.2. FIGURE 19.2 Enter the data series as a row or column. Enter the data table formula in the empty cell above or to the left of the results cells.
FIGURE 19.3 Provide an input cell in the Table dialog box.
PART
VI Analysis and Collaboration
Enter the formula in the cell directly above the first cell that will return results: B3 in Figure 19.2. Note that the formula in B3 refers to D2, the input cell. If the series is entered in a row, enter the formula in the cell immediately to the left of the first results cell. Select the data table range, including the formula, data series, and results cells as a single range; in our worksheet, the range A3:B12. Do not include the input cell. Do not hold the Ctrl key and select multiple ranges. Do not include nearby unused cells. With the cells selected, choose Data Table to open the Table dialog box, shown in Figure 19.3.
4002c19.qxd 7/18/01 3:02 AM Page 586
586
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
Enter the input cell in the Row Input Cell text box if your data is in a row or the Column Input Cell text box if your data is in a column. Click OK to create the data table, shown in Figure 19.2.
Creating a Data Table with Two Variables Now we’ll return to the data table in the Loan Payment worksheet. The process is the same, but two input cells are required: one for the changing number of periods in column A, and another for the changing loan principal in row 6. As with the single variable table, Excel will use the input cells to temporarily store each value in column A and row 6 while it calculates the table. The modified worksheet, ready for table creation, is shown in Figure 19.4. Note that there is no empty row between the loan amounts and the first row of the table. FIGURE 19.4 For two variables, create a formula that uses two input cells.
There are lots of empty cells in every worksheet. We applied a fill to the two input cells to make them easy to find with the Table dialog box open. The completed table is shown in Figure 19.5. We’re not quite finished, of course. We’ll remove the fill from E2:E3 and A7, and format A7 so the DIV/0 error isn’t displayed. The error is normal when the input cells are empty.
4002c19.qxd 7/18/01 3:02 AM Page 587
Forecasting and Modeling
587
FIGURE 19.5 This version of the Loan Payment Calculator worksheet uses a data table.
The formulas in a data table are an array. You can format the values (including conditional formatting), but you can’t delete a single value from the table.
To delete the results, select the results and press the Delete key, or choose Edit Clear Contents.
Forecasting and Modeling
• Historical information—last year’s sales, weighted averages of past performance, experience from similar business units
PART
VI Analysis and Collaboration
Business forecasts—predictions of business factors like product demand, production costs, income, and expenses—are the weather report for a business unit’s future. Like a weather forecast, a business forecast may be inaccurate. However, there is one important difference between a weather forecast and a business forecast: while we can’t change the weather, managers can monitor the progress of a business and make decisions to move actual performance closer to the forecast. Business forecasts try to simulate future behavior of variables (like gross profit) based on information gathered from a variety of sources. A forecast may be based on the following:
4002c19.qxd 7/18/01 3:02 AM Page 588
588
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
• Judgments or educated guesses by people in a position to help predict future performance (such as managers, clients, sales staff) • Information about the external environment—prices charged by competitors, the local employment level, regulatory changes, or the current interest rate • Relevant models for the industry, size, geography, or other attributes of the organization The more good sources of information you consider, the more accurate your forecast will be. There are different ways to construct forecasts. In Excel, forecasting always involves creating a model: one or more worksheets with formulas to show how different variables interrelate.
Making Assumptions Forecasting is always based on assumptions. Each model has specific, built-in assumptions, but there are general assumptions common to most models. One general assumption is that the future will be much like the present: the world’s financial markets won’t fall apart during the life of an equipment lease, so you will need to make a lease payment this month and every month in the future until the end of the lease. You also assume that a forecast will not be perfect. There will always be some neglected piece of information that affects the forecast, because a model is a simulation of reality, not reality itself. Another assumption is that the distant future is more difficult to predict than the near future. (That’s why it is difficult to get 50-year mortgages or place bets on the 2009 World Series.) No one could have accurately predicted the last four years of stock market prices or the recent success mapping the human genome. As the time involved in a forecast increases, the accuracy of the forecast decreases, even if the model was essentially accurate in the short term when it was constructed.
Building an Accurate Model There are several steps involved in building a model and using it to forecast performance: 1. Determine what you need to forecast with the model: Gross sales? Best price? Optimal number of staff? 2. Make explicit assumptions. 3. Define and collect information for the model. 4. Create the model in Excel.
4002c19.qxd 7/18/01 3:02 AM Page 589
Forecasting and Modeling
589
5. Use the model to forecast the future value of variables. 6. Compare real performance to the model and adjust the model (or change actual performance) as necessary.
Scenario: Organize! Corporation We’ll use a fictitious company, the Organize! Corporation, to work with Excel’s analysis tools. The Organize! Corporation makes a variety of organizer products, from paper clip holders to shoe racks. Organize!’s CD Division makes organizers for compact discs. 1. What We Need to Determine: Organize! management needs to decide how many organizers the CD Division should make each month. We’ve been put in charge of collecting and modeling the information needed to decide how the CD Division can maximize gross profit for the next 12 months. 2. Assumptions: Organize! management assumes that they will be able to sell CD organizers to large computer and music stores as they have in the past. More assumptions will be added as information is collected. 3. Required Information: We need to collect information on the income generated by organizer sales and the expenses involved in manufacturing the CD organizers. Some of the expenses are fixed expenses, expenses that are the same amount no matter how many CD Organizers are manufactured. Other expenses (like labor and materials) are variable expenses. The Accounting Department predicts that the CD Division’s fixed monthly expenses are not expected to change ($80,000 for building mortgage, maintenance, and salaries) in the next year. There are several pieces of variable cost information: hourly employees make $6.00 and overtime hours are paid at time and a half. During a month, the current workforce can build 48,000 organizers without working overtime. Each CD organizer takes an hour to make and uses $1.25 in raw materials.
PART
VI Analysis and Collaboration
www
The amount of effort spent on each step should be based on the importance of the information you intend to obtain from the model. You don’t want to spend hours researching a decision to save two dollars. But you need to spend sufficient time when you are creating a model to support decision making that involves hundreds of thousands of dollars. Excel’s analysis tools require something to analyze. You’ll use your own data to create a model that works for your organization, but in the short run, you can download the worksheets from the Sybex website (www.sybex.com).
4002c19.qxd 7/18/01 3:02 AM Page 590
590
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
The Marketing Department uses an Excel worksheet to determine sales at various prices for the CD organizer. They have determined that the formula Price=$20(Quantity/5000) expresses the price needed to sell a particular quantity. In other words, customers will spend no more than $20 for an Organize! CD Organizer. At a price of $19, Organize! can sell only 5,000 units. For each additional 5,000 units sold, Organize! must drop the price $1. This month, Organize! manufactured and sold 45,000 units.
Creating the Organize! Business Model We have enough information to create an Excel model of the basic factors that influence production and pricing for CD organizers. We also have some new assumptions: that the information from Accounting and Marketing is accurate and that their information will be valid for next year.
EXPERT TIP Use extensive commenting in worksheets used for forecasting. Every number or formula you enter has some basis, but it’s not always easy to reconstruct the source in six months or a year. If, for example, you enter information obtained from a website, right-click in the cell and choose Insert Comment from the shortcut menu. Enter the URL for the website and the date and summarize the information (which may be removed from the Web page at any time). The Accounting department information contains an IF statement: if production is less than or equal to 48,000 units, then the cost of labor is $6 per hour. Hours in excess of 48,000 cost $9 per hour. Since this month’s sales were 45,000, let’s begin by modeling production of sales of 45,000 units. The worksheet with formulas displayed at the right is shown in Figure 19.6. FIGURE 19.6 The basic model for current production
4002c19.qxd 7/18/01 3:02 AM Page 591
Forecasting and Modeling
591
Now we can expand the model to include three levels of production—40,000, 45,000, and 50,000—by adding column headings, entering units produced in row 5, and copying the formulas and fixed expenses to the other two columns. Figure 19.7 shows all three levels of production. FIGURE 19.7 The CD Division model includes cost figures at three levels of production.
PART
VI Analysis and Collaboration
Now we’re ready to check the accuracy of the model. Is the gross profit for the current month close to $88,750? If it is not, we know that information is missing from the model; if the difference between the model and reality is significant, we’ll want to track down the factors that account for the difference and include them in our model. If current gross profit is close to the $88,750 forecast, we can be more confident about the model’s ability to predict gross profit at other levels of production. If we needed to recommend one of the three production levels at this point, we would recommend production of 40,000 CD organizers (column D in Figure 19.7). They make more money making fewer organizers, which is bad news for a company named Organize!. Our goal, however, was to find the level of production that maximizes gross profit. We could continue adding columns and copying formulas until we arrived at an answer. Fortunately, there’s a better way. We’ll use Excel’s Goal Seek and Solver features to forecast values outside the current model. Use Goal Seek analysis when you want to find a specific solution by changing one variable. Solver, a linear programming tool, supports multivariate analysis and is the tool designed for most real-world problems where more than one variable can change.
4002c19.qxd 7/18/01 3:02 AM Page 592
592
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
Using Goal Seek Goal Seek is used to calculate backward—to determine the values necessary to reach a specific goal. If you have a worksheet model, you can use Goal Seek to get a specific answer. For example, one of the Organize! managers wants to know how many units must be manufactured and sold to result in gross profits of exactly $100,000 per month. You know the goal, and Goal Seek will help you find the answer. Goal Seek changes an underlying value (Units Produced in row 5) until the value in the goal cell (Gross Profit) is equal to the goal ($100,000). Excel will begin by trying an upper and lower value for Units Produced. If the goal falls between the initial values, Goal Seek then narrows the value in small increments until the Gross Profit value is within 0.01 of the goal. If the goal value is outside the initial range, Goal Seek will try larger values. Each attempt to meet the goal is an iteration. The default settings (Tools Options Calculation) instruct Excel to try 100 iterations before giving up. Here are the steps to use Goal Seek: 1. Open the workbook that has the figures you want to calculate from. 2. Choose Tools Goal Seek from the menu bar to open the Goal Seek dialog box, shown in Figure 19.8.
FIGURE 19.8 Select a cell to contain your goal, a target value, and a variable cell in the Goal Seek dialog box.
3. Enter references or values in all three controls of the Goal Seek dialog box: Set Cell The cell that will contain the goal result. There must be a formula in this cell. To Value
The target value.
By Changing Cell The cell that contains the value that will be incrementally changed to try to reach the goal in the Set Cell. This cell must contain a value. 4. Click OK to start Goal Seek. 5. To accept the solution, click OK in the Goal Seek Status dialog box to enter the Goal Seek solution. To reject the solution, click Cancel.
4002c19.qxd 7/18/01 3:02 AM Page 593
Using Goal Seek
593
When you choose to keep the Goal Seek solution, the solution overwrites the existing values with the solution values. To retain the data from the existing model, begin by copying any one of the columns to use with Goal Seek, as shown in Figure 19.9. FIGURE 19.9 When a solution is found, the solution value is entered in the worksheet.
PART
VI Analysis and Collaboration
The dialog box indicates both the goal value and Goal Seek’s progress in matching the value. In this case, the match is exact. Goal Seek was able to find a value for Units Produced that resulted in a Gross Profit of exactly $100,000. Clicking the OK button replaces the figures in the Set Cell and Changing Cell with the Goal Seek results. Clicking Cancel leaves the original figures in the two cells. Some problems don’t have a solution. Figure 19.10 shows the Goal Seek message box when a solution cannot be found. The target value entered for Gross Profit was 250,000. Goal Seek has already tried 100 numbers. The last number tested—a very large, negative number—is displayed as the Current Value; the other numbers in column E are so large that they can’t be displayed in the current column width. Goal Seek has already tried both positive and negative numbers as large as the Current Value shown in the dialog box. It’s unlikely that additional iterations would result in a solution. Even when Goal Seek can’t find a solution, however, you know more than you knew before. Given the values for price, fixed expenses, and variable expenses, Organize! cannot make $250,000 a month from the CD Division no matter how many CD organizers they manufacture (or fail to manufacture).
4002c19.qxd 7/18/01 3:02 AM Page 594
594
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
FIGURE 19.10 Goal Seek displays a message when a solution cannot be found.
Using Solver Solver is used to find an optimal solution: the largest or smallest value rather than a specific value goal (like 100,000). Optimization has many business applications. Solver can be used to find the least expensive solution to a problem, or a solution that maximizes income. Solver can also be used, like Goal Seek, to find a specific value. Use Solver rather than Goal Seek when you need to change values in multiple cells or apply constraints. Our original assignment was to maximize gross profit. This is a job for Solver. As with Goal Seek, a Solver solution overwrites existing data; you must copy the model to another column if you want to retain the solution. 1. Choose Tools Solver to open the Solver Parameters dialog box, shown in Figure 19.11.
4002c19.qxd 7/18/01 3:02 AM Page 595
Using Solver
595
If you don’t see Solver on the Tools menu, click Tools Add-Ins and choose Solver Add-In in the Add-Ins dialog box. Excel may prompt you for the CD to install this feature.
NOTE
FIGURE 19.11 Use Solver to find the optimal solution to a problem.
2. Enter references or values in the following controls: Set Target Cell Solver’s Target Cell is the same as Goal Seek’s Set Cell: the cell that the final result should appear in. If this is the active cell when you fire up Solver, it’s automatically entered. Equal To Set the Max, Min, or Value Of option to solve for the largest or smallest possible number or a set value.
3. After you have made choices for these three controls, click the Solve button. Like Goal Seek, Solver will try 100 iterations before reporting that it cannot find a solution. A successful solution is shown in Figure 19.12. Choose to Keep Solver Solution or Restore Original Values. (Saving scenarios is discussed in the “Using Scenarios” section later in this chapter.) If you choose Keep Solver Solution, the original values will be overwritten. You cannot undo this change.
PART
VI Analysis and Collaboration
By Changing Cells As with Goal Seek, the By Changing Cells is the cell that Solver changes to find the solution indicated. After you select a Target Cell, click the Guess button to have Solver examine the formula in the Target Cell and find all of its predecessor cells that contain values. Delete any guessed cells that Solver should not change as part of the solution.
4002c19.qxd 7/18/01 3:02 AM Page 596
596
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
FIGURE 19.12 Keep or discard the Solver solution.
Using the Evaluate Formula Feature We have the answer to our question: given the current fixed costs, variable costs, and pricing structure, Organize! can maximize gross profit by producing 31,875 CD Organizers. We also have a problem. If you multiply 31,875 by 13.63, the answer is 434,456, not the 434,297 shown in Figure 19.12. The Solver solution understates income by almost $160. More to the point, it’s just plain incorrect. If a couple of people get bored while you’re presenting your numbers and start punching their calculator buttons, the potential downside is larger than $160. This problem isn’t caused by Solver or by the fact that the income formulas are interrelated. The problem is a common problem when using Goal Seek and Solver, but this problem also crops up in simple division formulas. The problem also provides a great opportunity to use a new Excel feature, the Evaluate Formula feature to figure out what the problem is. To get to Evaluate Formula, display the Formula Auditing toolbar. Select the cell with the formula you wish to evaluate (in our case, E6), and click the Evaluate
4002c19.qxd 7/18/01 3:02 AM Page 597
Using Solver
597
button. The Evaluate Formula dialog box opens, displaying the formula. One portion of the formula is underlined.
Click the Evaluate button in the dialog box to evaluate the underlined portion of the formula:
PART
VI Analysis and Collaboration
Note that the Solver result in E5 is slightly less than 31,875. This could account for some small part of the missing $160. The other half of the formula, E6, is a formula, too. You can click the Step In button to drill down into the formula in E6.
4002c19.qxd 7/18/01 3:02 AM Page 598
598
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
Whether you step into the formula or continue to work with the formula in E7, continue to click the Evaluate button and view the results of each evaluation. When the formula is fully evaluated, the problem pops into view.
The result in E6 is not 13.63, but 13.6250000053992. Nearly one half a cent shy of $13.63. A half-cent doesn’t seem like a lot, but when you multiply it by 31,875, it’s about $160. This is a rounding error. The error is relatively hard to find, but easy to fix: so easy to fix that you should consider fixing the problem in advance when you’re working with Solver and Goal Seek. The current formula in cell E6 is =20–(E5/5000). Change the formula to =ROUND(20-(E5/5000),2), and the displayed result in E6 is the same: 13.63. The total income, however, is correct.
But wait a minute, isn’t this cheating? Of course not. You’re going to charge customers $13.63, not $13.6250000053992. By adding the ROUND function to the formula, the worksheet reflects reality: something it failed to do without ROUND.
Using Solver with Multiple Variables Goal Seek is limited to changing one variable, but Solver can work with multiple variables at the same time. Solver also lets you specify constraints—limits for individual
4002c19.qxd 7/18/01 3:02 AM Page 599
Using Solver
599
variables—to guide the optimization process. Our current model has only one independent variable—Units Produced—and no constraints except those already included in the model’s formulas. (While Unit Price changes, it changes only when Units Produced changes.) Many business problems are more complex: the optimal solution is not Choice A or Choice B, but a mix of the two, and is constrained by real conditions like the availability of materials or skilled labor. This type of business problem requires a type of analysis called linear programming—finding the best intersection between two or more courses of action.
What Should Organize! Build? Thanks to our model, the CD Division is now maximizing gross profits. A work team in the CD Division suggests that the division expand its product line. Each of the division’s four machines can make DVD organizers as well as CD organizers. DVD organizers sell for a higher price, but they also take longer to produce. Based on our earlier Solver solution, each CD organizer results in $3.87 gross profit for the division ($123,362/31,875). Marketing predicts that DVD organizers can be priced to gross $5.16 per unit.
Constraints We need to determine whether the CD Division will increase profit if they dedicate part of their machine time to DVD organizers. Organize! could simply try a new product mix for a couple of months, but we can easily model the mix of products that will maximize profits. There are some specific constraints: • It takes 3 pounds of material to make a CD Organizer. It takes 3.1 pounds to make a DVD Organizer. • The division can obtain 400 pounds of material daily. Currently the material is used to make 124 CD organizers.
Determining Organize!’s Optimum Production We’ll begin by creating a model that includes the relevant information for CD and DVD Organizer production to help determine the best production mix. This model doesn’t need a lot of formulas. A model with formulas displayed is shown in Figure 19.13. Row 5 models the current production mix per machine: 33 CD organizers produced per machine in each 24-hour period, which gross $3.87 each. The current mix for all four machines is in row 6.
PART
VI Analysis and Collaboration
• Forty-five minutes of machine time is required to make a CD organizer. DVD Organizers take one hour of machine time. In a 24-hour day, a machine can turn out 32 CD organizers or 24 DVD organizers. Organize! has four machines.
4002c19.qxd 7/18/01 3:02 AM Page 600
600
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
FIGURE 19.13 The DVD Proposal worksheet models the materials and time required for current production.
The number of hours in a day places a constraint on the optimal solution. The Hours constraint is the number of hours spent producing CD organizers (CD Qty * CD Hours) plus the hours used to created DVD Organizers (DVD Qty * DVD Hours). There are only 24 hours in a day and only four machines, so this number will need to be less than or equal to 96. The Solver Parameters dialog box allows you to specify constraints like this. The available pounds of material provide the other constraint. There are only 400 pounds to be divided between the two products. The Material constraint (CD Qty * CD Material + DVD Qty * LD Material) cannot exceed 400. There are two additional constraints: we can manufacture no fewer than zero DVD organizers or CD organizers. If you don’t specify these constraints, Solver often returns a solution that includes manufacturing a negative number of a product. After you’ve constructed your model, including constraints, open the Solver Parameters dialog box (Tools Solver), shown in Figure 19.14. Follow these steps to set multiple constraints: 1. In the Solver Parameters dialog box, set the Target Cell, Equal To option and the By Changing Cells range. In this case, the changing cell is F12 (Total) and the Changing Cells are B9 and B10. 2. To add a constraint, click the Add button to open the Add Constraint dialog box.
4002c19.qxd 7/18/01 3:02 AM Page 601
Using Solver
601
FIGURE 19.14 Set constraints to reflect real resource limitations that affect your model.
3. Select the cell that contains the formula to be constrained and an operator, and enter a value for the constraint. Click Add to add the constraint and create another constraint, or click OK to add the constraint and close the dialog box. 4. Click Solve to have Solver calculate a solution, as shown in Figure 19.15. 5. To keep the results, select Keep Solver Solution in the Solver Results dialog box and click OK.
PART
VI Analysis and Collaboration
FIGURE 19.15 Keep the original values or accept Solver’s solution.
4002c19.qxd 7/18/01 3:02 AM Page 602
602
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
Producing 46.24 CD Organizers and 61.32 DVD Organizers each day uses only 329 pounds of material and every available hour of machine time: the optimal solution. The increased efficiency also results in greater profits: $495.36 per day, an increase of $15.48 per day, which is over $4,000 per year.
Saving Solver Models In Excel 2002, you can save and rerun models created in Solver, so you can create Solver models with different assumptions (constraints) or with different goals. Create the model first: in the Solver Parameters dialog box (Tools Solver), set up the Solver parameters, including the constraints. Then click the Options button to open the Solver Options dialog box.
Click the Save Model button to open the Save Model dialog box, shown here:
A range of cells is suggested. You don’t need to save the model in the suggested range, but you need to select either a single cell or the same number of cells as the suggested range. Solver uses the range to store specific values from the model including the solution, the number of iterations, and the constraints. Click OK to save the model. To reuse a model, open the Solver Parameters dialog box, click the Options button, and click Load Model. In the Load Model dialog box, select the entire range of cells saved as the model.
4002c19.qxd 7/18/01 3:02 AM Page 603
Using Scenarios
603
Although we’ve used an example from manufacturing, Excel 2002’s analysis tools are used in many types of businesses. Hospitals use Solver to determine optimal staffing. Banks use Goal Seek and Solver to calculate necessary reserves at changing interest levels. Fast food chains use Solver to minimize the amount of time customers stand in line waiting to order a burger by increasing staffing during peak hours (part of a nifty realm of study called queuing theory). Whenever you are trying to meet a goal, increase efficiency, or maximize profit, Excel’s What If tools provide information to support a decision-making process.
Using Scenarios Wouldn’t it be nice if you could save models that reflect different scenarios: best case, worst case, current, and most likely? Excel has just the tool for this type of What If analysis! Create and save different groups of values using Excel’s Scenarios feature, and then view the results of different scenarios with just a couple clicks. Let’s take a look at Organize!’s gross profits in a worst-case scenario. We know from using Solver that while they maintain a single manufacturing line (CD organizers), Organize! can maximize their gross profits by producing 31,875 CD organizers at a per unit price of $13.63. Now let’s create a scenario that projects gross profits if Organize! can only use one of its four machines. It’s easiest to begin by clicking in the cell that contains the variable you are changing. Since we’re experimenting with Units Produced, we’ll select E5. Follow these steps to create a scenario: 1. Navigate to the original worksheet that just shows CD production, and choose Tools Scenarios to open the Scenario Manager. 2. Click the Add button to open the Add Scenario dialog box shown in Figure 19.16.
PART
VI Analysis and Collaboration
FIGURE 19.16 Create a variety of What If scenarios with the Add Scenario dialog box
4002c19.qxd 7/18/01 3:02 AM Page 604
604
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
3. Type a name for the scenario (like Single Machine Production) in the Scenario Name field. 4. Enter the address of the cell or cells you wish to change in the Change Cells field. Enter additional details about the scenario in the Comment field. If you’re sharing the workbook with other users, you may choose to protect the scenario by preventing changes or hiding it.
TIP
As with all protection, the worksheet and scenario are not protected until you protect the worksheet (Tools Protection Protect Sheet).
5. Click OK to open the Scenario Values dialog box and enter the value for this scenario.
6. Click OK to return to the Scenario Manager. Click Add to continue creating scenarios. Close the Scenario Manager when you’re finished. To display a scenario, open the Scenario Manager (Tools Scenario) and choose a scenario from the list. Click the Show button to display the scenario results in your worksheet. Goal Seek and Solver both support scenarios. To save the results of an analysis operation as a scenario, click the Save Scenario button in the Solver or Goal Seek Results dialog box.
Merging Scenarios You can merge scenarios from multiple workbooks, provided that each scenario has been created from the same base model and uses the same values except for the changing cells. The merge feature makes it easy for members of a team to create scenarios independently and then consolidate the scenarios into one workbook. To merge workbooks, open all the workbooks that contain scenarios. Activate the workbook that will receive all the scenarios. Choose Tools Scenarios to open the Scenario Manager dialog box, shown in Figure 19.17.
4002c19.qxd 7/18/01 3:02 AM Page 605
Using Scenarios
605
FIGURE 19.17 Open all scenario workbooks, switch to the workbook that will contain all the scenarios, and then open the Scenario Manager.
When you’re merging a number of scenarios in the Scenario Manager, you recognize the value of explicit but brief scenario descriptions. To edit a scenario description before merging the scenario, open the workbook, open the Scenario Manager, select the scenario, and click the Edit button to open the Edit Scenario dialog box. When you’ve finished editing the scenario, click OK to return to the Scenario Manager.
TIP Excel automatically appends your username and the current date to the scenario’s description when you modify a scenario. You can remove the added text if you wish by editing the scenario again and deleting it. Click the Merge button to open the Merge Scenarios dialog box, shown in Figure 19.18.
PART
Analysis and Collaboration
VI FIGURE 19.18 Choose the workbook and worksheets that contain the scenarios in the Merge Scenarios dialog box.
4002c19.qxd 7/18/01 3:02 AM Page 606
606
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
For each workbook that you want to merge scenarios from, do the following: 1. Select the workbook from the drop-down list. 2. Choose the worksheet that contains the scenarios. 3. Click OK to merge the worksheet’s scenarios into the workbook. If two scenarios have the same name, Excel appends the worksheet creator’s name or the current date to the end of the scenario name, depending on your operating system and profile. If a worksheet contains more than one scenario, all scenarios are merged. To remove a scenario, select the scenario in the Scenario Manager and click the Delete button.
Summarizing Scenarios Use the Scenario Manager’s summarization feature to create an executive summary, comparing the results of different scenarios in a single table or pivot table. The worksheet in Figure 19.19 summarizes four different scenarios for the Organize! CD Division. FIGURE 19.19 Summarize the results of several scenarios in a single table for side-by-side comparison.
In the summary, each column of data represents one scenario. The scenario name is used as the column label, with the description immediately below. The description can be easily hidden using the outline symbols on the vertical outline bar.
4002c19.qxd 7/18/01 3:02 AM Page 607
Using Scenarios
607
The description is followed by two sections: the changing cells and results cells. The row labels (in column B in Figure 19.19) are the names of the results cells. If you do not name the results cells, Excel uses the cell address to label the row, so before you launch the Scenario Manager, check to make sure that the cells you want to include in the summary are all named. Activate the worksheet that contains the scenarios, open the Scenario Manager (Tools Scenarios), and click the Summary button to open the Scenario Summary dialog box, shown in Figure 19.20.
FIGURE 19.20 Create a table or pivot table that summarizes all the scenarios from a worksheet.
Choose the Scenario Summary or Scenario PivotTable report type. In the Result Cells text box, either type the results cells, separated by commas, in the order you want them to appear in the summary or hold the Ctrl key and click on the cells in order. Click OK to generate the summary on a new worksheet. A summary pivot table for the same scenarios is shown in Figure 19.21. The summary pivot table is less flashy than the scenario summary, but is a better data source for a chart.
PART
Analysis and Collaboration
VI FIGURE 19.21 Create a summary pivot table if you want to chart the scenario results.
4002c19.qxd 7/18/01 3:02 AM Page 608
608
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
Creating Views A view is a specification for the appearance of an Excel workbook. The default view is the appearance of a workbook when it was last saved. If you close a workbook with the third sheet activated, it opens with the third sheet activated. A view always includes the following: • The size and position of the Excel application window and child windows, including split windows • The hidden/unhidden status of worksheets and columns • The active sheet and active cells when a view is created • Column widths • Display settings including the zoom ratio Optionally, a view can also include the following: • Print settings, including print area • Hidden/unhidden settings for columns and rows • Filter settings Saving custom views enables you to quickly switch between different view settings: for example, a managerial view that displays cost columns and a customer view that hides detailed costs.
NOTE
View has a very different meaning in SQL Server, where a view is similar to a
query.
To create a custom view, first set the print and display options and hide any rows, worksheets, or columns that you wish to hide. Activate the sheet and cells that should be activated when the view is initially enabled. Then follow these steps: 1. Choose View Custom Views to open the Custom Views dialog box. 2. Click the Add button to open the Add View dialog box.
4002c19.qxd 7/18/01 3:02 AM Page 609
Creating Reports
609
3. Enter a name for the view. 4. Disable the check boxes if you wish to omit the current print settings and hidden rows/columns and filter settings from the view. 5. Click OK to create the view and add it to the Custom Views dialog box. To apply a view, choose View Custom Views. Select the view in the Custom Views dialog box and click Show.
Creating Reports Reports combine worksheets, views, and scenarios into a single printable document with consecutive page numbers. Reports are created with an Excel add-in, the Report Manager, and saved with the workbook. You must download and install the Report Manager from the Microsoft website. To create a report, choose View Report Manager to open the Report Manager dialog box, shown in Figure 19.22. Click the Add button to add a report to the workbook. Enter a name for the report in the Report Name text box. Follow these steps to add sections, in order, to the report: 1. In the Sheet box, select the worksheet. 2. To print the worksheet using a view, enable the View check box and choose a view from the list. 3. To print the worksheet displaying a scenario, enable the Scenario check box and select the scenario from the list. 4. Click Add to add the section to the report.
PART
VI Analysis and Collaboration
www
4002c19.qxd 7/18/01 3:02 AM Page 610
610
CHAPTER 19 • Solving Business Problems Using the Analysis Tool
FIGURE 19.22 Create, edit, and print reports in the Report Manager.
If you need to tweak the report, simply open the Report Manager again. Add sections, use the Move Up and Move Down buttons to rearrange sections, or click Delete to remove sections from the report. To print a report, choose View Report Manager. Select the report you want to print. Set the number of copies then click Print.
4002c20.qxd 7/17/01 2:22 PM Page 611
CHAPTER
20
USING EXCEL’S WORKGROUP TOOLS F E ATU R I NG
Exchanging workbooks through e-mail, routing, and posting
Tracking workbook changes
Merging workbook changes
Working in a shared workbook
Using Send for Review
Saving to an Exchange Folder
Using SharePoint Team Services with Excel
Holding virtual meetings
4002c20.qxd 7/17/01 2:22 PM Page 612
ffective collaboration is the key to any successful business today. Whether collaborating across the office or across the world, with coworkers or with competitors, the industries that are thriving in today’s world economy are industries that have learned how to work together. The applications in Office XP were born to collaborate, and Excel is no exception. In this chapter, we’ll explore Excel’s collaboration tools such as sharing workbooks and tracking changes in workbooks. We’ll also introduce you to Microsoft’s newest collaboration tool, SharePoint Team Services, and show you how Excel can play a key role in SharePoint Team Site. Finally, we’ll take to a virtual meeting where you can work on workbooks and other documents without ever leaving your desk.
e
Working with Workgroups Excel’s sharing and tracking features make it easy for you to collaborate with others by sharing the same workbook file among multiple users. Excel’s workgroup features range from simple tools for distributing files for comments—e-mailing and routing— to powerful features that allow you to distribute copies of workbooks and merge changes from the copies into a single file. Excel minimizes the potential for problems by giving you control over how the changes made by all of the users are merged into a single, error-free file.
E-mailing Workbooks There are two ways to e-mail Excel worksheets to another user. You can send an entire workbook as an attachment or send a copy of the active sheet as HTML in the body of an e-mail message. Send the entire workbook when the recipient has Excel and you want them to be able to manipulate the data in Excel. When you send a copy of the active sheet, the recipient can view the information but cannot alter it. They do not, however, need Excel to view the worksheet; they only need Outlook or a Web browser.
NOTE
To e-mail a worksheet as HTML, you need Outlook. To e-mail a message as an attachment, you need Outlook, Outlook Express, or another MAPI- or VIM-compatible messaging system.
To e-mail the entire workbook, choose File Send To Mail Recipient (as Attachment) or click the Email button on the Standard toolbar and choose Send the Entire Workbook as an Attachment when prompted. To e-mail the active worksheet as HTML, choose File Send To Mail Recipient or click the Email button on the
4002c20.qxd 7/17/01 2:22 PM Page 613
Working with Workgroups
613
Standard toolbar and choose Send the Current Sheet As the Message Body. In either case, an Outlook message form opens for you to address and add additional comments. If Outlook is not already running, you may be prompted to select an Outlook profile. When you send the worksheet as the body of an HTML message, you can enter additional comments in the Introduction pane that opens in the message form, as shown in Figure 20.1. When you send the message, your comments appear above the worksheet separated by a horizontal line. FIGURE 20.1 When you send a worksheet as HTML, you can add comments to the message in the Introduction pane.
PART
Routing Workbooks By routing a workbook you can determine the order in which recipients can view the workbook. For example, you may want to have one of your coworkers review a workbook before you send it to your administrative assistant so that your assistant can see the changes or comments that your coworker made. You can also use routing to send a workbook to a distribution list. You can track the status of the routed workbook as it
Analysis and Collaboration
VI
4002c20.qxd 7/17/01 2:22 PM Page 614
614
CHAPTER 20 • Using Excel’s Workgroup Tools
moves from one recipient to the next. After all recipients have reviewed the workbook, it automatically returns to you. follow these steps to route a workbook: 1. Open the workbook. 2. Choose File Send To Routing Recipient to open the Routing Slip dialog box.
3. Before the Routing Slip opens, you are prompted to allow access to the Outlook address book. Select the Allow Access For check box and click Yes. This is one of Office XP’s tools to guard against the spread of e-mail viruses. You don’t need to change the length of time—one minute should be sufficient.
4. Click the Address button in the Routing Slip dialog box to open the Address Book dialog box and add recipients in the order that you want them to receive the workbook.
4002c20.qxd 7/17/01 2:22 PM Page 615
Working with Workgroups
615
TIP If you choose a distribution list as the recipient, all the members of the list are treated as a single recipient and will receive the workbook at the same time. To route the workbook to members of a distribution list in order, select the individual members, rather than the name of the list. 5. Click OK to return to the Routing Slip. 6. Use the Move Up and Move Down buttons to change the order the recipients will receive the workbook. 7. Edit the Subject, if desired, and enter a message to accompany the workbook in the Message Text box. 8. Set the Route to Recipients options: • Choose One After Another if you want the recipients to receive the workbook in order or All at Once if order is irrelevant. • Select Return When Done if you want the workbook back after everyone is finished with it. • Select Track Status if you would like to know who has the workbook at any given time. 9. Click Route to route the workbook. OR Click Add Slip to prepare the workbook for routing at a later time. When you’re ready to route the workbook, open it and choose File Send To Next Routing recipient. When you send the message, Outlook prompts you again that a program is trying to send mail on your behalf. Click Yes to allow the message to go through. PART
Analysis and Collaboration
VI
4002c20.qxd 7/17/01 2:22 PM Page 616
616
CHAPTER 20 • Using Excel’s Workgroup Tools
Receiving a Routed Workbook When you receive a workbook that has been routed to you, the e-mail message includes Routing in the subject and in addition to any message the sender added, includes the following text: The enclosed document has a routing slip. When you are done reviewing this document, choose Send To from the Microsoft Excel File menu. Then select Next Routing Recipient to continue the routing.
Open the attachment as you normally would by double-clicking it and then choosing to open it or save it to disk. When you are finished reviewing it and are ready to send it to the next person on the list, choose File Send To Next Routing Recipient. A dialog opens to tell you that this document has a routing slip—as if you didn’t know that—and asks if you want to route the document to the next person on the list or send a copy of the document without attaching the routing slip.
Generally, you are going to choose to send the workbook to the next name on the list. Use the second option if you want to send the workbook to someone who is not on the routing list. For example, you might need to ask a colleague for additional information or a second opinion on specific numbers before you “sign off” the workbook and route it to the next person. The recipient of a copy is not added to the routing list. When you send the document on to the next recipient, the originator receives a message showing the status of the document—but only if the originator enabled Track Status when they set up routing. Even with status tracking enabled, Excel routing has its limitations. Routed messages can’t skip recipients, and routing is entirely dependent on recipients. If, for example, one of the people on the routing list does not pay attention to their e-mail, they impede the process for anyone downstream. The routing feature is good for workbook review and commentary, but it isn’t robust enough for workflow applications where you need to know where a file is in the review process and move the workbook around obstacles.
4002c20.qxd 7/17/01 2:22 PM Page 617
Working with Workgroups
617
Sharing Workbooks Excel 2002 is designed to allow multiple users to view and modify a single workbook simultaneously. If you want others to be able to use a workbook while you have it open, you need to share the workbook and ensure that it is stored on a shared drive that other users can access. To share a workbook, choose Tools Share Workbook from the menu to open the Share Workbook dialog box.
PART
VI Analysis and Collaboration
By default, the current user has exclusive rights to the active workbook. On the Editing tab, enable the Allow Changes check box to make the file accessible to other users. Click OK and Excel immediately prompts you to save the workbook—click Save. After saving, notice it says Shared in the title bar. If you return to the Shared Workbook dialog box, you’ll notice that you no longer have the workbook open exclusively—other Excel users can now open it. When you share a workbook, Excel automatically tracks the changes made by each user. As the workbook owner, you can then review the changes and accept or reject each change made. You can set options for tracking changes and resolving conflicts on the Advanced tab, shown in Figure 20.2.
4002c20.qxd 7/17/01 2:22 PM Page 618
618
CHAPTER 20 • Using Excel’s Workgroup Tools
FIGURE 20.2 Use the Advanced tab of the Share Workbook dialog box to set up the rules for the shared workbook.
As the owner of the shared workbook, the options described here give you control over the changes made to the workbook: Track Changes Choose Keep Change History for X Days if you’d like Excel to maintain a history of changes so that you can review the changes and merge multiple copies of the same document for a specified interval. If you choose Don’t Keep Change History, you will not be able to merge changes from multiple copies of the same document and you will not be able to review changes. Update Changes You can choose to update changes only when the file is saved or at an automatic interval that you specify. If you choose the automatic update option, you can also choose whether you want to see your changes along with everyone else’s or only see other’s changes. Conflicting Changes between Users If more than one user changes the same cell of the shared workbook, you can choose to have Excel ask you which changes should be saved or you can have Excel automatically keep the changes as they are when you save the workbook. Include in Personal View Enable the Print Settings and Filter Settings check boxes so you can save any personal print or filter settings that you choose without affecting others who are sharing the workbook. After you have set all the shared workbook options, click OK to save the changes.
4002c20.qxd 7/17/01 2:22 PM Page 619
Working with Workgroups
619
Highlighting Changes in a Shared Workbook When you track changes in a workbook, Excel notes each change in the corresponding workbook cell. You can turn on the Track Changes feature by choosing Tools Track Changes Highlight Changes and selecting the Track Changes while Editing check box in the Highlight Changes dialog box, shown in Figure 20.3. If you have already shared the workbook using Tools Share Workbook, this option is already enabled. You can’t track changes in a workbook unless it is shared, so if you haven’t already enabled workbook sharing, this action also shares the workbook. FIGURE 20.3 Use the Highlight Changes dialog box to track changes, share a workbook, and set Highlight Changes options.
NOTE
If you want to simply track the changes that you make, save the workbook to a private folder or password-protect the shared workbook and don’t give anyone the password.
PART
VI Analysis and Collaboration
When Highlight Changes is enabled, each change made is noted in a comment, and changed cells are flagged with a cell indicator in the upper-left corner. Excel assigns a different triangle color to each user who modifies the workbook, so you can visually inspect the workbook to find all the changes made by each user. Hover over the cell, and Excel displays a screen tip to show you the changes that have been made.
4002c20.qxd 7/17/01 2:22 PM Page 620
620
CHAPTER 20 • Using Excel’s Workgroup Tools
NOTE
If you are not seeing indicators in the cells you change, read on. It could be because the Highlight options are set to only show the changes other people make.
Viewing the Change History You can examine all the changes that have been saved in a workbook since you shared it and set different criteria for which changes you want to view. To set options for which changes are highlighted in the workbook, return to the Highlight Changes dialog box (Tools Track Changes Highlight Changes), shown earlier in Figure 20.3. In the dialog box, select the time period for the changes you want to review and specify the users whose changes you want to see. If you only want to see changes for a particular range or sheet, select the range you want to view in the Where text box. If you would like to track changes but not see them on the screen, clear the Highlight Changes on Screen check box. Enable the List Changes on a New Sheet check box to have Excel add a History sheet to the workbook listing all of the changes made. Figure 20.4 shows an example of a History sheet. FIGURE 20.4 Excel creates a History sheet that notes all the changes made to a shared workbook.
When you view the history on a separate worksheet, you can filter the changes to find changes made by different users or on specific dates. When you remove a workbook from shared use, the change history is turned off and cleared. If you want to keep the changes, select the information on the History worksheet and copy it to another worksheet before unsharing the workbook.
4002c20.qxd 7/17/01 2:22 PM Page 621
Working with Workgroups
621
NOTE
History is a reserved name in Excel, so you’ll have to come up with a different name for the sheet you copy.
Resolving Conflicts If changes you are saving conflict with changes saved by another user, you are prompted to resolve the conflict (unless you changed the Conflicting Changes setting in the Advanced tab of the Share Workbook dialog box). In the Resolve Conflict dialog box, you can review each change individually and accept your change or others’ changes or you can accept/reject changes in bulk.
Accepting or Rejecting Changes
You can review a workbook and accept or reject changes in bulk or individually as you do in Microsoft Word. To begin reviewing, choose Tools Track Changes Accept or Reject Changes. A message box notifies you that this action will save the workbook. Click OK to open the Select Changes to Accept or Reject dialog box.
Specify the time period, users, and cell range you wish to review. If you don’t specify the changes, you’ll review the entire workbook. Click OK to open the Accept or Reject Changes dialog box. PART
Analysis and Collaboration
VI
To accept or reject all changes, click the Accept All or Reject All button. To accept or reject a specific change, select the change and then click the Accept or Reject button. Click Close when you are finished reviewing changes.
4002c20.qxd 7/17/01 2:22 PM Page 622
622
CHAPTER 20 • Using Excel’s Workgroup Tools
Merging Workbook Changes If you anticipate many conflicting changes in a shared workbook or if you want users to be able to make changes independently and then review all changes at once, make and distribute copies of the shared workbook. To create the copies, use Save As and give each copy of the workbook a different name. Then you can merge the copies when users are finished with their changes. You can only merge workbooks that have the same change history, so it’s important that none of the users turn off sharing while using the workbook (see the sidebar “Protecting Workbooks for Merging”). The history must be complete when you merge the workbooks. If, for example, you set the number of days for the history at 30 days and users keep the workbooks for 32 days, you won’t be able to merge the workbooks. Before you make copies of the shared workbook, make sure you set the history to allow enough time for changes and merging. If you’re uncertain, set the history to 1,000 days or an equally ridiculous length of time. Follow these steps to merge shared workbooks: 1. Open your copy of the shared workbook that you want to merge changes into. 2. Choose Tools Compare and Merge Workbooks. If you haven’t saved your copy of the workbook, you’ll be prompted to do so. 3. In the Select Files to Merge into Current Workbook dialog box, choose the copy (or copies) of the shared workbook containing the changes you wish to merge. Click OK.
Protecting Workbooks for Merging To prevent users from turning off sharing or changing the change history, password-protect the workbook before sharing and distributing it. The process for protecting shared workbooks is changed in Excel 2002. 1. Choose Tools Share Workbook to open the Share Workbook dialog box. 2. Select the Editing tab and make sure the Allow Changes by More than One User at the Same Time check box is enabled. 3. On the Advanced tab, select Keep Change History For, and enter a number of days that vastly exceeds the number of days the workbooks will be shared. If you’re not sure, enter 1,000.
4002c20.qxd 7/17/01 2:22 PM Page 623
Working with Workgroups
623
4. Switch back to the Editing tab and clear the Allow Changes by More than One User at the Same Time check box so the workbook is no longer shared. Click OK. A message box appears indicating you’ll remove the workbook from shared use. Click Yes. 5. Choose Tools Protection Protect and Share Workbook. 6. Enable the Sharing with Track Changes check box. 7. Type a password in the Password text box. 8. Reenter the password when prompted. 9. Save the workbook.
Working in a Shared Workbook Some Excel features aren’t available in shared workbooks. For example, while a workbook is shared, you can’t do any of the following: • Delete worksheets, even those you insert after the workbook is shared • Add or apply conditional formatting and data validation • Insert or delete charts, hyperlinks, or other objects (including those created with Draw) • Subtotal data • Group or outline data However, you can use the features before you share a workbook, or you can temporarily unshare the workbook, make changes, and then turn sharing on again. See Excel’s Online Help for the complete list of limitations of shared workbooks. PART
If you unshare a workbook, it cannot be merged with other copies of the shared workbook. For more information, see “Merging Workbook Changes” earlier in this chapter.
Using Send for Review Send for Review, a new feature in Excel 2002, combines sharing and merging with routing and built-in support for you and the reviewer. When you send a workbook for
VI Analysis and Collaboration
WARNING
4002c20.qxd 7/17/01 2:22 PM Page 624
624
CHAPTER 20 • Using Excel’s Workgroup Tools
review, Excel automates Outlook to create a review request form (so you need to have both installed on your computer). The review request form includes a follow-up flag, a link or attachment (or both) to the workbook, and a message for the reviewer. When the reviewer opens the workbook, Excel 2002 automatically displays the Reviewing toolbar. When the reviewed file is returned to you, Excel automatically prompts you to merge changes from the reviewed workbook into the original workbook. The Reviewing toolbar is displayed so you can accept or reject reviewer suggestions. Before sending a workbook for review, share the workbook and set sharing options. To send the workbook for review choose File Send To Mail Recipient for Review. If the workbook has not been shared, you’ll be prompted to share it under a different filename, but you won’t be provided with an opportunity to set options.
If the workbook is stored on your local computer, a copy of the file is attached to the e-mail message. If it is stored on a network drive or in a web folder, the review request contains a link. If the workbook is stored on a web discussion server (such as a SharePoint Team Services site, discussed later in this chapter), the review request includes a link to the file and instructions for the reviewer about using the discussion server. In either case, Excel asks whether you also wish to attach the file for users who don’t have access to your network or website. The Outlook message isn’t sent automatically, so you can set message options before sending. Table 20.1 describes message settings available on the message toolbar that are useful when sending a workbook for review.
TABLE 20.1
Outlook Message Settings and Options
Setting
Description
Importance
Click the Importance: High or Importance: Low button on the Standard toolbar.
Flagging
Click the Follow Up button on the Standard toolbar to change the default Send for Review flag text (Review) to, for example, Review Immediately or Review and Return, and to set a reminder date and time.
4002c20.qxd 7/17/01 2:22 PM Page 625
Working with Workgroups
625
To set other options, click the Options button on the message’s Standard toolbar to open the Message Options dialog box.
The dialog box options are explained in Table 20.2. Outlook Message Options
Option
Description
Sensitivity
Choose Private, Personal, or Confidential from the list of Sensitivity options.
Security
Click the Security Settings button to encrypt the message or add a digital signature.
Voting Buttons
Enable the Use Voting Buttons check box and select or enter choices separated by semicolons to vote on, for example, the number of days reviewers think the review will require.
Delivery Receipt
Enable the Request a Delivery Receipt for This Message check box to receive e-mail notification when the reviewer receives the message.
Read Receipt
Enable the Request a Read Receipt for This Message check box to request e-mail notification when the reviewer opens the message.
Delay Delivery
Enable the Do Not Deliver Before check box and select the earliest time and date for message delivery.
Delivery Expiration
Enable the Expires After check box and select an expiration date and time.
PART
VI Analysis and Collaboration
TABLE 20.2
4002c20.qxd 7/17/01 2:22 PM Page 626
626
CHAPTER 20 • Using Excel’s Workgroup Tools
After setting options, click OK to close the Options dialog box and click Send to send the message to reviewers.
Reviewing a Workbook A message sent for review is flagged Review in the recipient’s e-mail client. When the recipient opens the workbook, the Reviewing toolbar opens.
Use the Previous Comment and Next Comment buttons to move through the worksheet comments. Click Show All Comments to display all the worksheet comments. Use the Edit Comment button to create a new comment or edit an existing comment, and Delete Comment button to delete the selected comment. Click the Update File button to update a shared workbook with other users’ changes before saving your own changes. When you are finished reviewing the file, click Reply with Changes to return the file to the sender.
Receiving Reviewer Comments The e-mail created by Reply with Changes does not have a flag, so you need to watch for the message if you’re on a deadline. Use the Reviewing toolbar to check the changes submitted by reviewers. If you had reviewers who worked with attachments rather than links to the original shared file, you’ll need to merge their workbooks back into the original. As each reviewer’s workbook is returned, save it with a different name in the same folder. When you’re finished receiving comments and changes from reviewers, click the End Review button to end the review. If you decide to include other reviewers’ comments that arrive after you ended the review, use the Compare and Merge Workbooks feature explained earlier in this chapter.
Saving a Workbook to an Exchange Folder When you share a workbook, other users need to be able to access it. One of the most convenient and accessible storage locations is a Microsoft Exchange folder. You can post an Excel workbook directly to a Microsoft Exchange folder. The workbook appears
4002c20.qxd 7/17/01 2:22 PM Page 627
Using SharePoint Team Services
627
in the list of items in the folder in Outlook and the Exchange Web client, and users with access to the folder have the same permissions for the workbook as they do for other items in the folder. To further protect a workbook, assign passwords (or set permissions to edit ranges) to the workbook, as described earlier, before posting it; users are prompted for their passwords when they open the posted workbook. Follow these steps to post a workbook to an Exchange Folder: 1. Choose File Send To Exchange Folder to open the Send to Exchange Folder dialog box. 2. Select the folder you want to post a copy of the workbook in. 3. Click OK.
Using SharePoint Team Services If you need to collaborate with anyone about anything, SharePoint Team Services is an exciting new offering in the Office XP suite. Whether you are managing a workgroup in a large corporation, supervising home-based employees, or planning a wedding, SharePoint Team Services provides you with a valuable organizational and communication tool. SharePoint Team Services is a Web-based toolset that combines Web publishing, file sharing, and workgroup tools into a flexible and manageable website called a SharePoint team site. Using the team site structure, you can do all of the following and more: • Post announcements • Advertise events • Publish useful links • Share documents
• Share contact data • Assign tasks Figure 20.5 shows the home page of a team site developed for TRIAD Consulting. Since TRIAD is a consulting firm consisting of staff who work primarily from their homes, this team site provides a great way for the staff to stay on top of what is happening, share ideas, pose problems, collaborate on documents, share mutual contacts, and manage small projects. Assigning user roles enables TRIAD’s management to control who can post announcements to the site, who can participate in discussions, and who can customize the site’s design.
PART
VI Analysis and Collaboration
• Hold discussions
4002c20.qxd 7/17/01 2:22 PM Page 628
628
CHAPTER 20 • Using Excel’s Workgroup Tools
FIGURE 20.5 A SharePoint team site is a great way to help people stay in touch with each other.
NOTE
SharePoint Team Services is included with the Office XP Developers Edition and, for a limited time, with the Office XP Special Edition.
Hardware and software requirements for a SharePoint team site are minimal, making it an attractive option for team collaboration. If you are running Windows 2000 Server with Microsoft Internet Information Server 5 or later, you have pretty much everything you need to run SharePoint Team Services. A database such as SQL Server 7 or later is also required. but if you are not running SQL Server, Microsoft Data Engine 7 works fine and it is included with the package. Users can access the site with a Windows, Macintosh, or Unix computer through their browsers—Internet Explorer 4 or Netscape Navigator 4 both work fine for the job. Users who aren’t running Office 2000 or XP can’t contribute documents to the site, but they can still actively participate in the site.
4002c20.qxd 7/17/01 2:22 PM Page 629
Using SharePoint Team Services
629
Creating a Team Site After installing Microsoft SharePoint Team Services and accessing the newly created team site for the first time, you’ll find what looks like an already developed website. It has graphics, links, a navigation bar, and a welcome message. But if you look closely at Figure 20.6, you can see that the site is really an empty container waiting for you to add content. FIGURE 20.6 A newly created team site looks like an already developed site until you take a closer look.
PART
VI Analysis and Collaboration
The home page is designed to provide users with easy access to the major pages of the team site. You can keep your site vibrant by regularly adding new announcements, listing upcoming events, and sharing valuable web links. The Quick Launch bar takes users to key pages in the site. As you add content, you can add links so that key content is never more than a click away. Items that you add to any of the lists displayed on the home page and throughout the team site are designated with a New icon. By default, the New icon appears until midnight on the day it was created. The duration of the New icon can be set by the server administrator.
4002c20.qxd 7/17/01 2:22 PM Page 630
630
CHAPTER 20 • Using Excel’s Workgroup Tools
You can add all kinds of items to a team site from announcements to web links. However, we’ll focus here on how you can make Excel workbooks available and even use reviewing tools to have multiple users make changes to the workbooks. We’ll also show you how to create a team site list by using the contents of an Excel worksheet.
Making New Workbooks Available If you would like to contribute a document to a team site, click the Shared Documents link on the Quick Launch bar. To add a workbook or other document to the Shared Documents library, you have two choices. You can create a new document from scratch or you can upload an existing document. If you click New Document on the command bar to create a new document, you may find that Word opens. The default document type is set by the person who created the document library—in this case, the site administrator—and is a Word document by default. If you want to create any other type of document, such as a workbook, create the document in the appropriate application and then choose Upload Document from the command bar on the SharePoint site. This opens the Shared Documents: Upload Document form, shown in Figure 20.7.
FIGURE 20.7 Use the Upload Document form to make a document available in the Shared Documents library.
4002c20.qxd 7/17/01 2:22 PM Page 631
Using SharePoint Team Services
631
You can enter a filename, but you’re probably safer clicking the Browse button and locating the file that way. When you’ve located the document, click Save and Close to upload the document to the Shared Documents library. After a document is available in the library, click the Edit icon to open the Edit Item form, shown in Figure 20.8.
FIGURE 20.8 Use the Edit Item form to delete a document from the library, send it for review, start a discussion about a document, or edit a document.
PART
VI Analysis and Collaboration
The Edit Item form serves as the jumping-off point for a number of valuable functions. The only field in which you can enter information about the document is the Title field. Use this if you would like to enter a friendly or more descriptive title for the document. However, the title displays only on this page—it does not appear in the Shared Documents library list. If you would like to delete a document from the library, click Delete on the command bar. To edit the document in its native application, click Edit in Native Application on the command bar. When you resave the document in its native application, you must click Save and Close on the Edit Item form in order to make the changes available in the Shared Documents library.
4002c20.qxd 7/17/01 2:22 PM Page 632
632
CHAPTER 20 • Using Excel’s Workgroup Tools
If more than one person on the team edits a document at the same time, a conflict arises and this error message appears:
The site administrator determines how conflicts are handled. If you want to override the changes made by someone else, click the link to the file on the page. To disregard your changes, just ignore this page and click a link on the Top Link bar to move on to something else.
Sending Documents for Review If you would like people on the team, and maybe even some outside the team, to review a document, click Send Document for Review on the Edit Item form. If you plan to include reviewers who do not have access to the team site, you can choose from the following message box to attach the document to the review request.
If Outlook is not already open, it starts up and opens an e-mail message form with a link to the file location or a copy of the document attached. Address the message, add any comments you want, and send it.
4002c20.qxd 7/17/01 2:22 PM Page 633
Using SharePoint Team Services
633
When the recipients open the document, they will find the Reviewing toolbar turned on. They can make changes and send the document back to you with their changes marked by clicking the Reply with Changes button.
Holding Discussions about Documents A document discussion is a way for team members to make comments about a document that can be viewed within the document as a threaded conversation. (See “Holding Discussions about Documents” later in this chapter for more about threaded conversations.) To start a document discussion, click Discuss on the Shared Documents: Edit Item form command bar. This opens the document with a Discussions pane and toolbar at the bottom. Users can insert discussion comments directly in the document or in the Discussions pane. To insert comments in the document, it must be an HTML document. Either option is available from the Discussions toolbar. Figure 20.9 shows an Excel document with a discussion visible in the Discussions pane.
FIGURE 20.9 A document under discussion displays a Discussions pane and toolbar at the bottom of the document.
PART
Analysis and Collaboration
VI
4002c20.qxd 7/17/01 2:22 PM Page 634
634
CHAPTER 20 • Using Excel’s Workgroup Tools
When you click the Insert Discussion about the Document button, an Enter Discussion Text dialog box opens.
Enter the discussion subject and your comments, and click OK to save the discussion. Other users can create their own discussion topics or reply to yours. To reply to a discussion, click the Show a Menu of Actions button at the bottom of the discussion and choose Reply. The Enter Discussion Text dialog box opens again with the discussion subject already entered preceded by “RE:”. The reply appears in the Discussions pane, indented underneath the primary discussion. When you have finished entering discussions, click the Back button on your browser’s toolbar. Discussions are saved automatically.
Importing a List from a Spreadsheet A SharePoint team site is really a collection of lists. Almost everything else is contained in a list—lists of announcements, events, links, tasks, survey results and even document libraries. If you already have a spreadsheet that contains all the columns and list items you want to include in a list, there is no need to recreate the list in your team site. You can automatically create a new list by importing the existing spreadsheet. Before you do this, you need a spreadsheet that complies with the following Excel database rules: • The first row contains column names or you have defined the data set as a named range. If the worksheet contains titles above the database, select and name the database range. • No blank rows exist between the column names and the data. • No blank columns exist within the data set.
4002c20.qxd 7/17/01 2:22 PM Page 635
Using SharePoint Team Services
635
In addition to these standard database rules, the data has to be in the first sheet of the workbook. Taking a few more steps before importing a spreadsheet can make it easier to work with the worksheet after it is imported. You may want to do the following: • Rearrange the columns in the order you want them to be in the default view of the list. You can change the order of the columns after the list is imported, but it’s easier to create the default view in Excel before importing it. • Sort the list in the order you want it to be in the default view of the list. After it is imported, you and the members of the team who use the list can sort it again and also create custom views based on different sort orders. • Format numbers that are not designed to be used in calculations as text—phone numbers, zip codes, etc. Otherwise, you may find that inappropriate comma separators are inserted in the import process such as 49,620 instead of 49620. • Eliminate merged cells. SharePoint Team Services can’t handle merge cells and creates empty cells to replace the missing ones. This could inadvertently screw up both column headers and items in a list. • The file can be saved as an Excel workbook or a static web page, but not as a web page with interactivity. After you’ve verified that your spreadsheet meets requirements for a database and you’ve cleaned up anything you want to address, you are ready to import the list: 1. Click Lists on the Top Link bar. 2. Choose Import Spreadsheet on the Create Page page. 3. Enter a name and a description for the list. 4. Click Browse to navigate to the file location where the spreadsheet resides; select the file and click Open. This places the path to the file in the File Location text box.
6. Click Import to open the spreadsheet so you can select the range to import.
PART
VI Analysis and Collaboration
5. Choose whether you would like to create a link on the Quick Launch bar.
4002c20.qxd 7/17/01 2:22 PM Page 636
636
CHAPTER 20 • Using Excel’s Workgroup Tools
A. If the data you want to import is defined by a named range, click the Range Type drop-down list and select Named Range. You can then choose the named range from the Select Range drop-down list. B. If the range you want to import is not named, click the Select Range drop-down button to select the range in the spreadsheet. Drag over the range of cells you want to import. The range appears in the collapsed Import to SharePoint List dialog box.
7. Click the Expand button to expand the Import to SharePoint List dialog box, and click Import to import the list. If the list did not import as you anticipated it would, delete the list, make the appropriate changes to the spreadsheet, and import it again.
TIP
If numbers in the list contain too many decimals or you want to make other formatting changes, click Modify Settings and Columns on the SharePoint List page, select the column you want to format and set the number of decimal places or make other changes in the Optional Settings for Column section of the Change Column page.
Making Changes to an Imported List After the list is available on the team site, team members can access the list by either selecting it on the Quick Launch bar or selecting Lists from the Top Link bar and then choosing the list. To add items to the list, click New Item on the command bar and fill out the form that opens. Figure 20.10 shows a sample New Item form.
FIGURE 20.10 To add items to a list, enter data in the New Item form.
4002c20.qxd 7/17/01 2:22 PM Page 637
Using SharePoint Team Services
637
To edit an item in a list, click the entry in the first column and then click Edit Item on the command bar. This opens the item in edit mode. After making your changes, click Save and Close to return to the list. This method works great if you are adding a few items or making a few changes. However, if you want to make substantive changes to the list, you may want to export the list, edit it in Excel and then re-import it. This process is called round-tripping.
Exporting a SharePoint Team Site List To export a list from a SharePoint team site, follow these steps: 1. Access the list you want to save, and click Export on the command bar. 2. When you are prompted to save the file or to open it from its current location, choose to open the file from its current location. Excel opens the list as a web query on a sheet in a new workbook. 3. Make any changes to the worksheet. 4. Choose File Save As, and save the file as a workbook (.xls) or web page.
Re-importing the Excel List to a Team Site Before you can re-import a worksheet to a team site, you must first delete the previously imported list and then replace it with the revised list. To delete the list, follow these steps: 1. Open the list on the team site, and click Modify Settings and Columns on the command bar. 2. Click Delete This List. 3. Click OK to verify deletion.
If the list has a large number of columns, you might have to scroll to the right to find the Modify Settings and Columns link.
You can now re-import the list following the steps outlined earlier in this chapter.
Learning More about SharePoint Team Sites In this chapter, we hope we have wet your whistle for further exploration into SharePoint team sites. This dynamic new tool can solve many collaboration nightmares with minimal effort and minimal expense. SharePoint team sites are not only easy to
PART
VI Analysis and Collaboration
NOTE
4002c20.qxd 7/17/01 2:22 PM Page 638
638
CHAPTER 20 • Using Excel’s Workgroup Tools
use, they have incredible flexibility and options for customization. If you want to add content that doesn’t fit into the existing structure, you can edit pages in Microsoft FrontPage and add additional HTML pages to tailor the site to meet any need.
NOTE
SharePoint Team Services is one of two new of Microsoft products called SharePoint Technologies. The other is SharePoint Portal Server 2001, designed to facilitate collaboration in large enterprise environments. You can learn more about SharePoint Technologies, including SharePoint Team Sites and Portal Server at the Microsoft SharePoint Portal Server website www.microsoft.com/sharepoint.
Holding Virtual Meetings to Share Excel Documents Virtual meetings allow a group of geographically separated people to work together on documents over the Web. Microsoft provides three tools that can be used for online collaboration: • Windows Media Services can be used for one-way presentations and media events that invitees can view online. This is especially valuable for one-way audio/video conferencing and PowerPoint presentations. • Microsoft NetMeeting can provide application sharing, online chats, whiteboard capabilities, and file transfer for invitees on the Internet and intranet. Although NetMeeting can support multiple users, it is a point-to-point conferencing tool that limits audio/video conferencing to the initiator and first invitee. Others can participate using text-based chat. • Microsoft Exchange Conferencing offers similar tools to NetMeeting in a rich, multi-user environment. Participants can share applications, participate in online chats, use whiteboard capabilities, and transfer files among participants. Full collaboration capability and conference management is reached when Microsoft Exchange Conferencing 2000, Windows 2000 or later, Microsoft Exchange Server 2000, Exchange Instant Messenger, and Outlook 2002 are deployed simultaneously. To demonstrate the similarities and differences between Microsoft NetMeeting and Microsoft Exchange Conferencing and how different server environments affect their
4002c20.qxd 7/17/01 2:22 PM Page 639
Holding Virtual Meetings to Share Excel Documents
639
functionality, Microsoft has developed several case scenarios that you can review at www.microsoft.com/exchange/evaluation/overview/ECS_Scenarios.asp. You can use Outlook’s Calendar to schedule a virtual meeting—just click the This Is an Online Meeting Using check box in an open Appointment form and select the tool you plan to use.
PART
VI Analysis and Collaboration
You can then enter information about the Directory Server you want to use, the organizer’s e-mail address, and if you are using Microsoft NetMeeting, you can also enter the path to an Office document you want to share during the meeting. When the meeting time comes, Outlook automatically starts NetMeeting or Windows Media Services and signs you in to the meeting. Figure 20.11 shows the NetMeeting window when a meeting is in progress. If you would like to hold a NetMeeting with just a couple of people, you can use your standard Internet connection. However, if you plan to have a large group meeting, you should have access to a conferencing server, such as Microsoft Exchange Conferencing Server, to manage the conference for you. To learn more about NetMeeting and to download the free software, visit www.microsoft.com/windows/ netmeeting. For more information about Microsoft Exchange Conferencing Server visit www.microsoft.com/exchange.
4002c20.qxd 7/17/01 2:22 PM Page 640
640
CHAPTER 20 • Using Excel’s Workgroup Tools
FIGURE 20.11 From the NetMeeting window, you can click one of the buttons at the bottom to share an application, chat, use the whiteboard, or transfer files.
NOTE
Microsoft used to maintain a group of conferencing servers for public use. Because of the amount of unseemly traffic they were receiving, they have discontinued access to these servers. If you would like access to a public NetMeeting server, you can still find one at http://communities.msn.com/TheNetMeetingZone.
Whichever solution you decide is the best for your particular needs, moving meetings out of drab conference rooms and into virtual conference environments can be a challenging but rewarding undertaking. The next time you need to work with someone else on a Excel workbook to develop a client proposal, conduct data analysis, explore what-if scenarios, or any of the myriad other collaborative tasks you have to do, consider giving NetMeeting a try. It may feel awkward at first but with a little practice can turn a boring meeting into a dynamic and productive work session.
4002c21.qxd 7/17/01 3:12 PM Page 641
PA R T
VII AUTOMATING EXCEL 2002 WITH MACROS AND VBA ◗
Recording macros
◗
Running macros
◗
Creating custom menus and toolbars
◗
Assigning macros to command buttons
◗
Using the Visual Basic editor
◗
Creating UserForms
◗
Setting properties
◗
Creating user-defined functions
◗
Testing and debugging in VBA
◗
Understanding the Excel 2002 Object Model
◗
Creating an application
4002c21.qxd 7/17/01 3:12 PM Page 642
This page intentionally left blank
4002c21.qxd 7/17/01 3:12 PM Page 643
CHAPTER
21
AUTOMATING EXCEL WITH MACROS F E ATU R I NG
Recording a macro using the Macro Recorder
Storing and naming macros
Running macros
Examining and editing Visual Basic code
Creating custom menus and toolbars
Creating custom menu items and buttons to run macros
Assigning macros to commands
Assigning hyperlinks to commands
Using form buttons to run macros
4002c21.qxd 7/17/01 3:12 PM Page 644
xcel 2002 is more than just a spreadsheet, chart creator, or data analysis tool. This chapter and those that follow look at the most powerful Excel tool of all—its programmability. Excel and the other Office XP applications share a common language, Visual Basic for Applications (VBA), so you can automate other Office applications from Excel creating, for example, worksheets that send data to Word or charts to PowerPoint presentations. There are two ways to create VB programs. If you’re already familiar with Visual Basic, you can program Excel by opening the Visual Basic interface and typing code. You’ll learn about Visual Basic and Visual Basic for Applications later in this chapter, but you don’t have to know anything about Visual Basic to create macros in Excel 2002. The simplest way to create VB code in Excel is by using the Macro Recorder, which automatically writes VB code as you step through a task.
e TIP
While Excel’s Macro features are included in a typical installation, the Office XP Administration Kit allows installers to omit Visual Basic and all the VB tools when they install Office XP. If the Macro menu items do not appear, or are disabled, talk to your network administrator.
Creating Macros in Excel In Excel 2002, as in Word, PowerPoint, and previous versions of Excel, you can use the Macro Recorder to create macros. You turn on the recorder, complete the steps you want to repeat, and save the macro. The next time you need to complete the steps, you “play back” the steps by running the macro. Before recording a macro, you should practice the steps you want to record, because once you begin recording, all your actions are recorded, mistakes included. Take note of the conditions your macro will operate under and set up those conditions. Will you always use the macro in a specific workbook? If so, open the workbook. Will the macro always be used to change or format a selected range? Then have a range selected before you begin recording the macro, just as you will when you run the macro later. When you are clear which steps you wish to record and have set up the same conditions the macro will run under, select Tools Macro Record New Macro to open the Record Macro dialog box, shown in Figure 21.1.
4002c21.qxd 7/17/01 3:12 PM Page 645
Creating Macros in Excel
FIGURE 21.1 The Record Macro dialog box in Excel
645
PART
Automating Excel 2002 with Macros and VBA
VII
The suggested name is Macro1 just as the name of a blank workbook is Book1. Enter a more descriptive name for the macro. Here are rules to bear in mind when naming a macro: • Visual Basic names, including macro names, can be up to 255 characters long, and they can contain numbers, letters, and underscores but not spaces or other punctuation. • Names must begin with a letter. • Names can include both uppercase and lowercase letters. Visual Basic will preserve your capitalization style, but it is not case sensitive: it won’t recognize FixMyName and fixmyname as different names. If your organization uses a naming convention, you’ll probably prefix the macro name with mcr for macro or bas for Visual Basic code. Some companies only use the bas prefix, whether or not you create the macro with a macro recorder. Check the standards for your organization to determine the appropriate prefix. Excel creates a description that includes the date and your username (see Figure 21.1) Enter a new description of the macro’s action; include your name and contact information (extension or e-mail address) so other users will know who to contact if there are questions or problems with the macro.
TIP In Excel 2002, don’t create macros to open other workbooks, insert images, or navigate within a workbook. All of these actions are more easily handled with hyperlinks. See Chapter 14, “Creating Workbooks for Other Users,” for information on navigational hyperlinks. For information on using hyperlinks to insert images or open files, see the “Assigning a Hyperlink to a Command” section later in this chapter.
4002c21.qxd 7/17/01 3:12 PM Page 646
646
CHAPTER 21 • Automating Excel with Macros
Storing a Macro In the Store Macro In drop-down list, select the workbook you want to store the macro in. The storage location determines how you’ll be able to access and run the macro later: • If you select the current workbook (or another workbook), the macro will only be directly available in that workbook. If you want to use the same macro somewhere else, you’ll have to copy or re-create it or you will need to insert Visual Basic code that loads the workbook before the macro can be run. Macros that are stored in a workbook or template are called local macros. • Storing an Excel macro in the Personal Macro Workbook creates a global macro, which is available to all workbooks created in Excel. If you’re not sure where to store a macro, err on the conservative side and store it locally. While global macros are convenient, all global macros are loaded each time you launch Excel, consuming valuable resources. And macro names you use globally can’t be reused in individual workbooks. Unless a macro is going to be widely used, it’s best to store it locally. In the Record Macro dialog box, you can assign a shortcut keystroke combination to a macro. In practice, this is not a very good idea; most of the Ctrl combinations and many of the Ctrl+Shift combinations are already in use. It is better practice to assign frequently used macros to a menu or a toolbar button; you have more control over menus and toolbars, which can be turned on and off programmatically. After you’ve set the recording options in the Record Macro dialog box, click the OK button to begin macro recording. The message Recording is displayed at the left end of the status bar and the Stop Recording toolbar opens. The Macro Recorder records the actions you take, but not the delay between actions, so there’s no rush. If you want the macro to enter text, enter the text now. Type carefully—if you make a mistake, then reverse it later, the mistake and correction will be included when you replay the macro unless you edit the macro (see “Working in the Visual Basic IDE”). To include menu commands in the macro, just make menu selections as you normally would.
TIP
When you format text in a macro, choose the formatting options from a Format Cells dialog box rather than clicking toolbar buttons to select font style and alignment. If you use the toggle buttons, the results when you run the macro are unpredictable: if selected cells are already italicized, clicking the Italics button turns italics off.
4002c21.qxd 7/17/01 3:12 PM Page 647
When you are finished entering all the steps in the macro, click the Stop Recording button on the Stop Recording toolbar. The toolbar will close automatically. You don’t need to do anything special to save the macro now. Local macros are saved when you save the workbook. Excel saves global macros when you end your Excel session.
Absolute and Relative Cell References in Macros In Excel macros, all cell references are absolute by default. If you click in a cell during macro recording, the macro will select that cell each time you play it back. This is not always useful. For example, you might want a macro to format selected cells and move to the cell below the selection. When you record the macro, the cell below the selection is J22. But each time you play the macro, you don’t want Excel to select J22; you want to select the cell below the cells you just formatted. To use relative cell references, click the Use Relative References button on the Stop Recording toolbar. The macro will record references relative to the current cell until you click the button again to turn relative references off. Then you can record other actions using absolute references.
Running Macros from the Macros Dialog Box To run a macro, choose Tools Macro Macros to open the Macro dialog box. The Macro dialog box is shown in Figure 21.2. Select the macro from the list and click the Run button. The macro will execute. You can’t enter text or choose menu options while the macro is executing. When the macro is done playing, Excel will return control to you. It’s a good idea to save any open workbooks before you run a new macro. If you’ve made a mistake during recording, the playback results may not be what you expected.
TIP If there is an error, you can record the macro again using the same name or delete the macro in the Macro dialog box. You may also have to click Undo a few times to back out of any problems the macro created.
647
PART
VII Automating Excel 2002 with Macros and VBA
Creating Macros in Excel
4002c21.qxd 7/17/01 3:12 PM Page 648
648
CHAPTER 21 • Automating Excel with Macros
FIGURE 21.2 Run macros directly from Excel’s Macro dialog box.
Terminating a Macro during Execution You can accidentally create a macro that won’t be able to run to completion because it gets caught in a loop. If, for example, you write a macro that subtracts 1 from the value in cell B10 until B10 > =20, it will run forever, continually subtracting, if the initial value in B10 is already less than 20. When a macro doesn’t end on its own, you need to be able to terminate it. If you need to stop a macro during execution, press Ctrl+Break. A Visual Basic dialog box will open, offering you options to End program execution or Debug the macro in the Visual Basic Editor. If Ctrl+Break doesn’t stop macro execution, press Ctrl+Alt+Del once to open the Close Program dialog box in Windows 95/98 (in Windows NT/2000 click the Task Manager button after the dialog box opens). Select the application that contains the macro, and click the End Task button. When you reopen the application, you’ll probably need to revert to the copy of the document that you saved before running the macro.
Deleting Macros There are two ways to delete a macro: by overwriting or by deleting. If you need to improve the way a recorded macro executes, record the macro again, using the same name. You are prompted to overwrite the existing macro with the new one. If you no
4002c21.qxd 7/17/01 3:12 PM Page 649
longer need a macro, choose Tools Macro Macros, select the macro from the macro list, and click the Delete button. The global macro workbook, PERSONAL.XLS, is open, but hidden, when Excel is running. You can’t delete macros from hidden workbooks using the Macro dialog box. To delete a macro from the global workbook, choose Window Unhide to open the Unhide dialog box:
Unhide the workbook, then open the Macro dialog box to delete the macro. If you’re feeling adventurous or are VB experienced, you might prefer to select the macro in the Macro dialog box and click Edit to open the Visual Basic Editor. Select all the lines of code in the macro and delete them to delete the macro.
NOTE
If the Unhide command is disabled, odds are there are no global macros; therefore, PERSONAL.XLS did not load with Excel 2002.
Opening a File That Contains Macros If you can add code to an Excel 2002 workbook, so can the people who write viruses. Viruses are self-replicating programs. When you open a workbook that contains a virus, the virus copies its code into the default Excel template, effectively becoming a global virus. From that point forward, every workbook you save using the template will be infected, which means that every file you give to someone else on a disk, by e-mail, or via the Internet will also contain the virus. Office XP does not include virus detection software; you’re responsible for installing anti-virus software on your computer. Your computer is at risk unless you never receive files from another computer via disk, CD, network, or Internet connection. (But then why would you even own a PC?) However, Excel scans workbooks to see if they contain macros. Based on your security settings, Excel 2002 disables the macros, notifies you that the workbook has macros, or does nothing. To view or
649
PART
VII Automating Excel 2002 with Macros and VBA
Creating Macros in Excel
4002c21.qxd 7/17/01 3:12 PM Page 650
650
CHAPTER 21 • Automating Excel with Macros
change your macro security settings, choose Tools Macro Security to open the Security dialog box.
If you run a lot of macros in Excel, choose Medium security. You can decide whether you want to open the workbook with macros enabled or disable them. Clicking the More Information button doesn’t give you more information about the macros in the workbook; it opens the Excel help topic on macros and security.
If you know that the workbook contains macros that you or a coworker put there, choose Enable. If, on the other hand, you received the workbook unsolicited in an e-mail message from a friend who just loves to pass along the latest hot item from the Internet, you should consider disabling the macros or not opening the file. Disabling the macros gives you an opportunity to look at them in the Visual Basic Editor without endangering your computer. If you decide the macros are legitimate, close the Visual Basic Editor, reopen the workbook, and choose Enable Macros.
4002c21.qxd 7/17/01 3:12 PM Page 651
TIP
If you receive workbooks from developers who digitally sign their work and you use Internet Explorer 4.0 or higher, you can bypass this process by adding the developer to your list of trusted sources. Open a workbook that contains macros digitally signed by the developer. On the Security tab of the Options dialog box, click the Macro Security button to open the Security dialog box. Enable the Always Trust Macros from This Source check box, then click OK. If there is no such check box, the macros in the workbook are not digitally signed.
A macro’s code includes the macro’s description. This is yet another good reason to always note your name and contact information when creating a macro: it gives other users less reason to delete the macro and a way to reach you if they’re still not sure.
Working in the Visual Basic IDE Excel 2002 macros are written in the Visual Basic programming language and directly accessible in the Visual Basic Editor. To examine or edit a macro, choose Tools Macros to open the Macros dialog box, select the macro you want to examine, then click the Edit button to open the Visual Basic Integrated Development Environment (IDE), also referred to as the VB Editor (see Figure 21.3). To go directly to the VB Editor from Excel, choose Tools Macro Visual Basic Editor. FIGURE 21.3 The Visual Basic IDE includes a Code window, the Project Explorer, and a Properties window.
651
PART
VII Automating Excel 2002 with Macros and VBA
Working in the Visual Basic IDE
4002c21.qxd 7/17/01 3:12 PM Page 652
652
CHAPTER 21 • Automating Excel with Macros
In Figure 21.3, the Project Explorer and Properties window are open to the left of the Code window. The Project Explorer shows all the open VBA projects. Every document can have one VBA project associated with it; the project is stored with the document. The project in Figure 21.3 has two types of project components: application objects (worksheets and a workbook) and a module. A module is a container for VB code. Each macro you create with the Macro Recorder is placed in a new module. Projects can include other types of objects, including forms for user interaction and references to templates or other documents.
TIP If you have lots of macros, the Project Explorer will quickly fill up with modules. Use cut-and-paste to move the macros to one module window, or use two or three modules to organize your macros by functionality, and then delete the empty modules. To delete a module, right-click it in the Project Explorer and choose Remove Module N from the shortcut menu. The Properties window displays the properties for the object selected in the Project Explorer; it will be familiar if you’ve designed tables, forms, or reports in Microsoft Access. The Code window displays code from the active component in the Project Explorer. Double-click a module or select the module and click the View Code button in the Project Explorer to display the module’s code in the Code window. If there are a number of macros in a module, select the macro name from the Procedure list at the top right of the Code window. The green lines of code that begin with apostrophes (‘) are remarks that explain the code. The code itself is displayed in the default text color, black. The code below is a simple Excel macro that selects and previews the first chart, Chart 1, in the active worksheet. We created the macro by recording two actions with the Macro Recorder: selecting the chart and clicking the Print Preview button on the Standard toolbar.
NOTE
Although this is a simple macro, recording it is a bit counterintuitive. You can’t click Stop Recording when you’re in Print Preview. You have to close the Preview window and then click the Stop Recording button. Logic tells you that when you run the macro, you’ll quickly go to Print Preview and exit. But that’s not how the macro runs. It leaves you in Print Preview—which is what you want—even though it doesn’t seem that it should.
4002c21.qxd 7/17/01 3:12 PM Page 653
The Macro Recorder generated this Visual Basic code: Sub basPrintChartOnly() ‘ ‘ basPrintChartOnly Macro ‘ Macro recorded 2/15/2001 by Gini Courter ‘ ActiveSheet.ChartObjects(“Chart 1”).Activate ActiveWindow.SelectedSheets.PrintPreview End Sub You need to be slightly familiar with the VB IDE if you want to edit macros created with the Macro Recorder or if you want to create macros that can’t be recorded. The Macro Recorder is limited to elements that are visible in the interface. There are other objects that are best manipulated, or can only be manipulated, by writing code.
NOTE
You’ll find more information on Visual Basic in the chapters that follow.
The code begins with the word Sub (for subroutine) and ends with End Sub. Following Sub is the macro name we entered in the Record Macro dialog box and a set of parentheses like those used to enclose arguments in an Excel function. The username, the date recorded, and other remarks are from the Description in the Record Macro dialog box. Two lines of code follow. The first line activates Chart 1 on the active sheet: ActiveSheet.ChartObjects(“Chart 1”).Activate ActiveSheet.ChartObjects(“Chart 1”) identifies the object; Activate is a method of the object. Methods are actions for objects. Activate is a method common to many objects, because almost any Excel object—from a cell to a toolbar button— can be activated. The second line sends the selected sheets to Print Preview. Because the chart is selected, the preview only includes the chart—that’s how Excel always behaves when you print or preview with a chart selected. The object is ActiveWindow. SelectedSheets, and PrintPreview is the method being used: ActiveWindow.SelectedSheets.PrintPreview When the VB interpreter hits the End Sub line, it’s finished running the macro. It returns control to Excel, which is displaying Chart 1 in the Print Preview window. The user can choose to print the chart or close the Preview window.
653
PART
VII Automating Excel 2002 with Macros and VBA
Working in the Visual Basic IDE
4002c21.qxd 7/17/01 3:12 PM Page 654
654
CHAPTER 21 • Automating Excel with Macros
You don’t need to know much about programming to do some simple editing here. For example, you can have the macro preview Chart 2 simply by changing the name of the chart object. You can copy this macro two or three times and create macros to preview different chart objects in the active worksheet. (Each macro must have a different name, so be sure to change the macro name following the word Sub in the first line of the macro.) When you finish editing, close the Visual Basic window to save your changes and return to Excel. The formatting macro created earlier in this chapter (and shown in the VB IDE in Figure 21.3) created a lot of extra code. We changed two settings on the Font page and one setting on the Alignment page of the Format Cells dialog box, but Excel recorded the settings for every option on both pages: Sub mcrCenterUpsizeTitles() ‘ ‘ mcrCenterUpsizeTitles Macro ‘ Gini Courter, TRIAD Consulting, 3/1/2001. This macro merges and centers the selection and applies Times 14 pt ‘ With Selection .HorizontalAlignment = xlCenter .VerticalAlignment = xlBottom .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With Selection.Merge With Selection.Font .Name = “Times New Roman” .Size = 10 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone
4002c21.qxd 7/17/01 3:12 PM Page 655
.ColorIndex = xlAutomatic End With With Selection.Font .Name = “Times New Roman” .Size = 14 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ColorIndex = xlAutomatic End With End Sub The macro recorder records properties in the order in which they appear as you proceed through the recording sequence, so your code may look slightly different than that listed. You can edit this macro to delete the settings that you don’t want the macro to change—options like underline, color, strikethrough, or outline font—by deleting the entire line that includes the name of the setting: Sub mcrCenterUpsizeTitles() ‘ ‘ mcrCenterUpsizeTitles Macro ‘ Gini Courter, TRIAD Consulting, 3/1/2001. This macro merges and centers the selection and applies Times 14 pt ‘ With Selection .HorizontalAlignment = xlCenter End With Selection.Merge With Selection.Font .Name = “Times New Roman” .Size = 14 End With End Sub When you’re finished editing, choose File Close and Return to Microsoft Excel to close the VB Editor.
655
PART
VII Automating Excel 2002 with Macros and VBA
Working in the Visual Basic IDE
4002c21.qxd 7/17/01 3:12 PM Page 656
656
CHAPTER 21 • Automating Excel with Macros
Now that you know how to create and edit macros in Excel, let’s examine ways to make the macros accessible to the people who use your workbooks.
Making Macros Easy to Use Most users aren’t anxious to memorize additional commands or open a lot of extra dialog boxes to complete a task. If you create a macro that saves three steps, but requires the user to complete three different steps to run the macro, you’ve wasted your time. Running a macro from the Macros dialog box always takes at least four steps (Tools Macro Macros, then double-click the macro name). More importantly, you don’t want inexperienced, curious users kicking around in the Macro dialog box, checking to see what exciting functionality lurks behind the Delete and Edit buttons. There are three other, better ways to have users run macros: from a menu, a toolbar, or command button. We’ll examine all three methods in this section.
TIP
Are you creating navigational macros—macros that move to a particular sheet and cell, then wait for user input? If you are, this is a good time to stop. Excel 2002 supports hyperlinks, which anyone who uses the Web knows how to use. See Chapter 14, “Creating Worksheets for Other Users,” for more information on hyperlinks.
Design Decisions for the User Interface The decisions about where to store macros and where to place buttons or menu items that let users run the macros are related. Users should always be able to find the commands for available macros. And they should only be able to see commands if the macros are available; clicking a button for a macro that Excel can’t find will result in an error message. For example, let’s say you’re creating macros to automate an Excel workbook that will be distributed to customers, colleagues, or suppliers at a variety of locations. In this case, you should store the macros locally in the workbook you’ll distribute. The buttons that users click to run the macros should be displayed in the distributed workbook and should not be visible if your client switches from your workbook to another open workbook. To achieve this, you can create a custom toolbar that will be turned on when the workbook opens and off when it closes, or add freestanding command buttons that run the macro. In either case, commands that run macros should be available always and only when the macros are available.
4002c21.qxd 7/17/01 3:12 PM Page 657
You may also create macros that you use in a variety of documents. For example, you may create a macro that adds a custom footer to Excel workbooks with the date, time, file name, and the text © All rights reserved with the year and your company and department name. This is a good candidate for a global macro. Store the macro in the Personal Macro Workbook and place a button or menu command that runs the macro on one of the command bars that is displayed by default: the Excel 2002 menu, Standard toolbar, or Formatting toolbar.
NOTE
If you want to create a custom menu or toolbar, see “Creating a Custom Toolbar” at the end of this chapter, then refer to Chapter 24, “Creating an Excel Application,” for information on using Visual Basic to hide and display custom menus and toolbars.
Customizing the Command Bars From Excel’s point of view, there are few differences between menus and toolbars. Menus and toolbars are both members of the command bar family of objects. Menu items and toolbar buttons are generically referred to as commands or command items.
TIP
There is one major difference between the menu bar and toolbars: you can hide toolbars, but you can’t hide the menu bar.
Before we create new menu items and toolbar buttons, we’ll quickly review the steps required to customize menus and toolbars by adding existing items from the Excel command library: 1. Choose View Toolbars Customize, Tools Customize, or right-click the menu or a toolbar and choose Customize to open the Customize dialog box. Click the Commands tab, which is shown in Figure 21.4. 2. To add a command to a command bar, select the type of command you want to add from the Categories list. Drag the command from the Commands list and drop it on a toolbar or menu. 3. To delete a command, drag the item or button off the menu or toolbar and drop it in the worksheet.
657
PART
VII Automating Excel 2002 with Macros and VBA
Making Macros Easy to Use
4002c21.qxd 7/17/01 3:12 PM Page 658
658
CHAPTER 21 • Automating Excel with Macros
FIGURE 21.4 Drag commands from the Customize dialog box to a menu or toolbar.
4. Use drag and drop to move commands within or between toolbars or menus. Hold the Ctrl key while dropping the command to copy the command. 5. Click OK when you’re finished rearranging the command bars. In Excel 2002, menus and toolbars are functionally interchangeable: a toolbar can include a menu, and a menu can include toolbar buttons images. For example, let’s look at the Hyperlink command on the Insert menu:
The Hyperlink menu item includes the following: The Command Name The text Hyperlink, which the user can click on to choose this command. The name is followed by ellipses (…), because choosing this command opens a dialog box that requires a user to enter parameters. If your macro displays a dialog box that asks for user input other than clicking OK or Cancel, append an ellipses to the name. A Keyboard Accelerator The key combination Alt+I (I is the underlined letter in the Hyperlink command), which can be used to select the menu item if the Insert menu is open. The Shortcut Key Ctrl+K, listed with the menu item, which can be used to insert a hyperlink without opening the menu. A Button Image
Helps the user find this command when it appears on a toolbar.
4002c21.qxd 7/17/01 3:12 PM Page 659
A general rule is that if you want to use text to describe the command, it belongs on a menu; if you want to use an icon only, make it a toolbar button. Always include a menu shortcut; only assign a shortcut key to commands used very frequently. If the command appears on a menu and a toolbar, add the button image to the menu command for consistency.
TIP While you can add commands to the Standard and Formatting toolbars, you can’t guarantee that they’ll be displayed. The personalized toolbars feature moves less frequently used buttons off the toolbars. To really ensure that choices are available for users, either place them on the menu or create and display a custom toolbar. Whether you’re adding a command to run a macro to a toolbar or the menu bar, you’ll work in the Customize dialog box. Right-click any menu or toolbar and choose Customize, or choose View Toolbars Customize or Tools Customize to open the dialog box, then click the Commands tab. In the Categories list, select Macros to see the two choices in the Commands list: Custom Menu Item or Custom Button, as shown in Figure 21.5. FIGURE 21.5 Use the Customize dialog box to create custom menu items and toolbar buttons.
659
PART
VII Automating Excel 2002 with Macros and VBA
Making Macros Easy to Use
4002c21.qxd 7/17/01 3:12 PM Page 660
660
CHAPTER 21 • Automating Excel with Macros
Creating a Custom Menu Item or Toolbar Button Create a custom menu item or toolbar button to accomplish the following: • Add a command to run a global macro to the Excel menu bar • Add a command to run a local macro to a custom toolbar To create a custom menu item, drag the Custom Menu Item button from the Customize dialog box. Point to the menu that you want to add the item to and wait for the menu to open; for example, to add a macro to the Tools menu, drag Custom Menu Item from the Customize dialog box and point to the word Tools on the menu bar. After a pause, the Tools menu opens. Point to the position where the custom menu item should appear, and release the mouse button. Although you can position the Custom Menu Item in a submenu, we don’t recommend it. You’re trying to save steps and navigating to a submenu defeats that purpose. Additionally, the user isn’t as likely to find the command in a submenu. To create a custom toolbar button, drag Custom Button from the Customize dialog box and drop it on a toolbar.
Modifying a Custom Item or Button Right-click the newly positioned Custom Menu Item or Custom Button, or click the Modify Selection button in the Customize dialog box to open the Modify Selection shortcut menu, shown in Figure 21.6. FIGURE 21.6 Open the Modify Selection menu to set the name and assign a macro to the command.
The shortcut menu is used for customizing both menu commands and toolbar buttons. Table 21.1 describes the commands on the Modify Selection menu.
4002c21.qxd 7/18/01 2:37 PM Page 661
Making Macros Easy to Use
Menu Item Options Description
VII
Reset
Restores the original menu command text or button image
Delete
Removes the menu item or button
Option
Interface Options Name
Command name; displayed on menus
Copy Button Image
Copies the button image to the Clipboard
Paste Button Image
Pastes the button image from the Clipboard
Reset Button Image
Restores the item’s original button image
Edit Button Image
Opens the Image Editor so you can modify or customize the current button image
Change Button Image
Opens a palette of 42 compelling, well-designed images that you can use (or not) on your custom buttons
Default Style
Applies the default style: for buttons, the button image is displayed; for menu items, the menu text and the button image are both displayed
Text Only (Always)
Uses the Name text as the caption in both menus and toolbars; omits the image in both settings
Text Only (in Menus)
Uses the Name text as the command caption on menus only
Image and Text
Uses the button image and text on both menus and toolbars
Begin a Group
Adds a separator to group commands on a menu or toolbar
Action Options
www
PART
Automating Excel 2002 with Macros and VBA
TABLE 21.1
661
Assign Hyperlink
Inserts an image or open a document
Assign Macro
Runs a macro
Excel’s Button Editor is a fairly rudimentary tool that creates 16 × 16 pixel images. If you need to create button images and icons, visit the Mastering Excel 2002 page on the Sybex website for links to more powerful button image creation tools (like Microangelo).
Entering Command Text In the Name text box on the Modify Selection menu, enter the text to appear on the menu. Nearly all of the commands on Excel’s menu have a keyboard accelerator: a letter that the user can press while holding the Alt key to invoke the command. Within a menu, each command must use a different letter as an accelerator, and the letters are not case sensitive. To designate a letter as the keyboard accelerator, precede it with the ampersand symbol (&). When the menu is displayed, the accelerator letter is underlined.
4002c21.qxd 7/17/01 3:12 PM Page 662
662
CHAPTER 21 • Automating Excel with Macros
TIP
Enter a name even if you’re only creating a toolbar button. If you assign a macro to the button, the Name is used as the button’s ToolTip.
Assigning a Macro to a Command Choose Assign Macro from the Modify Selection menu to open the Assign Macro dialog box, shown in Figure 21.7. In the Macros In drop-down list, choose This Workbook for a local macro or Personal Macro Workbook to assign a global macro. Select the macro from the list and click OK to assign the macro to the menu item. FIGURE 21.7 Select the appropriate workbook in the Assign Macro dialog box, then select the macro to assign to the menu item.
If you rename a macro that’s assigned to a menu item or toolbar button, return to the Assign Macro dialog box and assign the macro using its new name.
Assigning a Hyperlink to a Command
Hyperlinks are used to navigate within and between documents. In Excel 2002, the Assign Hyperlink feature has been expanded to include inserting graphic files. Assign a hyperlink to a menu item or toolbar button to do the following: • Open an Excel workbook • Launch the default browser and open an HTML document • Open any document that has an assigned application installed on the computer • Create a new document • Send an e-mail • Insert an image
4002c21.qxd 7/17/01 3:12 PM Page 663
You can’t use assign hyperlink to point to another place in the workbook, so command buttons and menu items cannot be used for internal navigation. Navigational hyperlinks are created in the workbook with Insert Hyperlink.
NOTE
See Chapter 14, “Creating Worksheets for Other Users,” for more on creating
hyperlinks.
When you assign a macro to a button, the button’s Name is used as the ToolTip. When you assign a hyperlink to a button, the hyperlink address (URL or file path) is displayed as the ToolTip. Opening or Creating a File or Sending an E-mail To assign a hyperlink that opens a file, creates a new document, or opens an e-mail message, open the Modify Selection menu and then choose Assign Hyperlink Open to display the Assign Hyperlink: Open dialog box, shown in Figure 21.8. In the Link To bar, choose Existing File or Web Page, Create New Document, or E-mail Address. FIGURE 21.8 Assign a hyperlink that creates a file or that opens a file or e-mail message form.
Inserting a Picture Assign a hyperlink to a command to make it easy for users to insert frequently used images (like logos) in Excel worksheets. On the Modify Selection menu, choose Assign Hyperlink Insert Picture to open the Assign Hyperlink: Insert Picture dialog box shown in Figure 21.9. Browse to select the image file, then click OK to create the assignment.
663
PART
VII Automating Excel 2002 with Macros and VBA
Making Macros Easy to Use
4002c21.qxd 7/17/01 3:12 PM Page 664
664
CHAPTER 21 • Automating Excel with Macros
FIGURE 21.9 Assign a hyperlink that inserts a frequently used image like a company logo.
Creating a New Menu Windows users like menus. If a user can’t remember where to find a command, they often start with File and open each menu in turn, hoping to locate the lost command. If you’re adding a number of macros to a worksheet, take advantage of this frequently observed user behavior: create a new menu and add the macros to the menu.
NOTE
If macros are stored locally, you need to create a custom toolbar or menu that you can hide and display with Visual Basic code. See Chapter 24 for more information.
In Windows applications, the first menu should be File, then Edit, then View (if the application uses these menu items. Window and Help menus appear in that order on the right end of the menu. Your new menu should be added directly to the left of the Window menu to maintain consistency. Follow these steps to add a new menu, which you can then populate with macros: 1. Right-click any toolbar or menu and choose Customize to open the Customize dialog box. 2. On the Commands tab, choose New Menu in the Categories list. 3. Drag the New Menu command from the Commands window and drop it between Data and Window on the Excel menu bar.
4002c21.qxd 7/17/01 3:12 PM Page 665
4. Click the Modify Selection button in the Customize dialog box to open the shortcut menu. 5. In the Name text box, enter a name for the menu. Type the ampersand (&) symbol in front of the letter that will be used with the Alt key to open the menu. The letter does not have to be the first letter of the word, and cannot duplicate those already used: F for File, E for Edit and so on.
6. Begin adding commands to the menu (see “Modifying a Custom Item or Button” earlier in this chapter).
Creating a Custom Toolbar To create a toolbar, open the Customize dialog box (View Toolbars Customize). On the Toolbars tab, shown in Figure 21.10, you can display or hide toolbars, delete custom toolbars, reset toolbars, and attach toolbars from other open workbooks. FIGURE 21.10 Create custom toolbars in the Customize dialog box.
Click the New button to open the New Toolbar dialog box and enter a name for the toolbar. The new toolbar with room for a single button appears on in the workbook window.
665
PART
VII Automating Excel 2002 with Macros and VBA
Making Macros Easy to Use
4002c21.qxd 7/17/01 3:12 PM Page 666
666
CHAPTER 21 • Automating Excel with Macros
Add buttons to the toolbar from the Commands page of the Customize dialog box. When you have finished adding buttons, click OK to close the dialog box.
TIP
Custom toolbars are sometimes used to replace one of the default toolbars. If you’re going to display your custom toolbar instead of the Formatting toolbar, be sure that your custom toolbar includes default buttons that users will need.
Attaching and Resetting Toolbars Use the Attach feature to copy your custom toolbars from one workbook to another. Open the workbook that contains the custom toolbar. In the workbook that you want to copy the toolbar into, open the Customize dialog box and click the Attach button on the Toolbars page to open the Attach Toolbars dialog box shown in Figure 21.11. Select the toolbar or toolbars you want to attach, and click the Copy button to copy them to the current workbook. Click OK to close the Attach Toolbars dialog box. FIGURE 21.11 Use Attach to copy a custom toolbar from another workbook.
The Reset button in the Customize dialog box returns a command bar to its default settings by removing custom buttons and menu items and restoring buttons previously removed. Custom command bars cannot be reset; if a user tinkers with your custom toolbar, you need to re-create it.
4002c21.qxd 7/17/01 3:12 PM Page 667
TIP
If you keep a copy of all of your custom toolbars in a backup workbook that other users can’t open (named, for example, Custom Tools.xls), you can delete the useless toolbar and attach the correct toolbar from Custom Tools.xls.
To reset a toolbar or the Worksheet Menu bar, select the command bar from the list on the Toolbars tab of the Customize dialog box, and click Reset. You’ll be prompted to confirm the reset action.
Running a Macro from a Form Button In the interests of full disclosure we’ll start by noting that some application developers believe that all commands belong on a toolbar or menu, and discourage the use of form buttons in the user interface. And not many people will argue passionately for the other side in this argument. However, there are reasons you might choose to use form buttons, particularly with local macros. Developers who are using ActiveX controls on worksheets might choose to use form buttons on a chart sheet because chart sheets don’t support ActiveX controls. Users who don’t want to deal with Visual Basic code to hide and display custom toolbars might choose form buttons because they are easy to create and modify.
NOTE
You’ll find a comparison of ActiveX and Form controls and information on using Excel’s Form controls in Chapter 15, “Creating Forms.”
To access the form controls, open the Forms toolbar (View Toolbars Forms). Click the Button control, then click or drag in the worksheet to create the form button. When you release the mouse button, the Assign Macro dialog box automatically opens. Choose a macro from the Macros list and click OK to assign the macro, or click the Record button to begin recording a new macro to assign to the form button. To edit the button name, drag the button text to select it and begin typing. Move and resize the button as you would any object. To change other button properties, make sure you are not in edit mode and right-click the button and choose Format Control from the shortcut menu to open the Format Control dialog box shown in Figure 21.12.
667
PART
VII Automating Excel 2002 with Macros and VBA
Making Macros Easy to Use
4002c21.qxd 7/17/01 3:12 PM Page 668
668
CHAPTER 21 • Automating Excel with Macros
FIGURE 21.12 Set button options in the Format Control dialog box.
Pay particular attention to the Properties page. These settings determine whether the button will print as part of the worksheet and how the button behaves when a user resizes or hides the column or row that the button is positioned in. When you have finished formatting the button control, close the dialog box and click somewhere else in the worksheet to deselect the form button. When the button isn’t selected, clicking the button fires up the macro. To edit the button control’s properties, select the button by right-clicking it. To change the button text, right-click the button then press the Escape key to close the menu but leave the button selected.
4002c22.qxd 7/18/01 12:33 AM Page 669
CHAPTER
22
USING VISUAL BASIC WITH EXCEL F E ATU R I NG
An introduction to automation
What is Visual Basic?
Making use of Visual Basic
Getting familiar with the Integrated Development Environment
Creating UserForms
Controls, Events, and Properties
Writing your first programming code
Debugging your program
Additional Visual Basic Resources
4002c22.qxd 7/18/01 12:33 AM Page 670
utomation has always been the promise of computers: get more work done as the computer toils away at repetitive tasks. However, in order to have your computer perform a series of actions when you click a button, you need to tell it what to do in words that it understands. What if your company has a need for a specialized contact sheet, needs to speed up the budget approval system, or needs to collect disparate versions of a Word document and create a report on the changes as quickly as possible? You can’t simply tell your computer to go do these things as you would tell an assistant. You need to write a program. This is where Visual Basic (VB) and its offspring Visual Basic for Applications (VBA) and Visual Basic Script (VBScript) come in. Now, don’t shy away. Microsoft has worked hard to make VB programming relatively easy, using English language terms strung together, to tell your computer what to do. For our Excel examples and custom applications, we will be using VBA, a streamlined version of Visual Basic designed specially for working in Microsoft Office. VBScript was created to facilitate Internet and communications tasks and is used in Microsoft Outlook.
a NOTE
VB and VBA are identical in syntax. Microsoft, however, felt it would be smart to ship VBA with a trimmed-down version of the VB programming interface, called the Integrated Development Environment (IDE), which focuses on augmenting the capabilities of a host application (in this case Excel) rather than on creating freestanding applications, which it cannot do.
In Chapter 21, “Automating Excel 2002 with Macros,” we took a quick look at the Visual Basic Integrated Development Environment (IDE) as an editor for macros created with Excel’s Macro Recorder. In this chapter, we’ll build and run a small Visual Basic application that includes a type of VB form called a UserForm, a form that can be customized to include other objects like text boxes, check boxes, and command buttons. Small applications in any language are called applets. The applet we’ll look at is called Hello World! and has a long history in the world of programming as the first program many people create when learning a new language. We will also learn how to automate Microsoft Word from Excel. In Chapter 24, “Creating an Excel Application,” we’ll use our new knowledge to create a custom Excel application.
4002c22.qxd 7/18/01 12:33 AM Page 671
What Is Visual Basic? To understand what VB is, we need to understand what it does. Within the scope of its abilities, VB will perform the tasks you ask of it. VB cannot be used to tell your computer to make coffee at 7:00 A.M. every morning unless your computer is actually capable of controlling a coffee maker. (No Java jokes, please.) However, you will probably not be seeking a programming solution for coffee making unless you’re spending time at a ubiquitous computing shop. You’ll use VB to automate tasks and extend the capabilities of Excel. Excel is already a very powerful spreadsheet and calculation program that can solve, evaluate, display, graph, and store a great variety of data. Microsoft realized, though, that there was no way they could anticipate the exact needs of all their users, so they allow you to do it. Most often you will do this by creating a UserForm or developing a custom Function.
NOTE A control is an object, like a button or a text field, that you add to a form and that can modify the form’s behavior. For example, the OK buttons that show up in most dialog boxes are controls. When you place a control on a form, you must also add programming code to tell the control what to do. We will examine coding later in this chapter. Behind each control you add code that makes the control do what you wish. If the control you placed on your form was a CommandButton (one of the control choices), you could, for example, program that button to open a Save As dialog box to automatically let you retain an additional copy of outgoing documents in a folder of your choice.
NOTE An event is a user- or system-generated action, such as the user clicking a button or a CD-ROM to activate the AutoPlay software. Visual Basic is called an event-driven programming language because it responds to events. You place control objects on your forms and then program them to handle specific events. In the case of a command button, you would program it to respond to a Click event: the event that happens when a user mouses over to and clicks a button. All of this is created in the Visual Basic IDE, shown in Figure 22.1. You will be entering the VBA IDE and creating your own application in the section “Hello World” later in this chapter.
671
PART
VII Automating Excel 2002 with Macros and VBA
What Is Visual Basic?
4002c22.qxd 7/18/01 12:33 AM Page 672
672
CHAPTER 22 • Using Visual Basic with Excel
FIGURE 22.1 The Visual Basic environment
In essence, each control has its own capabilities and can be coded to operate independently of everything else on the form. As an example, we’ll look at the ubiquitous OK button, present on most dialog boxes. To create an OK button in VB you would simply click on the CommandButton button in the toolbox, drag the cursor to the form, and drop. This procedure creates a button called CommandButton1, as shown in Figure 22.2. For each control there are properties that define how the control works. In Figure 22.2, the properties for the selected command are displayed in a separate window, in the lower left corner of the VBA environment. The properties for the CommandButton control are simple, and you use them to define the way the control presents itself. In Figure 22.2, the Default property of CommandButton1 is set to True, meaning that if you were to open this Form in an application and press the Enter key, this button would be clicked by default.
4002c22.qxd 7/18/01 12:33 AM Page 673
What Is Visual Basic?
FIGURE 22.2
673
PART
A new CommandButton on a form, with Default property set to True
Automating Excel 2002 with Macros and VBA
VII
If we created a simple form, placed a CommandButton control and a TextBox control on it, and programmed it to put something in the TextBox control when the CommandButton is clicked, we would be looking at a simple example of programming in action. If, on the other hand, we only included the controls and omitted the code, nothing would happen. Why? Because there is no code to tell the button control what to do. You would click the button, and nothing would happen. It’s safe to say that users don’t really appreciate this type of form very much. You can think of writing code as sending a letter of instructions to someone. Assuming we were in the VBA IDE, we would begin that letter by double-clicking the CommandButton control to open the Code Editor, which automatically adds the following code (which, in the world of programmers, is called a snippet or stub): Private Sub CommandButton1_click() End Sub
The IDE assumes that you want to add code to the control you just double-clicked to open. This snippet is a procedural framework, a structure that defines the beginning and the end of what is called a procedure.
NOTE
A procedure is a complete and independent piece of working code. Procedures can be triggered by an event or called from other procedures.
4002c22.qxd 7/18/01 12:33 AM Page 674
674
CHAPTER 22 • Using Visual Basic with Excel
In that code snippet, Private tells the control that this code will only be available to the form that it is being constructed in. Sub is short for subroutine and identifies the code as a procedure.
NOTE
The terms subroutine and function both refer to types of procedures in VB. The difference is that a function, as in Excel, returns a value to a variable and subroutines, like the macros created in Chapter 21, take actions but don’t return values.
CommandButton1_Click identifies the CommandButton by name and indicates what the procedure expects of the control: a click. Each control receives a unique name when it is created so it can be individually identified later. You can rename your controls anything you like, as long as each name is unique. It is also a good idea to make the names easily recognizable so that you can readily recognize their purpose when you go back to the code next year. End Sub indicates the official close of the procedure. To get the command button to close the window when it is clicked, we just need to add one command between the Private Sub and End Sub lines: Unload Me. The whole completed procedure will look like this: Private Sub CommandButton1_click() Unload Me End Sub
If you were writing this as a letter of instructions in English, it might read something like this: RE: Confidential To Do List Dear CommandButton1, If you get clicked, close the window you occupy. Sincerely, Programmer
Now that we’ve added a command in language that VB can understand, it will perform the action we ask of it. Clicking the small blue arrow button on the toolbar causes the form to run. This is the same as selecting Run Run Macro. If we clicked the command button, we would see that the form disappears.
4002c22.qxd 7/18/01 12:33 AM Page 675
NOTE
You can create code without first creating a button. To create a new macro, choose Tools Macro Macros and type a name for the macro. Make sure that the names you give macros are short, descriptive, and contain no spaces (you can, however, use underscores). If the name you enter meets these criteria and isn’t already used in the current module, the Create button will be enabled. Click the Create button to open the Visual Basic Editor.
Making Use of Visual Basic We just took a quick look at what VB is and how easy it can be to use it. Now, we’re going to examine what VB can be used for. To begin, let’s further examine what VB can do as a language. VB is a complete and powerful event-driven language, which means that each component, like our example button, can operate independently of the rest of the program. When an event occurs, VB responds by running the procedure that was defined for that specific event, if any; if no procedure was defined for the event, nothing happens. These event procedures are tied to the controls that you place on your forms to permit users to interact with the application (for example, the Common Dialogs control, which adds the ability to use system-based Open and Save dialog boxes with only a few lines of code). Going back to our example in the previous section, we told CommandButton1 to execute the code related to it when it was clicked. The click was the event, and the code executed is the event procedure.
NOTE
Event-driven programming should not be confused with object-oriented programming languages. A programming language can be event driven, object oriented, or both. Visual Basic is event driven, and almost object oriented. With Visual Basic, you can create objects with properties and behaviors that can be used as the basis for other “child” objects that inherit the properties and behaviors of the “parent” object. VB does not meet all the requirements of an object-oriented language like C++, but each version comes closer to meeting the requirements. VB is a very powerful programming environment used to create commercial applications.
Generally, VB is considered a Rapid Application Development (RAD) tool, with which custom solutions can be prototyped, debugged, and built much quicker than
675
PART
VII Automating Excel 2002 with Macros and VBA
Making Use of Visual Basic
4002c22.qxd 7/18/01 12:33 AM Page 676
676
CHAPTER 22 • Using Visual Basic with Excel
with other languages. One of the more common reasons VB is deployed is to provide fast development of database front-end applications. Additional reasons include the following: • You can automate how forms work, specify customized handling of new data, or create new data. • You can create customized Excel forms and personalized applications. • You can access data from Excel while in other applications and vice versa.
The Big Picture Before we do anything at all with the computer, we need to determine exactly what we want the computer to do and how we are going to accomplish this using VB. Very few professional programmers sit down and start coding with no idea of what their goal is. If you want to develop a good program in the most efficient way, you need a process. There are several steps in the program development process: 1. Define the application. 2. Define the programmatic requirements. 3. Define the interface. 4. Compose the application. 5. Debug and test the application. 6. Build and distribute the application. Let’s take a closer look at this to-do list, which is generally referred to as a development cycle. The term cycle implies that this process happens more than once, and it does in the course of developing a large application or improving an application. You finish testing your application, release it to users, and then begin planning extensions or improvements. First we need to define the application. This is when you hammer out the most important details of your application and nail down just what your application will do. In this case, we’ve already decided what we’re going to do. For the purposes of this exercise, we’ll be using the classic beginners’ program, Hello World! This little application performs a minor task, but it provides an easy framework for understanding Visual Basic. The task is simple: create an application that displays a message when you click a button.
4002c22.qxd 7/18/01 12:33 AM Page 677
Second, we need to define the programmatic requirements. At this point we need to take inventory of our needs and trim them down to the most necessary. It’s a cycle, so we can always go back and add functionality; initially, we want to separate the requirements from the fluff. For our project, our basic requirements are the following: display a button to click, a text box so users can view the message, and a window (form) to display them on. Third, we need to define the interface: the part of the application that the user interacts with. Interface design is a critical component, so don’t jump into it until you understand the concept behind the application. If you are not entirely clear on what your program will do, you can’t be clear on an interface design. (Programs with an outstanding interface but no real functionality are referred to “smoke and mirrors.”) Our applet has a simple but easy-to-understand interface: a form with a CommandButton control and a TextBox control. The fourth step is to actually compose the application. Only after you’ve set down what you want your application to do, what programmatic components it should contain, and how the user will interact with it can you really start to create it. This is the step in which you’ll create the interface that you decided on in the previous step. As you place each control, you will modify its properties to suit your needs. Once this is completed, you can create the operational code that makes the application work. For our project, we’ve included a step-by-step tutorial on the construction of the Hello World! program. The fifth step is to debug and test the application. As you are working on your application you will run it from time to time to make sure you have not missed anything or made an error. When you do this in VBA’s IDE, you are not actually compiling the code (translating it into a form that the computer can read more easily) as you are required to do with many IDEs. The code you have written is actually interpreted as it’s read by the computer. Interpreting the code allows the application to run without waiting for all of your code to compile. This also allows you to debug your source code while the application is running.
NOTE
When VB compiles your code, it actually strips out all formatting and comments and creates a more streamlined version of the program for the computer to run. The result is called P-Code. Unlike compiling in languages such as C/C++ or Pascal, this process does not convert the program code into another language.
Although this can be the end of the development process, that’s only if your application is perfect the first time around—an unlikely event except in the case of very
677
PART
VII Automating Excel 2002 with Macros and VBA
The Big Picture
4002c22.qxd 7/18/01 12:33 AM Page 678
678
CHAPTER 22 • Using Visual Basic with Excel
simple applications like Hello World! If you find a bug, you go back one or more steps depending on whether minor or major changes are needed to fix the problem. At a minimum, you need to repair the problem and run and test the application again. Some applications actually work with minor or occasional bugs in them until a user notes the combination of events that triggers the bug. Most commercial applications ship this way, despite exhaustive beta testing. The bugs that affect operation or that damage files are the most important to fix. Then come the less problematic operational bugs, which make the application less usable but do not cause it to crash. Finally, you can deal with the relatively minor cosmetic bugs, which are unpleasant to look at but don’t cause any actual programmatic problems. Our Hello World! applet is small enough that an experienced programmer could create it with no bugs the first time around. However, we will slip a few deliberate errors into the code so you can see how VBA handles them and reports their activities to you. And no matter how experienced you become, you always need to test even simple programs. Finally, we will build and distribute our application. The term build refers to the process of making a program ready for an end-user to use. In other languages, projects must be built before the user can even run them. In VB, however, the code is interpreted, as we mentioned previously, so when we talk about compiling VB code, what we really mean is that the code is pre-interpreted, allowing it to run somewhat faster. Compiling will also identify any lingering syntax errors, because every line of code is interpreted and checked for syntactical accuracy.
NOTE
Until you compile the program, VBA runs an application interpretively. That means it only compiles the lines of code that it uses and nothing else.
Hello World! We’re now ready to begin with the fourth step: composing the program, which will consist of a dialog box with a TextBox and a CommandButton control. When the button is clicked, the program will display a text string in the TextBox control. We’ll use the Visual Basic Integrated Development Environment to create our program. Visual Basic’s IDE is a programming environment in which you manage, create, and compile your projects. The IDE provides you with the windows and tools you
4002c22.qxd 7/18/01 12:33 AM Page 679
need for programming. The VBA IDE is somewhat trimmed down from the full VB version, but it maintains most of the same functionality. To get to the VBA IDE, follow these two steps: 1. Start Excel. 2. Select Tools Macro Visual Basic Editor. Or you can press Alt+F11.
FIGURE 22.3 The VBA IDE for Excel
This opens the VBA IDE as shown in Figure 22.3. To the left, there are two panes: the top one displays the Project Explorer, and the bottom one is the Properties window, which displays the selected object’s properties and makes them available for editing. The large gray area is where you’ll actually create your form, and the relatively familiar toolbars are just up above. There are other panes you can use during code writing and debugging: Object Browser Allows you to browse through all available objects in your project and their properties, methods and events. You can also see the procedures and constants that are available from object libraries in your project. Click the Object Browser button, select View Object Browser, or press F2 to open.
679
PART
VII Automating Excel 2002 with Macros and VBA
Hello World!
4002c22.qxd 7/18/01 12:33 AM Page 680
680
CHAPTER 22 • Using Visual Basic with Excel
Immediate Window Displays information resulting from debugging statements in your code or from commands typed into the immediate window. Use this to query or change values (of variables, properties, etc.) and to test newly written code. Select View Immediate Window or press Ctrl+G to open. Locals Window Displays all of the declared variables and their values in the current procedure. Select View Locals Window to open. Watch Window Automatically appears when watch expressions (statements that are flagged with the watch icon) are activated. Information about the selected expression is displayed. Select View Watch Window to open the Watch Window. Call Stack Dialog Box Displays a list of currently active procedure calls. Select View Call Stack to open.
NOTE
When you start a new project in VBA, you do so within the host application, in this case, Excel. In the Project Explorer, you’ll see an entry at the top called VBAProject (Book1) linked to Microsoft Excel Objects and then to any UserForms, Modules, or Class Modules you have written. Each workbook and add-in that’s currently open is considered a project.
Creating the Application Interface Our project calls for a text box and a command button, but before we can create them, we have to create the UserForm that they will sit on. The UserForm is our canvas, onto which we will “paint” our controls.
Adding the UserForm To add a UserForm, go to the toolbar and look at the second icon from the left, which is the Insert Object button. Click the pull-down menu attached to the button to see the objects you can add. These options are also available from the Insert menu.
4002c22.qxd 7/18/01 12:33 AM Page 681
The choices, as shown above, are the following: • Procedure UserForm • Module • Class Module A fifth type, File, is only available from the Insert menu. We’ll only be using the UserForm for our application, but here’s a brief explanation of each of the types: UserForm A dialog box or window that is used to provide or collect information in an application’s user interface.
NOTE
You can attach VB code to a UserForm; the code is stored in a form module built into the UserForm. This form module is not to be confused with modules or class modules.
Module Modules are also known as standard modules. They are where procedures and declarations are stored for your project. In essence, this is a code stockpile. Class Module This is the first hint of object-oriented programming (OOP) in Visual Basic. Class modules are used for complex applications and other operations that are only possible through Visual Basic code. For example, class modules are used to define functions that no control or add-in already provides or to call functions directly from the Windows 32-bit application programming interface (API). Procedure Procedures are used to break VB code into components that perform specific functions so that repetitive tasks do not need to be written over and over again. Using procedures eases your coding work because each procedure can be written, tested, and debugged independently, rather than as one part of a much larger whole. You can also reuse your procedures in other applications if you keep the code homogenous (avoiding references or calls to application-specific variables).
NOTE
The Procedure item is only available when you have a UserForm code module, (standard) module, or class module window open.
File Insert code that has been written and saved in a separate file into your UserForm code, module, or class module. The default file types are text files (.txt), Basic files (.bas), and Class files (.cls).
681
PART
VII Automating Excel 2002 with Macros and VBA
Hello World!
4002c22.qxd 7/18/01 12:33 AM Page 682
682
CHAPTER 22 • Using Visual Basic with Excel
NOTE
The File item is only available from the Insert menu, and only when you have a UserForm code module, (standard) module, or class module window open.
Now that you’ve seen the options, select Insert UserForm from the VB Editor toolbar to create a UserForm for your application. The form will appear in the large gray area of the VB Editor. You’ll notice that you get two windows: a UserForm object and a window to hold it, as we see in Figure 22.4. FIGURE 22.4 The default UserForm object
This form, as you can see from Figure 22.4, is named UserForm1. The Properties window shows the properties of the form and the current values of each property. And to the right (or left) of the UserForm, you can see the Toolbox. This Toolbox is where you select the controls to add to your UserForm, which we’ll do next.
4002c22.qxd 7/27/01 3:03 PM Page 683
Removing and Restoring the UserForm A brief aside on the topic of file maintenance: you may wish to share UserForms with other programmers or between projects. You can do this by importing and exporting UserForms using the File menu (File Import File, File Export File). To delete a UserForm from your project, click on the UserForm you wish to remove, and then select File Remove UserForm. The name of your selected UserForm will appear on the Remove menu item. Excel will display the following dialog box:
Clicking Yes will display the Export File box as shown in Figure 22.5. Enter the file name for your UserForm. Note that the default type is Form Files (.frm). To work with the saved form file during a future Excel Session, select File Import File. On the Import File dialog box select the form you wish to open. FIGURE 22.5 The Export File Dialog Box
But now let us return to the Hello World! project.
Adding the Controls A control is a preprogrammed object that the user can interact with or get information from. Controls include buttons, pull-down lists, and check boxes. Every time you see a dialog box warning you of something and you click the OK button, you have used a control.
683
PART
VII Automating Excel 2002 with Macros and VBA
Hello World!
4002c22.qxd 7/18/01 12:33 AM Page 684
684
CHAPTER 22 • Using Visual Basic with Excel
To add a CommandButton control to the form, follow these steps: 1. Click the CommandButton button on the Toolbox (the small, gray rectangle, shown here). The button remains depressed once you have clicked it, indicating that the CommandButton is selected.
2. Move your mouse pointer to the form area and point to where you would like the top-left corner of the button to be; then click and drag down and right until you’ve outlined a rectangle the size you want the button to be. The other way of creating a CommandButton on your form is to click on the button in the Toolbox and drag it to the UserForm. The default size and shape of the CommandButton control will be illustrated by a gray box.
TIP The best way to think of the interface design process is to equate it with painting a picture. If you’ve used Microsoft Paint or any of the Office drawing tools, you’ll have a good idea of how this works. Just select a tool from the Toolbox and click and drag on the form to define its size. 3. Resize and relocate the control to look something like Figure 22.6. To resize a control, select it, point to one of the handles that appear around the control, and drag the handle. Moving the control is simple, too. Point near the center of the selected control and drag it to the new location. This takes care of the first control, the CommandButton with its default name of CommandButton1. We’ll change the name in a moment, but first we’re going to add the TextBox control. Go back to the Toolbox and select the icon with “ab|” on it. Follow the same steps that you used to create the CommandButton control, but place the TextBox above the button control. Your end result should look something like Figure 22.7.
4002c22.qxd 7/18/01 12:33 AM Page 685
Hello World!
PART
VII Automating Excel 2002 with Macros and VBA
FIGURE 22.6 Congratulations, your first control!
685
FIGURE 22.7 Adding the TextBox control
4002c22.qxd 7/18/01 12:33 AM Page 686
686
CHAPTER 22 • Using Visual Basic with Excel
After placing the TextBox, you can also resize and relocate it to meet your needs. You can do that by clicking the control and dragging the handles around, as you did with the CommandButton, but the VB Editor can perform this task for you. There are two tools that can resize and relocate your controls so they look uniform. First, let’s size our two new controls in relation to each other. 1. Select the two controls by clicking on the form and dragging across both of them to “lasso” them. Both controls will have handles when they’re selected. In Microsoft products, you don’t have to drag completely around controls to select them; any control that you drag across will be selected. 2. Select Format Make Same Size Height. 3. While the two controls are still selected, select Format Align Centers to align the centers of the two controls. 4. While the two controls are still selected, choose Format Center in Form Horizontally. Do not center them vertically in the form or you’ll simply place one object on top of the other in the very center of the form. Now that you’ve created the interface, we’ll move on to setting properties and other options.
Changing Properties It’s one thing to add controls to your form, but it’s another to make those controls look and act as you want them to. This is where properties come in. In this section, we’ll look at the properties for each of our controls and examine what they can do for us.
NOTE
We’re not going to list all of the properties for each control because there are a great number of them. If you’re curious about a control’s properties, place the control on a form following the steps we’ve outlined above, and look in the Properties window, which gives you access to all of the properties for the selected control.
First, we’ll look at the properties for our UserForm. The Properties window, which is in the lower-left part of the VB Editor window, sorts the list alphabetically by default. You can also click the Categorized tab to see your control’s properties organized by type.
NOTE To select the UserForm itself, click any area on the UserForm that is not occupied by a control. When the object handles appear around the form itself, it is selected, and you can see and modify the UserForm’s properties.
4002c22.qxd 7/18/01 12:33 AM Page 687
The left column of the list shows the name of the property; the right column shows the value for that property. There are two ways to change a property: • Type a new value. • Select an option from a list.
The UserForm For our Hello World! project, we need to rename our UserForm for all the same reasons that we don’t keep the default Excel workbook name Book1. Display the UserForm properties by clicking in the background or title bar of UserForm1. Locate the Caption property in the Properties window, and click the property name (Caption) to highlight it. When you begin typing, even though the text, “UserForm1,” is not selected, your new text will replace it. You will note that your new text also appears in the UserForm at the same time. Type Hello World! and press the Enter key to change the Caption property. Then change the name of the form to frmHelloWorld by clicking the property (Name) and typing the new name. To add some individuality to our UserForm, we’ll also define its SpecialEffect property. Locate the SpecialEffect property near the bottom of the list and select its name. You’ll note that a pull-down arrow appears in the value column. This property has preset values. You can choose from the following: • fmSpecialEffectFlat • fmSpecialEffectRaised • fmSpecialEffectSunken • fmSpecialEffectEtched • fmSpecialEffectBump Take a look at the form in each of these modes and decide which one you like better. We’re particularly fond of the etched look, so we’ll use that ourselves. You can choose what you like; choosing a different value will not affect how the form works, just how it looks.
TIP It is good programming practice to give meaningful names to the controls on your forms as well as the forms themselves. The Microsoft default names (UserForm1, TextBox2, CommandButton1) quickly become confusing on a complex form or project. A common naming convention is to preface each control name with the type of control: cmd for CommandButton, txt for TextBox, cbo for ComboBox, frm for UserForm, etc. The names are then finished with a description. Brevity and clarity are the goal. For example, name the Exit buttons on your forms cmdExit. You will be able to find the Exit control no matter what form you are working on.
687
PART
VII Automating Excel 2002 with Macros and VBA
Hello World!
4002c22.qxd 7/18/01 12:33 AM Page 688
688
CHAPTER 22 • Using Visual Basic with Excel
The CommandButton Control Now we can move on to the next control, the CommandButton. We’re going to do three things to the CommandButton control: • Change the Caption property to “Hi, my name is World.” • Change the (Name) property to cmdNameWorld. • Set the newly named CommandButton as the default button for the UserForm. First, select the CommandButton in your form; then locate the Caption property in the list and select it by clicking on the word Caption. As with the UserForm, the Caption changes as you type the new caption. If your caption text is larger than the button itself, simply drag one of the side handles until the button is large enough to show all of the text in one line.
NOTE
If you resize your CommandButton, it will probably be out of alignment with the TextBox. Simply drag-select both controls and select Format Align Centers to fix it.
When that’s done, go back to the Properties window and locate the Default property. From the pull-down list, select the True value. This sets the button to be the default when the UserForm is run, which allows it to be “clicked” with the Enter key or spacebar as well as the mouse. Next, locate the Name property in the Properties window. Rename the button cmdNameWorld. There are no properties we need to set for the TextBox control, but it’s good practice to assign it a meaningful name. Call your TextBox txtHelloWorld.
Writing the Code Now that we have a pretty face on our project, we need to write some code so that clicking the CommandButton will cause a text string to appear in the TextBox control. Here is the code for the CommandButton that will start our procedure when we click on it. Private Sub cmdNameWorld_Click () txtHelloWorld.Text = “Hello World!” End Sub
Once you’ve added the second line of code, your code window should look like Figure 22.8.
4002c22.qxd 7/18/01 12:33 AM Page 689
Hello World!
FIGURE 22.8 The code editor window showing our program code
689
PART
Automating Excel 2002 with Macros and VBA
VII
The easiest way to add code to a control is to double-click the control. This opens the Code Editor window. As you can see when you try this yourself, most of your code is already there. All you have to do is add the second line of code. This is just one of the ways that VBA makes it easy for you to create applications.
TIP There are a few conventions in programming that are accepted by most programmers. Your program will still work if you don’t follow them, but most programmers follow these conventions because it makes code easier to read. When you add the new code, you can add it without indenting the second line, but it would be harder to distinguish the subroutine from the surrounding statements. Adding tabs at the beginning of lines that are controlled by the previous line simply shows that the tabbed line is subordinate to the preceding one. It won’t make much difference in this program, but in larger ones it makes your logic easier to follow and your bugs easier to find. Blank spaces and blank lines are ignored by program compilers and interpreters, so performance is not affected by adding white space for readability. Let’s look at each line of the code so we can get a better understanding of how it works. The first line reads like this: Private Sub cmdNameWorld_Click ()
First, Private indicates that this procedure is available only to the form that it is on. If you want to make the procedure available to other forms in this application, you would substitute Public for Private.
4002c22.qxd 7/18/01 12:33 AM Page 690
690
CHAPTER 22 • Using Visual Basic with Excel
Second, Sub indicates that the code following is a subroutine. Subroutines are the building blocks that make up programs. Our subroutine here, which includes a single line of code, performs a single task. Third, cmdNameWorld_Click does two things. The first part of the name tells the subroutine which control is expecting an event; the Click part of the name tells the subroutine what kind of event to expect, in this case a Click event. When we run the application, we will see that clicking the button does cause the text “Hello World!” to appear in the TextBox control.
NOTE
You probably noted the lonely parentheses apparently doing nothing at the end of the first line. They are used to surround any values you need to pass into the procedure from another function or to apply a static value that is always used. These values are called variables. You need the parentheses, even if you don’t have any variables to pass into the procedure, just as Excel’s NOW function needs parentheses: =NOW(). If you remove them, you’ll get an error.
The next line, which is indented for easier reading, is a statement. A statement is a line that contains instructions for the program to follow. The first item is txtHelloWorld, which performs the same function as cmdNameWorld in the previous line. It is the name of the TextBox control we placed on our UserForm, and we named it txtHelloWorld for identification purposes. Its presence here indicates that when we click the button, the result will happen in the TextBox control. The period (.) tells the program that the next item (Text) is a property of the first item, txtHelloWorld. This sets up the Text property to be ready to accept input of some sort.
NOTE
The Text property of the TextBox control is used to set the default text in the control when the form opens. If you place nothing in the Text property field, the TextBox control will be empty.
You can probably already figure out how the rest of the line works. The equal sign (=) sets the Text property equal to the next bit of information. In this case the Text property is set to “Hello World!” When we run the program and click the button, the text string “Hello World!” will replace the existing text in txtHelloWorld’s Text property.
4002c22.qxd 7/19/01 11:22 AM Page 691
The last line, End Sub, simply tells the program that it has finished its subroutine and can return control to Windows. Every time you click the button, the program runs and puts the text string “Hello World!” into the TextBox control. You won’t actually see this unless you change or delete the text in the TextBox. Now that we understand how the program works, let’s run it and see it in action.
Proof of Concept Click the Run Macro button on the toolbar and, unless an error exists, your form should appear on your screen. Click the CommandButton and watch as the phrase “Hello World!” appears in the TextBox control.
FIGURE 22.9 Hello World!
This was a very basic project, but it is indicative of the process required to add to or modify the functionality of Excel with VBA. There are, however, a few things that can trip up even the simplest applications.
To Err Is Human Computers take everything literally, so if you made a typing mistake, your program won’t work properly. For example, if instead of this line: txtHelloWorld.Text = “Hello World!”
you had entered this line: txtHelloWorld.Txt = “Hello World!”
the program would return an error. (Try it yourself and see what happens.) To fix this problem, you simply need to fix the typing error. However, it’s good to know what happens when VBA detects that something is not quite right. When we
691
PART
VII Automating Excel 2002 with Macros and VBA
Hello World!
4002c22.qxd 7/18/01 12:33 AM Page 692
692
CHAPTER 22 • Using Visual Basic with Excel
run the program with the error and click the button, we get an error dialog box with the following message: Compile Error: Method or Data member not found
If we look at the code after dismissing this dialog box, we’ll see that the first line of code is highlighted in yellow and that the text we changed is marked in blue. This tells us that the yellow line was the one that the compiler stopped on when it detected something wrong and that the error comes from the misnamed property, Text, which is highlighted in blue.
Compiling and Distributing Your Program Because VBA is dependent on the application it lives in to run (in this case, Excel), that is where the code you create is stored. If you don’t build your project, VBA will compile your procedures from the code when the user runs a macro, which can be significantly slower, depending on the size of your application. To confuse the issue slightly, VBA refers to building a project as compiling it (though, as we mentioned previously, what it really does is pre-interpret it). To compile your project, go to Debug Compile VBA Project.
Going Further with Visual Basic Here is a list of some resources—print and Internet-based—that can help point you in the right direction while you work with VB. Mastering VBA 6 by Guy Hart-Davis (Sybex) Visual Basic for Applications is the most widespread application programming language around, offering you the ability to automate and customize the behavior of hundreds of VBA-compliant applications. Mastering VBA 6 begins by equipping you with a solid foundation in VBA programming, then moves on to clear, tutorial-based instruction in the specific techniques you need to know to get the performance you want. Visual Basic® Language Developer’s Handbook™ by Ken Getz & Mike Gilbert (Sybex) This is the book you need if your programming involves the Visual Basic language—regardless of whether you work with Visual Basic or a specific VBA host. Inside, two acclaimed Visual Basic experts explain how the underlying language works and how you can apply this understanding to get the most out of any Visual Basic development environment.
4002c22.qxd 7/18/01 12:33 AM Page 693
Microsoft’s Visual Basic Technical Resources site Plenty of technical information, tutorials, and other helpful material that’s freely available. Information is available to help you on your decision to transition to Visual Basic.NET from Visual Basic 6. msdn.microsoft.com/vbasic/technical/default.asp Developer.Com® A large network of resources for developers from all walks and languages. The Visual Basic area is excellent. softwaredev.earthweb.com/vb Visual Basic Web Directory An immense collection of pointers and links to a huge amount of information about VB. It is organized in categories, which makes it simple to find what you’re looking for, including learning from the bottom up. searchvb.techtarget.com/ VBOnline Magazine An online magazine with lots of helpful material and tutorials that can help get you up to speed with VB. www.vbonline.com/vb-mag/
693
PART
VII Automating Excel 2002 with Macros and VBA
Going Further with Visual Basic
4002c22.qxd 7/18/01 12:33 AM Page 694
This page intentionally left blank
4002c23.qxd 7/18/01 12:57 AM Page 695
CHAPTER
23
DO -IT-YOURSELF FUNCTIONS F E ATU R I NG
Creating a user-defined function
Working with user-defined functions in worksheets and formulas
Creating add-ins for your user-defined functions
Debugging your VBA code
Looking at Windows API functions
4002c23.qxd 7/18/01 12:57 AM Page 696
y now you should have a good feel for using Excel’s worksheet functions. There are more than 300 predefined functions in 11 categories, which cover most conceivable circumstances. So why create custom functions? To create more powerful formulas and to simplify the way you work in Excel. In addition, you can use Windows’ built-in System Functions within the Applications Programming Interface (API) when collaborating or sharing data with other Office XP applications. In this chapter, we will create a couple of user-defined functions and examine in detail the debugging features of the VBA IDE. Then we will save our functions for use in the next chapter’s sample application. Finally, we will take a quick look at the Windows API functions.
b
Creating User-Defined Functions There are only a few steps to creating functions. Before we begin, we’ll examine the syntax for a function, show you how to use functions in a formula and how to pass arguments in user-defined functions. The syntax for a function is as follows: [Public | Private][Static] Function name [(arglist)][As type] [statements go here] [Exit Function] [statements go here] End Function
There’s a lot of information in these few lines of syntax, so let’s unpack them to see the available options: • Public (optional) makes the function accessible to all other procedures and modules in the workbook, while Private (also optional) makes the function accessible only to other procedures in the same module. If you select Private, your functions will not appear in the list in the Insert Function dialog box, so users can’t include the function in formulas. • Static (optional) preserves the values of variables declared in the function between calls so the variable values persist from one use to the next. • Function keyword (required) indicates that this code is a function rather than a procedure or subprocedure. • Name (required) is the function’s name. • Arglist (optional) is one or more variables or constants that represent arguments passed to the function. • Type (optional) is the data type of the value returned by the function.
4002c23.qxd 7/18/01 12:57 AM Page 697
• Statements are optional but highly recommended if you want your function to actually do something. • Exit Function (optional) causes an immediate exit from the function. • End Function (required) finishes your function. Let’s jump right in and create a couple of user-defined functions. The Years of Service and Count Weekends functions will give you practice with some simple VBA coding. Years of Service introduces the use of nested If statements in VBA, while Count Weekends uses looping.
The Years of Service User-Defined Function In this function, the application passes a hire date to the function, which uses the passed parameter and today’s date to calculate and return a value for years of seniority. The Years of Service function, basYrsService, also takes into account whether the current year’s anniversary date is in the past or the future. All the code for this function is included here, so we’ll assume that you’re playing along, creating the function and getting some additional experience with the VBA IDE. Follow these steps to create the function: 1. From Excel 2002, open the VBA IDE by choosing Tools Macro Visual Basic Editor. 2. Insert a new module (Insert Module) or open an existing module. 3. Choose Insert Procedure from the menu to open the Add Procedure dialog box, shown in Figure 23.1.
FIGURE 23.1 Use the Add Procedure dialog box to insert subroutines, functions and properties.
697
PART
VII Automating Excel 2002 with Macros and VBA
Creating User-Defined Functions
4002c23.qxd 7/18/01 12:57 AM Page 698
698
CHAPTER 23 • Do-It-Yourself Functions
4. Enter a name for the procedure in the Name text box. Choose the Type of procedure you’re creating: Function. The Scope is a procedure’s range: Private procedures can only be called by other procedures in the same module; Public procedures can be called by any procedure in the same application. Select Public for this function. Click OK to add the first and last lines of the procedure to the Code window. Here’s the completed code: Public Function basYrsService(dteHireDate) As Integer ‘returns years of service Dim dteToday As Date ‘get the system date dteToday = Date ‘get the years and calc difference dteThisYear = Year(dteToday) dteHireYear = Year(dteHireDate) intYrsService = dteThisYear - dteHireYear ‘get the months dteThisMonth = Month(dteToday) dteHireMonth = Month(dteHireDate) ‘determine if the hire month & day have passed in the current year ‘if so, the seniority years are the difference between today & hire date ‘else, the seniority years are the years difference minus 1 If dteThisMonth < dteHireMonth Then basYrsService = intYrsService - 1 Else If dteThisMonth > dteHireMonth Then basYrsService = intYrsService Else dteThisDay = Day(dteToday) dteHireDay = Day(dteHireDate) If dteThisDay < dteHireDay Then basYrsService = intYrsService - 1 Else
4002c23.qxd 7/18/01 12:57 AM Page 699
basYrsService = intYrsService End If End If End If End Function
It’s always a good idea to test your functions. To test the function, you need an application that calls the function. Until we create an application in the next chapter that uses basYrsService, you’re going to have to fudge it. Following is a bare-bones subroutine that displays an input box to enter a hire date. It then calls the basYrsService function and displays a message box with the calculated years of service.
NOTE
This subroutine does not check the date input for validity (we’ll cover that in Chapter 24, “Creating an Excel Application”), so make sure you enter a hire date prior to today when testing this function.
Create this subroutine in the same module where you created basYrsService. Open the module, select Insert Procedure from the menu, and create a subprocedure called GetData. Enter the code as follows: Sub GetData() Dim dteHireDate As Date Dim intYrsService As Integer dteHireDate = inputbox(“What is your hire date?”, “Enter Date of Hire”) intYrsService = basYrsService(dteHireDate) MsgBox “You have “ & intYrsService & “ years of seniority.” End Sub
To test your function, in the VBA IDE click anywhere in the GetData function. Select Debug Compile VBAProject from the menu, and click the Run button on the main toolbar. First, you’ll see the input box shown in Figure 23.2. FIGURE 23.2 Enter a hire date here to calculate years of seniority.
699
PART
VII Automating Excel 2002 with Macros and VBA
Creating User-Defined Functions
4002c23.qxd 7/18/01 12:57 AM Page 700
700
CHAPTER 23 • Do-It-Yourself Functions
The basYrsService function returns an integer containing the years of service to the GetData subprocedure, which displays the years in a message box. Enter a hire date and click OK to see the results of the function (Figure 23.3). We will be using this function in the sample application in Chapter 24, so save your work! FIGURE 23.3 The result of your first user-defined function
The Count Weekends User-Defined Function The basCountWeekends user-defined function will loop through the days from now to a selected day in the future to determine the number of weekend days and weekday days. There are other ways to accomplish this task, but this function also serves a dual purpose: it illustrates the use of looping in a user-defined function. See the “VBA Programming Structures” in Appendix B for information on different structures you can use to loop through your code. Enter this function in the same module you created earlier in the chapter. Because functions can only return one value, we have selected the number of weekend days to be the passed parameter. (We could just as easily have chosen the number of weekday days, but it’s more fun to work for the weekends.) The dteRetireDate is passed to basCountWeekends. The total number of days between the two dates is determined within the calling subprocedure with a calculation based on the result of basCountWeekends. Public Function basCountWeekends(dteRetireDate) As Integer ‘get the system date Dim dteToday As Date dteToday = Date Dim countdate As Date Dim intWeekend As Integer
‘counter for day loop ‘number of weekend days
‘initialize date counter and weekend fields countdate = dteToday intWeekend = 0
4002c23.qxd 7/18/01 12:57 AM Page 701
‘starting with today, check each date until retirement ‘to check if it is a Saturday (7) or Sunday(1) ‘Increment intWeekend if date is a weekend date Do While countdate < dteRetireDate intDayNum = Weekday(countdate) If intDayNum = (1 Or 7) Then intWeekend = intWeekend + 1 End If countdate = countdate + 1 Loop ‘set the value of the function to the number of weekend days basCountWeekends = intWeekend End Function
In order to test our function and ensure we’ve avoided the dreaded infinite loop, we will create a simple subprocedure to view our results: Public Sub GetMoreData() Dim dteRetireDate As Date Dim dteToday As Date Dim intTotalDays As Integer Dim intWeekdays As Integer Dim intWeekends As Integer dteToday = Date dteRetireDate = inputbox(“What is your planned retirement date?”, _ “Enter Retirement Date”) intWeekends = basCountWeekends(dteRetireDate) intTotalDays = dteRetireDate - dteToday intWeekdays = intTotalDays - intWeekends MsgBox “You have “ & intTotalDays & “ days until retirement. But “ _ & intWeekends & “ of them are weekends!” End Sub
701
PART
VII Automating Excel 2002 with Macros and VBA
Creating User-Defined Functions
4002c23.qxd 7/18/01 12:57 AM Page 702
702
CHAPTER 23 • Do-It-Yourself Functions
The user enters his or her planned retirement date in an input box. The basCountWeekends function calculates the total weekend days between the today’s date and the planned retirement date that was passed as a parameter. The calling subprocedure, GetMoreData, then calculates the total number of days between the two dates and formats a message box to display the results:
You have two user-defined functions that you can use in the sample application in the next chapter. In the next section, we’ll discuss using user-defined functions in formulas and creating add-ins with user-defined functions.
Using Custom Functions Writing a user-defined function is just the first step in your customization quest. Worksheet formulas can contain Excel’s built-in worksheet functions, user-defined functions, or any combination of the two. The Insert Function dialog box allows you to choose from Excel’s built-in functions and any user-defined functions you have created. And you also can create an add-in to more easily run your user-defined functions. But first, we’ll provide some descriptions for our functions. The descriptions appear in the Paste Function dialog box and simplify the search for the right function. It is good programming practice to add a description for all of your user-defined functions, especially if the code will be shared with or maintained by others.
Calling User-Defined Functions To call a user-defined function from a procedure, use the following syntax: Result = Function (arglist)
The result is a variable previously defined to hold the returned value from the function. If you are not allowing VBA to default to the data type variant, be sure that you define the variable and the function return value as having the same data type. The function is simply the function name and the arglist contains the parameters required by the function. Separate the parameters with commas and enclose them in parentheses.
4002c23.qxd 7/18/01 12:57 AM Page 703
User-Defined Functions on a Worksheet Before we insert a user-defined function on a worksheet, let us add some descriptions for the two user-defined functions we just created: 1. From the Excel workbook (not the VBA IDE) select Tools Macro Macros to open the Macro dialog box shown in Figure 23.4. Note that the Macros list includes the subprocedures you’ve written but not the user-defined functions.
FIGURE 23.4 The Macro dialog box lists only procedures and subprocedures.
2. Enter your function name in the Macro Name text box and click Options. Excel will display the Macro Options dialog box shown in Figure 23.5. 3. In the Macro Options dialog box, enter a function description. 4. Click OK, then click Cancel to close the Macro dialog box.
FIGURE 23.5 The Macro Options dialog box with a description entered for the userdefined function basCountWeekends
703
PART
VII Automating Excel 2002 with Macros and VBA
Using Custom Functions
4002c23.qxd 7/18/01 12:57 AM Page 704
704
CHAPTER 23 • Do-It-Yourself Functions
NOTE
You can modify the function description at any time by returning to the Macro dialog box and entering the name of the user-defined function.
4. To use a function in a worksheet formula, select a cell and choose Insert Function from the menu or choose More Functions from the menu on the AutoSum button. User-defined functions are located in the User Defined category. The descriptions are shown on the bottom of the dialog box, along with the function name and the parameters passed to it (see Figure 23.6). Select one of the user-defined functions and click OK.
FIGURE 23.6 The Insert Function dialog box for a userdefined function
5. Excel displays the Function Arguments dialog box. For our example basCountWeekends, enter a future date and click OK. The function and passed parameters are now referenced in that cell.
4002c23.qxd 7/18/01 12:57 AM Page 705
NOTE
To reference user-defined functions that are located in a different workbook, you must include the file reference. This is accomplished by including the file name in the cell reference—for example, =myfile.xls!basCountWeekends(7/4/2010) —or by selecting Tools References in the VBA IDE to refer to the project that contains your userdefined function. A third method is to define the function as an add-in (see the following section, “Creating an Add-In”).
Creating an Add-In Creating an add-in for user-defined functions allows you to use the functions in any workbook without having to include a filename qualifier. Shorter reference names make worksheets and formulas more readable and easier to maintain. Follow these steps to create an add-in: 1. Create a new workbook in Excel and launch the VBA IDE by selecting Tools Macro Visual Basic Editor. Create a user-defined function. Close the VBA IDE and return to the Excel worksheet.
TIP
If you already have a user-defined function you want to turn into an add-in, copy the function and paste it into a module in the new workbook.
2. Select File Properties and enter a Title and Comments. The title and comments will appear in the Add-Ins dialog box. Click OK. 3. Select File Save As. In the Save As dialog box, select Microsoft Excel Add-In in the Save as Type drop-down list. Enter a filename and click Save to create the add-in. Excel saves the add-in in the default add-in file location, deep in the bowels of Windows.
TIP
To find the add-ins on your hard drive or network, search for files with an .xla extension.
4. Close the file.
705
PART
VII Automating Excel 2002 with Macros and VBA
Using Custom Functions
4002c23.qxd 7/18/01 12:57 AM Page 706
706
CHAPTER 23 • Do-It-Yourself Functions
Follow these steps to include your add-in in a different workbook: 1. Select Tools Add-Ins to display the Add-Ins dialog box shown in Figure 23.7. 2. Check the add-ins you wish to reference. If you don’t see the add-in you need, click the Browse button to search for it. Click OK to add the add-in to the workbook so you can refer to the user-defined functions contained in your add-in by their function names.
FIGURE 23.7 The Add-Ins dialog box showing available add-ins, including the custom Retirement Add-In
Testing and Debugging In-Depth It’s hard to believe, but programmers make mistakes sometimes. The consequences of coding errors run the gamut from merely annoying to disastrous. After the Hubble Space Telescope was launched in 1990, scientists discovered that its primary mirror was misshaped—ground too flat on one side due to a fabrication error. A few years later astronauts in the Space Shuttle repaired Hubble, but many remember the scorn heaped upon the programmers of the grinding machine. Is there a moral to this story? Of course there is: use the testing and debugging tools included with Excel 2002 to find problems before your users do.
4002c23.qxd 7/18/01 12:57 AM Page 707
Using the Debugging Toolbar and Menu Debugging is necessary when programs either refuse to run or return unexpected or incorrect results. Even if a program isn’t obviously broken, it’s good programming practice to test your code and ensure that it can handle unusual conditions like creative data entry in input boxes or division by zero errors. Excel’s Visual Basic IDE provides a host of debugging and testing tools to aid you in creating stellar applications. Begin by displaying the Debug toolbar in the VBA IDE. Select View Toolbars Debug. The Debug Menu contains all of the commands available on the Debug toolbar and a few additions. Let’s first look at the Debug toolbar:
Design Mode
Turns design mode on and off.
Run Runs the active procedure, subprocedure, or UserForm. Displays the Run Macro dialog box if there is no active code or UserForm. Does not run Functions; these must be called from a procedure or inserted into a formula. Break Pauses execution of a program while it is running. To restart execution of the program, click the Run button. Figure 23.8 shows a breakpoint set on the evaluation line of a Do Loop. The highlighted line of code with an arrow in the left margin is the line of code about to be executed. Reset Clears the execution stack and module level variables and resets the project. Toggle Breakpoint cut is F9.
Sets or clears a breakpoint at the selected line. Keyboard short-
Step Into Executes the next logical statement in the code that is running. Keyboard shortcut is F8. Step Over Executes the next procedure in the code that is running or completes the current procedure. Keyboard shortcut is Shift+F8. Step Out Executes the remaining lines of a procedure in which the current execution point lies. In other words, finishes the current procedure. Keyboard shortcut is Ctrl+Shift+F8. Locals Window Displays the Locals window, which shows all of the declared variables in the current procedure. The Locals window updates every time you enter break mode or when a new procedure is called. You can edit the value of the variables in the Value column (to put an array back in bounds, for instance). See Figure 23.9 to see a Locals window that has been updated when the application reached a breakpoint.
707
PART
VII Automating Excel 2002 with Macros and VBA
Testing and Debugging In-Depth
4002c23.qxd 7/18/01 12:57 AM Page 708
708
CHAPTER 23 • Do-It-Yourself Functions
FIGURE 23.8 Debug looping code by breaking at the evaluation points.
FIGURE 23.9 Debugging an application using the Locals window and Watch window.
4002c23.qxd 7/18/01 12:57 AM Page 709
Immediate Window The Immediate window is used to view or edit the value of a variable while running an application, assign a variable a new value during break mode, view or edit a property value while running an application, and call procedures and view debugging output while the program is running. To execute code, simply type a line of code in the Immediate window. Press Enter to execute the statement. The keyboard shortcut is Ctrl+G. See Table 23.1 for a list of the shortcut keys that can be used in the Immediate window.
TABLE 23.1
I m m e d i a t e Wi n d o w Ke y b o a r d S h o r t c u t s
Keys
Result
Enter
Run a line of code
Ctrl+C
Copy to the clipboard
Ctrl+V
Paste from the clipboard
Ctrl+X
Cut to the clipboard
Ctrl+L
Display Call Stack dialog box during break mode
F5
Continue running an application
F8
Execute one line of code
Shift+F8
Execute code one procedure at a time
Delete
Delete selection
F2
Display the Object Browser
F7
Display Code
Ctrl+Enter
Insert Carriage Return
Ctrl+Home
Move cursor to top of the Immediate window
Ctrl+End
Move cursor to the bottom of the Immediate window
Shift+F10
View shortcut menu
Alt+F5
Runs error handler code or returns the error to the calling procedure
Alt+F8
Steps into the error handler or returns the error to the calling procedure
Watch Window Displays the Watch window shown in Figure 23.9. It displays all of the expressions you have selected for watching. If you wish to display the Edit Watch dialog box, press Ctrl+W from within the Watch window. The Watch window contains the expression that has been selected for watching, the value of the expression at the time of entering break mode, the type of expression, and the
709
PART
VII Automating Excel 2002 with Macros and VBA
Testing and Debugging In-Depth
4002c23.qxd 7/18/01 12:57 AM Page 710
710
CHAPTER 23 • Do-It-Yourself Functions
context of the expression. The Watch window is updated whenever your application enters break mode. Two watch types will force a break when the value of the expression changes or evaluates to TRUE. See the Add Watch and Edit Watch dialog box descriptions later in this list for more information. Quick Watch Displays the Quick Watch dialog box with the current value of the selected expression. The keyboard shortcut for the Quick Watch window is Shift+F9. Add items to the Watch window, then check the value of the items as you step through your code. Variables that are not in use are listed as Out of Context.
Call Stack Displays the calls dialog box, which lists the currently active procedures in the application that have started but are not completed. This is very useful if your application calls multiple subprocedures and functions before it completes execution. Keyboard shortcut is Ctrl+L. The Debug menu also contains most the commands just listed as well as the following: Compile VBAProject (or the Name of Your Current Project) This might be the most important selection of all. Compiling your code not only speeds up execution, but the compiler will find all of your VBA syntax errors (also known as “typos”) before you try to run your code.
TIP
Always compile your code before attempting to test and debug it to find syntax
errors.
Run to Cursor This command runs the code up to the position of the cursor. Use this command to verify that code runs clean up to a specified point.
4002c23.qxd 7/18/01 12:57 AM Page 711
Add Watch Use this command to add an expression you wish to be monitored in the Watch window. When your application enters break mode, the selected watch expressions appear in the Watch window. A watch can also cause your application to enter break mode depending on the watch type entered. 1. Highlight the expression you wish to watch in your code window, then select Debug Add Watch. You can enter the expression directly in the window if you wish (see Figure 23.10). 2. Select a module or procedure in the Context group to select the times the expression will be evaluated. Selecting a very wide range can slow down processing, so select the narrowest scope that will work for your testing needs. 3. Select a Watch Type option: Watch Expression, which displays the value of the watched expression; Break when Value is True, which stops execution when the expression evaluates to TRUE; and Break when Value Changes, which stops execution when the value changes.
FIGURE 23.10 The Add Watch dialog box
Edit Watch You can modify or delete your watch expressions with this command (see Figure 23.11). Change the scope or watch type or click the Delete button to remove the watch completely. You can always add it again if needed. The keyboard shortcut is Ctrl+W.
711
PART
VII Automating Excel 2002 with Macros and VBA
Testing and Debugging In-Depth
4002c23.qxd 7/18/01 12:57 AM Page 712
712
CHAPTER 23 • Do-It-Yourself Functions
FIGURE 23.11 The Edit Watch dialog box
Clear All Breakpoints Removes all of the breakpoints in the active project. Once you have cleaned up your program logic and want to run your application all the way through, those pesky breakpoints tend to keep popping up. The keyboard shortcut is Ctrl+Shift+F9. Set Next Statement Continues code execution at the statement where the insertion point is located. It is used to quickly change the execution to a different code line. Keyboard shortcut is Ctrl+F9. Show Next Statement Highlights the statement that will be executed next. It is used as a bookmark so you can scroll to another section of code and find your place when you return.
TIP
Mouse over variables in procedures or functions during break mode to show ToolTips with the current values.
Now that you have been introduced to the debugging tools available in Excel 2002, try them out on your own code. Select a line of code and insert a breakpoint or two by clicking the Toggle Breakpoint button or by choosing Debug Toggle Breakpoint. Then click Run and watch your code execute.
4002c23.qxd 7/18/01 12:57 AM Page 713
Testing and Debugging In-Depth
713
PART
Getting Help with VBA and Excel 2002 Objects When you enter code, you refer to objects in Excel like headers and ranges. For a list of objects, use the VBA libraries, which are just a click away in the Object Browser. Click the Object Browser button (or choose View Object Browser) to open the browser.
All Libraries or the current library (Excel) will be displayed in the Project/Library dropdown list. You can choose other libraries from the Project/Library drop-down list, or select Excel to limit your search to Excel. To search for an object, enter part of the object’s name in the Search Text text box and click the Search button. When you choose an object in the Classes pane, you’ll see a list of properties and methods for the object in the right (Members) pane of the browser. If you want more information about the selected object, click the Help button in the Object Browser. For a more global view of application objects, browse the object model, the map of all the objects in an application. The model shows each object and how it relates hierarchically to other objects in the application. To access the object model for an application, open the application, launch Help in the VBA IDE, and search for the words object model in the Help Index. The Excel Object Model is discussed in Chapter 24, “Creating an Excel Application.”
Automating Excel 2002 with Macros and VBA
VII
4002c23.qxd 7/18/01 12:57 AM Page 714
714
CHAPTER 23 • Do-It-Yourself Functions
Windows API Functions There is another type of function available for use in Excel 2002. The Windows Application Programming Interface (API) contains functions that you can use to work with a component, application, or operating system. Typically an API consists of one or more dynamic link libraries (DLL) that provide some specific functionality. DLLs are files that contain functions that can be called from any application running in Windows and are only linked at runtime. Because most DLLs are written and documented primarily for C/C++ programmers, calling a DLL function may differ somewhat from calling a VBA function. In order to work with an API, you need to understand how to pass arguments to a DLL function. This is a potentially treacherous road, especially if you are a relatively new VBA programmer. We will simply point you in the right direction to learn more about using Windows API functions in your VBA code. On the Internet, the Microsoft Platform SDK is available free of charge through the Microsoft Developer Network (msdn.microsoft.com) and contains thorough documentation and many code samples. The Visual Basic Developers Guide, included with Visual Basic (but not included with VBA) also has a chapter on using Windows API functions.
WARNING Calling the Windows API and other DLL functions can be dangerous. When you call a DLL function directly from your code, you’re bypassing some of the safety mechanisms that VBA normally provides. If you make a mistake in defining or calling a DLL function (as all programmers eventually do), you may cause an application error (also referred to as a general protection fault, or GPF) in your application. The best strategy is to save your project before you run your code, and to make sure that you understand the principles behind calls to DLL functions.
4002c24.qxd 7/18/01 1:28 AM Page 715
CHAPTER
24
CREATING AN EXCEL APPLICATION F E ATU R I NG
Using the VBA Help files
Working with other Office applications
Sample application: Retirement Countdown Application
Loading and unloading a custom toolbar
4002c24.qxd 7/18/01 1:28 AM Page 716
n this chapter we’ll create an Excel application. First, we’ll explore the store of information available in the VBA Help files so you have help at your fingertips while creating the application. We will work more with custom toolbars, as well as with Excel’s Text to Voice capabilities. Digital signatures as well as the Package and Deployment Wizard will be covered, so that you can share your applications with others. Finally, the simple application—Retirement Countdown—will give you experience in bringing together most of the skills covered in this chapter. While creating the application, you may want to refer to the VBA Reference in Appendix B where you’ll find information on VBA syntax, properties, methods, events, and objects as well as the Excel object model and the Excel Help files.
i
Getting the Help You Need Microsoft has enriched the Visual Basic IDE and all the Office applications with a comprehensive set of resources. In this section we will examine the Visual Basic Help application and the Object Browser. Directions on finding help in the Microsoft Developers Network website are also provided.
Introducing the Excel Visual Basic Help File The Microsoft Excel Visual Basic Help file and MSDN website contain a huge amount of information on Excel’s objects, properties, and methods. As you might guess, you access this information from the Visual Basic IDE by choosing Help Microsoft Visual Basic Help or pressing F1. To visit the Microsoft Developer’s Network, select Help MSDN on the Web. In this section, we’ll look at the information available in the Help file and how you get to it. The programming Help for Excel 2002 has been upgraded. There are a number of reference “books” available for your use as shown in Figure 24.1, but specific books are displayed when you search for the answer to a question. After we introduce the reference materials, we’ll talk about how to use them to answer specific questions that will arise while you’re creating an application.
TIP To see the help file without having it filtered with search criteria, run the VBA for Excel Help file directly. The file, VBAXL10.CHM, is located in the 1033 subfolder where Excel is installed.
4002c24.qxd 7/18/01 1:28 AM Page 717
Getting the Help You Need
FIGURE 24.1 Use the Contents page of the Microsoft Visual Basic Help file to access information about programming Excel.
717
PART
Automating Excel 2002 with Macros and VBA
VII
Between the help contained in the VBAXL10 Help files and the information on the MSDN site, you’ll find the following: • Visual Basic User Interface Help, which contains a list of all the commands available in the VBA IDE; shortcut keys for Visual Basic, Office, and Windows applications; all commands available by menu; keyboard shortcuts available in the various windows; all the dialog boxes and tabs available on each one; all the toolbars used in VBA coding; the windows available in the IDE; and a guide to icons and wildcard characters. This book is a veritable roadmap to mastering the Visual Basic development environment. • Visual Basic Conceptual Topics, which contains articles on programming concepts and universal truths that will help in your work. Some topics include: • Avoiding naming conflicts • Making faster For…Next Loops • Passing arguments efficiently • Creating Recursive Procedures
4002c24.qxd 7/18/01 1:28 AM Page 718
718
CHAPTER 24 • Creating an Excel Application
• Visual Basic How-To Topics, just in case the User Interface Help is too general for your needs, this book tells you how to accomplish specific tasks, including the following: • Executing a specific statement • Using the object browser • Setting Visual Basic Environment options • Finding a variable definition • Visual Basic Language Reference, which contains all you ever wanted to know about the language itself. Check the “Miscellaneous” section for a handy reference on an ASCII character set. The Indexes/Lists section contains summaries of all of the function keywords used in Excel. This provides a more thorough documentation than the help provided in Excel 2002 itself. • Visual Basic Add-In Model contains the collections, events, methods, objects, and properties of the VB Add-In Model. • Microsoft Forms Reference, which contains the following: Microsoft Forms Object Model Overview Another object model for your enjoyment, this one containing the pieces of UserForms and DataObjects. Microsoft Forms Design Reference An extremely thorough series of pages on creating forms in Excel 2002. Contains sections the Forms Toolbox, making your UserForms more beautiful, as well as more functional with Control Tips, Tool Tips, and custom Help files. Microsoft Forms Developer Tips Contains development tips, helpful features (like protecting sensitive information and controls that automatically adjust to the size of its data), and ways to control navigation within your UserForms. Microsoft Forms Object Model Reference Just in case the overview did not meet your needs, the events, methods, objects, collections, controls, and properties of the Forms object model are all documented here. • Microsoft Excel Visual Basic Reference, which contains the following: • Excel object model • “What’s New” contains information about the new objects, events, methods, and properties in Excel 2002. All the events, methods, and properties are presented both alphabetically and by their associated objects. • Programming concepts with sections on workbooks and worksheets (creating, opening, referring, and saving); cells and ranges (including working with 3D ranges and looping techniques); controls, dialog boxes, and forms
4002c24.qxd 7/18/01 1:28 AM Page 719
(ActiveX, web components, and custom dialog boxes); events, worksheet functions, and shapes (techniques for manipulating); working with other applications including OLE ProgID’s, ActiveX references, and controlling one Office application from another. • Microsoft Graph Object Model, clickable version of the object model for graphs and charts created in Excel 2002. • Microsoft Office Object Model, clickable version of the object model for shared Office XP components. • Microsoft Office Visual Basic Reference, which contains the following: The Microsoft Office Object Model Used for objects that are shared among the Office applications such as the ever-popular Office Assistant, as well as nuts and bolts like the FileSearch, CommandBar, and HTMLProject objects. What’s New for Office Developers Includes changes to the Office object model and how to use the new objects. Programming Concepts Concentrates on the shared processing such as Command bars, Toolbars, Menu Items, and Shortcuts, as well as an article on creating Automation Objects (look in the OLE Programmatic Identifiers section). Objects, Methods, Properties, and Events Contains specific information about Office’s shared events, methods, objects, and properties. They are listed alphabetically. Whew! There’s a lot of help out there for Excel and Office developers, and if you still can’t find the answers you need, try the Knowledge Base located on Microsoft’s website at support.Microsoft.com.
Using the Excel Visual Basic Help File When you choose Help Microsoft Visual Basic Help, VB displays the Microsoft Excel Help dialog box. • The Contents tab (see Figure 24.1) displays the help information in hierarchical forms, like traditional books, sections, chapters, and articles. • Use the Answer Wizard tab (see Figure 24.2) to ask a question in English. The Answer Wizard returns topics that fulfill your criteria. Topics preceded with WEB, like the topic “WEB: Using the Protection Object to Protect Your Worksheets” in Figure 24.2, are located on Microsoft’s website, rather than in the Help file. If you wish to search exclusively on the Internet for your answer, click the Search on Web button to display a dialog box that will take you to the Microsoft site for further searching.
719
PART
VII Automating Excel 2002 with Macros and VBA
Getting the Help You Need
4002c24.qxd 7/18/01 1:28 AM Page 720
720
CHAPTER 24 • Creating an Excel Application
FIGURE 24.2 Use the Answer Wizard page of the Microsoft Excel Visual Basic Help file to ask a question and receive a list of associated topics.
• If you know the name of the topic you need to locate (for example, the name of the object, event, method, or property), use the Index tab (see Figure 24.3). Type one or more keywords in the text box (#1) or select from an alphabetical listing of keywords (#2). Type in a keyword and click Search or select a keyword from the listing and Excel will return a list of associated topics (#3). Select a topic to view it in the pane on the right. Excel will automatically insert semicolons between keywords you type on this page and perform a Boolean “and” search. For example, to find information on the Worksheet object, you might proceed as follows: 1. From the VBA Editor, choose Help Microsoft Visual Basic Help to display the Microsoft Visual Basic Help dialog box. 2. On the Contents tab, double-click the Microsoft Forms Reference main topic to display its subtopics. 3. Double-click the Microsoft Forms Object Model Reference to display the subtopics. 4. Double-click the Objects, Collections, and controls to display the alphabetic list of objects. 5. Expand the O–Z section, and click the Worksheet object to display its Help.
4002c24.qxd 7/18/01 1:28 AM Page 721
6. Click the Properties hyperlink to display the Topics Found dialog box (see Figure 24.4) containing a list of the properties available for the item you chose. Some help pages will display a drop-down list of properties, rather than the Topics Found dialog box. They all work the same. Alternatively, click the Methods, Events, or Specifics hyperlinks to display the associated lists for these items.
FIGURE 24.3 Use the Index page of the Microsoft Excel Visual Basic Help file to search for information by keywords.
FIGURE 24.4 Finding associated Properties for an Object in Help
7. Click one of the items in the Topics Found dialog box, and then click the Display button to see the Help associated with it.
721
PART
VII Automating Excel 2002 with Macros and VBA
Getting the Help You Need
4002c24.qxd 7/18/01 1:28 AM Page 722
722
CHAPTER 24 • Creating an Excel Application
The Help dialogs typically include some of the following hyperlinks to additional information: • The See Also hyperlink displays a Topics Found dialog box or list of topics associated with the Help topic you were viewing. • The Example hyperlink goes to the bookmarked Visual Basic Example on the current help page or to a new page if the example is more complex. Figure 24.5 shows an example that changes the order of tabs in a TabStrip control. If there is more than one example, Help displays a drop-down list of the choices. • The Applies To hyperlink (which appears for properties and methods) displays a drop-down list of the objects to which the property or method applies. • The Events hyperlink (which appears for objects) displays a drop-down list of the events associated with the object. • The Specifics hyperlink displays topics that are related to the current Help topic, but do not fit into any of the above categories.
FIGURE 24.5 The Example provided for the Index property
4002c24.qxd 7/18/01 1:28 AM Page 723
Using the Object Browser The Object Browser (see Figure 24.6) provides quick reference to the objects that Excel uses. FIGURE 24.6 Use the Object Browser to look up objects, properties, and methods.
To use the Object Browser, follow these steps: 1. Choose View Object Browser or press the F2 key to display the Object Browser. 2. In the Classes list box, select the class (the item) you want to investigate. The classes available in Microsoft Excel are objects, Microsoft Office constants (prefix Mso), Visual Basic constants (prefix Vb), and Excel constants (prefix Xl). The Members pane displays the members of the class—the properties, procedures, and functions associated with the class. The Description pane at the bottom of the Object Browser window lists the object’s class (for example, “Class Worksheet” if you select the Worksheet class). 3. In the Members pane, select the property, function, or procedure you want to learn more about. The Description pane lists the description of the member, together with its type. For example, the DisplayPageBreaks property for the
723
PART
VII Automating Excel 2002 with Macros and VBA
Getting the Help You Need
4002c24.qxd 7/18/01 1:28 AM Page 724
724
CHAPTER 24 • Creating an Excel Application
Worksheet class is a Boolean data type, so it is listed as “Property DisplayPageBreaks as Boolean.” If a property is read-only, the description box will display “read only” after the description. 4. For more information about an object, property, event, or method, select the item in the Members pane, then click the Help button. VBA Help opens, displaying the Help topic. 5. Select a member and click the Copy button to copy it to the clipboard for use in the Code Window 6. Click the Close button to close the Object Browser dialog box.
TIP If you know the property or method, but aren’t sure of the object, use the search function at the top of the Object Browser window. Enter a few letters of your search phrase, and all matching libraries, members, and classes will be displayed.
Integrating Excel with the Other Office Applications In this section, we’ll discuss how to use automation to integrate Excel with the other Office applications. Because this chapter and this book have a finite length, we will assume that you are familiar with the other Office applications and have had some experience working with them. In the sample application at the end of this chapter we will be using Excel and Word to produce a document with both Word prose and Excel data. When you open the VB IDE from an application, that application’s library is automatically loaded. In order to either use other Office objects in Excel or to send Excel objects to other Office programs, you must first load the library for that application. To automate Word, Outlook, PowerPoint, or another application from Excel, you must do the following: 1. Add a reference to the Object Library for the collaborative application. 2. Create an Application object within your VBA code. 3. Close the application when you are finished with it.
4002c24.qxd 7/18/01 1:28 AM Page 725
Adding Object Library References Add the Object Library reference for each Office XP application you will be using. After the reference is added, the objects, properties, and methods from each application’s object library will show up in the Object Browser. Help will be available for the referenced objects, and the syntax will be checked upon compile or run. In order to add a reference to the Object Library for other Office XP Applications from the Visual Basic IDE, follow these steps: 1. Select Tools References to display the References dialog box as shown in Figure 24.7. Note that four references are selected by default: Visual Basic for Applications, Microsoft Excel 10.0 Object Library, OLE Automation, and Microsoft Office 10.0 Object Library.
FIGURE 24.7 The available references for Excel, with the default object libraries selected
2. Scroll to locate the reference for the Office application you wish to use. The following are reference names for the other Office XP applications: • Microsoft Access 10.0 Object Library • Microsoft Outlook 10.0 Object Library • Microsoft PowerPoint 10.0 Object Library • Microsoft Word 10.0 Object Library • Microsoft Publisher 10.0 Object Library
725
PART
VII Automating Excel 2002 with Macros and VBA
Integrating Excel with the Other Office Applications
4002c24.qxd 7/18/01 1:28 AM Page 726
726
CHAPTER 24 • Creating an Excel Application
The following are other references that might come in handy: • Microsoft FrontPage 5.0 Page Object Reference Library • Microsoft FrontPage 5.0 Web Object Reference Library • Microsoft Graph 10.0 Object Library • Microsoft Office Web Components Function Library Spend a moment browsing the dialog box for the applications you might want to automate from Excel. If an application on your system can be automated, you’ll find an Object Library in this dialog box. 3. Select the libraries you wish to reference, and click OK. You must add libraries whenever your code includes external references.
Create an Application Object After you have set up the Object Library references, create an Application object for use in VBA procedures: 1. Declare object variables for each application to be used. You get to choose the variable name, and it’s beneficial if you can tell at a glance that the variable points to an Application object of a specific type, as in these declarative statements: Dim appAccess As Access.Application Dim appExcel As Excel.Application Dim appOutlook As Outlook.Application Dim appPowerPt As PowerPoint.Application Dim appWord As Word.Application
2. Use the CreateObject function to work with the application. Use this statement in conjunction with the declaration described in step 1; for example, to create an Access application object: Set appAccess = CreateObject(“Access.Application”)
Do this for each application other than Excel referenced in the VBA module. 3. If you wish to view the session of the other application, set the Visible property of the application object to True. If you simply want to run the application in the background, set the property to False. appAccess.Visible = True
4. When you are finished using the object, use the Quit method to close the application session: appAccess.Quit
4002c24.qxd 7/18/01 1:28 AM Page 727
Referencing Excel from another Office Application When you’re comfortable creating Excel applications, it takes only a few extra steps to automate Excel from other applications. Specifically, you must add the Excel Object Library as a reference, open the Excel application, and close it when you’re finished— the same tasks you must complete to automate another application from Excel. For illustration, we’ll create a subroutine in PowerPoint to take advantage of functionality that only appears in Excel 2002. Microsoft Excel 2002 is the only member of the Office XP family with built-in Text to Speech capabilities. The Speech object contains methods and properties that pertain to speech and can make your computer talk. The Speak method of the Speech object plays back the contents of a string or the contents of a cell. The following subprocedure, when created in PowerPoint’s Visual Basic IDE, uses Excel to read aloud the contents of a PowerPoint slide. First fire up PowerPoint and create a presentation with a slide. Type the words to be spoken on the slide. For this example, let’s assume that the text on our slide is “This is a talking PowerPoint Presentation.”
In the PowerPoint VB IDE, add the reference to the Excel 10.0 Object Library. Choose Insert Module and then enter this code: Sub ExcelTalk() ‘declare Excel application object Dim appExcel As Excel.Application ‘create Excel application object Set appExcel = CreateObject(“Excel.Application”) ‘show the slide ActivePresentation.SlideShowSettings.Run
727
PART
VII Automating Excel 2002 with Macros and VBA
Integrating Excel with the Other Office Applications
4002c24.qxd 7/18/01 1:28 AM Page 728
728
CHAPTER 24 • Creating an Excel Application
‘make the slide talk appExcel.Speech.Speak “this is a talking power point presentation.” ‘close Excel Application object appExcel.Quit SlideShowWindows(1).View.Exit End Sub
To test your code, click the Run button in the PowerPoint VBA IDE. This is a very simple procedure, which declares and opens an Excel object, displays a slide, and then closes the Excel object and ends the slide display. If Text to Speech is not currently installed, you are prompted to do so when the code runs.
NOTE
Within Excel you can use the Speak method of the Speech object to verbalize the contents of a range of cells as well as a string.
The Visual Basic Package Manager If you have the Developer’s Edition of Microsoft Office XP, Developer’s Studio, or a standalone version of Visual Basic, you can use the Visual Basic Package and Deployment Wizard to publish your Visual Basic, VBA, and VBScript applications. Use this wizard to create cabinet files (.cab extension) of your applications. Cabinets are single files that are like filing cabinets, storing and compressing the files needed by your application. You can then package your .cab files with all the other information needed for installation, such as a setup program and readme file. The Package and Deployment Wizard is a great time and space saver, even more so because there is also a Manage Scripts option that allows you to save and reuse scripts of all the choices you made for earlier applications during the wizard’s execution. To load the Package and Deployment Wizard, select Tools Add-Ins in the Visual Basic IDE. Select the Package and Deployment Wizard check box in the Add-Ins dialog box.
4002c24.qxd 7/18/01 1:28 AM Page 729
An Example: Retirement Countdown Application In this section, we’ll walk through the creation of an Excel-based application, the Retirement Countdown application. Retirement Countdown is more a collection of useful features than a full-strength application. Retirement Countdown could be used as part of a retirement planning seminar or a work-life balance class, but isn’t complex or complete enough to be packaged and sold as an off-the-shelf application. But while Retirement Countdown is limited in scope, the tools you will use to develop the application and the programming techniques covered can be reused and modified in countless other applications that will be useful in your business environment.
NOTE
Retirement Countdown uses the two user-defined functions created in Chapter 23, “Do-It-Yourself Functions.”
The Retirement Countdown process is as follows: • An individual fills out a form with their name, hire date, when they plan to retire, and whether they want to display the results in a letter, chart, or both. • Excel verifies the user-entered information. Errors produce a message box with the incorrect field highlighted, and the error message is spoken to the user. • When valid information has been entered for all fields, Excel calculates the years of seniority in a user-defined function and looks up the eligible vacation days in a spreadsheet range. • An Input box informs the user that they are eligible for a certain number of vacation days in the current year and asks them to enter the number of days they have taken. • Excel then calculates the total remaining vacation days, personal/sick days (estimated), remaining holidays (lookup on a spreadsheet range), weekend days (user-defined function), and total days until retirement (worksheet function). • The resulting data is used to create a pie chart. The total pie is total days until retirement, with slices for all the working and nonworking days. • The resulting data is used in Microsoft Word to create a form letter informing the user of how many of each type of day is left in their career.
729
PART
VII Automating Excel 2002 with Macros and VBA
An Example: Retirement Countdown Application
4002c24.qxd 7/18/01 1:29 AM Page 730
730
CHAPTER 24 • Creating an Excel Application
The Retirement Countdown includes several new skills as well as some information from previous chapters. Application tasks include how to use UserForms, Message and Input boxes, data validation, the Speech object, and user-defined functions, as well as how to create a chart with VBA and collaborate with another Office application. Retirement Countdown gathers data with a user form and an input box: • The Retirement Countdown User Form (shown in design mode in Figure 24.8) is the starting point for the application. The user enters a name, hire date, and planned retirement date, as well as selects the format in which the Retirement Countdown results will be presented.
FIGURE 24.8 Filling out the Retirement Countdown form is the first step in the Retirement Countdown application process.
• The Enter Remaining Vacation Days input box pops up after the user data from the Retirement Countdown form has been validated. The user is prompted to enter the number of unused vacation days left this year. The number of days entered will be used in the Retirement Countdown calculation (see Figure 24.9).
FIGURE 24.9 The user is asked how many vacation days remain in the current year.
4002c24.qxd 7/18/01 1:29 AM Page 731
Creating the Retirement Countdown Form
PART
VII Automating Excel 2002 with Macros and VBA
There are two constants that Retirement Countdown uses to determine available vacation days and holidays. The constants are retrieved from two tables in a worksheet named Constants, shown in Figure 24.10.
731
FIGURE 24.10 These two lookup tables express the business rules for vacation days and holidays. Retirement Countdown includes user-defined functions that search the two tables: Vacation Days by Seniority A two-column range whose number of rows and values will vary by company. Column 1 is the number of vacation days given to employees who have at least the number of years of service in Column 2. Annual Holidays Will vary by company. Since the dates of some holidays vary from year to year, we will simplify matters by simply placing the constant for the total annual holidays and estimate the holidays already taken in the current year and the number of days to be taken in the retirement year by calculating the fraction of the year already worked and the number of holidays within that proportion.
Creating the Retirement Countdown Form First, we’ll create the user interface: the Retirement Countdown UserForm. This simple form gathers the information needed to perform the Retirement Countdown calculation. Begin by opening the Excel workbook where you created the Years of Service and Count Weekends functions in Chapter 23, “Do-It-Yourself Functions.” Dog ate your workbook? That’s OK; download the UserDef Functions.xls workbook from the Sybex website.
Creating the Form In the workbook that contains the two user-defined functions from Chapter 23: 1. Choose Tools Macro Visual Basic Editor, or press Alt+F11 to open the Visual Basic IDE.
4002c24.qxd 7/18/01 1:29 AM Page 732
732
CHAPTER 24 • Creating an Excel Application
2. To create a blank UserForm select Insert UserForm from the menu or click the UserForm button on the Standard toolbar. Excel creates a UserForm called UserForm1 as shown in Figure 24.11. Note that your VBA project file now contains Microsoft Excel objects, forms, and modules.
FIGURE 24.11 A new UserForm, waiting to be customized
3. Click on the UserForm1 window to open the UserForm1 Properties window. (If the Properties Window is not displayed, select the UserForm and choose View Properties Window.) Change the following properties: Name = frmRetire Sets the object name of the UserForm to frmRetire, which follows standard naming conventions for Visual Basic. Caption = Retirement Countdown Places Retirement Countdown in the title bar of the UserForm window. Your UserForm will now resemble Figure 24.12.
4002c24.qxd 7/18/01 1:29 AM Page 733
Creating the Retirement Countdown Form
FIGURE 24.12 A Userform with the Name and Caption properties set
733
PART
Automating Excel 2002 with Macros and VBA
VII
Adding Controls to the Form The next step is to add controls to the UserForm. This form will contain the following: • A text box and label to hold the user’s name • A text box and label to hold the user’s hire date • A text box and label to hold the user’s planned retirement date • A set of three option buttons that the user will use to select the delivery method of the results of the calculation • A command button that starts the Retirement Calculation process
Adding Text Boxes and Label Controls We will add VBA code behind each of these controls in order to edit the data entered in the text boxes. For now, we will simply create the controls and format them on the UserForm. 1. If it is not already displayed, display the Toolbox by clicking the toolbox icon on the Standard toolbar or by selecting View Toolbox.
4002c24.qxd 7/18/01 1:29 AM Page 734
734
CHAPTER 24 • Creating an Excel Application
2. Click the TextBox button in the Toolbox and drag it to the top of the UserForm. Then click the Label button in the Toolbox and drag it to the left of the TextBox you just created. 3. Update the properties of the TextBox. Select the TextBox on the UserForm. Change the name from TextBox1 to txtName. Type the following in the ControlTipText property: Enter your first and last name.
TIP
The Control Tip text box will pop up when the user moves the mouse over the text box. Use this property to give helpful hints on data entry requirements.
4. Update the properties of the label you just placed on the UserForm. Select the label in the UserForm and change the following properties in the Properties Window: • Name = lblName • Caption = Name: • AutoSize = True (automatically sizes the label depending on its contents) • WordWrap = False (prevents words in the label from wrapping onto subsequent lines) • Change the Font size by selecting the Font property in the Properties window. Click the Build button to open the Font dialog box. Select Font Style = Bold and Size = 10 to make the labels more readable.
4002c24.qxd 7/18/01 1:29 AM Page 735
5. Add two more text boxes and labels to your UserForm. Name the text boxes dteHireDate and dteRetireDate and name the labels lblHireDate and lblRetireDate. Create captions and format the labels like you did for lblName and txtName. Add ControlTipText of Enter your hire date in mm/dd/yyyy format for dteHireDate and Enter your planned retirement date in mm/dd/yyyy format for dteRetireDate.
Resizing and Aligning Controls With the text boxes and labels placed on the form, it’s time to resize and align the controls so the form has a tidy, uniform appearance. 1. Select the three labels (lblName, lblHireDate, and lblRetireDate) by either dragging the mouse pointer so it catches all three labels or by clicking on a label and then pressing the Shift key or the Ctrl key and clicking the remaining labels. 2. Right-click the labels and select Align Rights. Move the aligned labels so they are positioned properly on the UserForm. 3. Select the text box dteHireDate and size it using the mouse so that it is large enough to hold the date, but not as wide as the txtName text box. The relative size of the two text boxes helps the user know that one entry will be longer than the other. With dteHireDate selected, hold the Shift key and click on dteRetireDate to select it, too. Right-click the date text boxes and select Make Same Size Both.
TIP
When you use the Shift key to select multiple controls, the first control selected is the “master” control, so to speak. It is the control to which the subsequently selected controls are sized or aligned. On the other hand, using the Ctrl key to select multiple controls will make the last control selected the “master” control. You can tell the “master” control because the handles on the border are white. The other controls have black handles.
4. Select all three text boxes (txtName, dteHireDate, and dteRetireDate). Rightclick on the selection and select Align Lefts. After the text boxes are aligned, move them so they are lined up with the appropriate labels. 5. If the labels and their related text boxes are not aligned horizontally, select both the label and text box and use the Align Middles command. 6. After you have sized and aligned all the controls, select all six controls. Rightclick and select Group so you can move the controls as one if the UserForm requires further adjustment. You can always ungroup the controls by right-clicking and selecting Ungroup. With the text boxes, labels, and form properties in place, your UserForm should look a lot like the form shown in Figure 24.13.
735
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Retirement Countdown Form
4002c24.qxd 7/18/01 1:29 AM Page 736
736
CHAPTER 24 • Creating an Excel Application
FIGURE 24.13 The Retirement Countdown form now has three text boxes and labels in place, but little else.
Adding Option Groups and Command Buttons Next we will add a frame containing option button controls (known as radio buttons to some of us old-timers), a command button to start the Retirement Calculation process, and a Cancel command button. In an option group, the option buttons represent mutually exclusive choices. When a user chooses one button, they are “unchoosing” the other buttons in the group. VB knows that the buttons are a group (and, therefore, behave this way), because they are created within the same frame control. In Retirement Countdown, the user will select one of three methods of displaying the results of their personal retirement calculation. The Retirement Countdown application can create a pie chart, automate Microsoft Word to generate a form letter, or create both a chart and a letter. 1. Select the Frame control in the Toolbox and drop it on the bottom left section of the UserForm. Name the frame fraOutput and set the Caption property to Output Options. Set the Font Style to Bold and the Font Size to 10. 2. Select the OptionButton control in the Toolbox and place three option buttons within the frame you just created. The first button (which in our application produces an Excel chart) is the default. The default button is initially set to True, so if the user makes no choice, they get a chart. Selecting either of the other
4002c24.qxd 7/18/01 1:29 AM Page 737
option buttons selects the attached option. Set the option button properties to the following: • button 1: Name = btnChart; Caption = Chart; Font Size = 10; Value = True • button 2: Name = btnLetter; Caption = Letter; Font Size = 10 • button 3: Name = btnBoth; Caption = Both; Font Size = 10 3. Select the CommandButton control in the Toolbox and place two command buttons on the bottom right side of the UserForm. Set their properties to the following: • Name = cmdOK; Caption = OK; Font Size = 11; Font Style = Bold • Name = cmdCancel; Caption = Cancel; Font Size = 11; Font Style = Bold The frmRetirement layout is now complete. It should look something like the form shown in Figure 24.14. FIGURE 24.14 The Retirement Countdown form
Creating the Code The form looks fine, but it doesn’t do anything. Click the buttons and nothing happens. We’re using controls in three different ways: for input, labeling, and commands. The option buttons, frame, and text boxes are input controls, used to collect data from the user. The labels label the input controls. We won’t be attaching code to any of these controls. In this form, as in many forms, all the code is attached to the command buttons and refers to information entered in the other controls.
737
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 738
738
CHAPTER 24 • Creating an Excel Application
Coding the Cancel Command Button The code for the Cancel button is exceedingly simple. When the user clicks the cancel button, the Retirement Countdown application stops running and the Retirement Countdown form closes. 1. To add code to the cmdCancel button, double-click the button. The code window for frmRetire is displayed, with the start and end statements for the cmdCancel_Click subroutine already entered:
2. Indent by pressing the Tab key once and enter the following statement: Unload frmRetire
To test this code, click the Run button on the Toolbar. The Retirement Countdown form is displayed. Click the Cancel button and the Retirement Countdown form closes and you return to the Visual Basic IDE. Figure 24.15 shows the Retirement Countdown form during runtime. The data entry tip for the Name field is displayed because the mouse is over that text box. FIGURE 24.15 The Retirement Countdown form as it appears to the user. The Control Tip is displayed for the Name text field.
4002c24.qxd 7/18/01 1:29 AM Page 739
Coding the OK Command Button The OK button is more challenging. Several actions must take place when the user clicks the OK button: 1. The data entered by the user must be verified. 2. An input box queries the user about remaining vacation days. 3. The days until retirement calculation is performed. This calculation takes into account weekends, holidays, vacation days, and sick/personal days. The number of nonworking days is determined by lookups on a constants worksheet, as well as by using user-defined functions. 4. Finally, the results are presented to the user in either an Excel chart or a Word document format, or both.
Validating User Data To accomplish this task, we will create user-defined functions that are called when a user action fires the Click event of the cmdOK button. This function, called basVerify, will check the values in the three text boxes on the Retirement Countdown form and respond with both a verbal description and a message box if any errors are encountered. Here are the rules we’ll use to see if the data is valid: • The name field must be filled in. Test this by ensuring that the length of the field txtName must be greater than zero. • The date fields must be in mm/dd/yyyy format. • The Retirement Date must be in the future. • The Hire Date must be in the past. All of the validation code is attached to the cmdOK button. 1. To add code to the cmdOK button, double-click the button. The code window for frmRetire is displayed, with a stub for the second subroutine cmdOK_Click below the cmdCancel_Click subroutine. 2. Define three variables that we’ll use to store the results of the validation check of each of the three text boxes. The variables NameValid, HireDteValid, and RetireDteValid will contain zero if the data entered by the user was valid; they will contain values of 1, 2, or 3 depending on the error encountered. These variables will be used to parse the Error Type and Error Number arguments required by the error messaging function.
739
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 740
740
CHAPTER 24 • Creating an Excel Application
3. Use the TextLength property of the text box txtName to validate that a name was entered on the form. Set the variable NameValid to 0 if the TextLength is greater than 0 or to 1 if the TextLength is 0 (in other words, if there’s no text in the text box). 4. There are two checks we want to perform on the date text boxes dteHireDate and dteRetireDate. First, we’ll check the TextLength property to see if the user entered anything in the text box. If the user failed to enter data, we’ll set the value in HireDteValid or RetireDteValid to 3. If the user has entered data in the fields, then we’ll call a user-defined function to perform further checks on the entry. The following is the first half of the cmdOK_Click subroutine. After the date validation functions have been created, we will add the rest of the cmdOK_click subroutine, which calls the error messaging function. Private Sub cmdOK_Click() ‘declare variables to hold validation results Dim NameValid As Integer Dim HireDteValid As Integer Dim RetireDteValid As Integer ‘check that a name was entered txtName.SetFocus If txtName.TextLength > 0 Then ‘user has entered something in the txtName text box NameValid = 0 Else ‘user did not enter text in the txtName text box NameValid = 1 End If ‘If date fields were entered call user-defined functions to validate them dteHireDate.SetFocus If dteHireDate.TextLength > 0 Then ‘user entered text in dteHireDate, so validate HireDteValid = basVerifyHireDate(dteHireDate) Else ‘no entry in dteHireDate HireDteValid = 3 End If
4002c24.qxd 7/18/01 1:29 AM Page 741
dteRetireDate.SetFocus If dteRetireDate.TextLength > 0 Then ‘user entered text in dteRetireDate, so validate RetireDteValid = basVerifyRetireDate(dteRetireDate) Else ‘no entry in dteRetireDate RetireDteValid = 3 End If . . . Error Messaging Code to be added here . . End Sub
WARNING
If you didn’t create the two user-defined functions back in Chapter 23, go back and do it now. You will need Module1, as well as the functions basCountWeekends and basYrsService to complete this application. Or if you already understand user-defined functions, feel free to download the UserDef Functions.xls workbook from the Sybex website.
Now we need to create two functions to verify the text entered in the dteHireDate and dteRetireDate text boxes. Create these two public functions in Module 1. First, create public function basVerifyHireDate, and define the passed argument (dteHireDate) as a date. The function will perform two checks. We’ll use the IsDate function to make sure that a valid date was entered by the user. If the date is valid, we’ll use the DateValue function to convert the string argument dteHireDate to an integer and compare the integer to the current date (represented by the Date keyword) to ensure that the Hire Date entered is in the past. If both conditions are met, the value of the function is set to zero. If there are any errors, the value of the function is set to 1 or 2. Here is the code for the basVerifyHireDate function: Public Function basVerifyHireDate(dteHireDate As String) ‘This function validates the Hire Date. It returns 3 possible values: ‘ 0 if the date is valid ‘ 1 if the date is not in valid date format ‘ 2 if the date is not in the past
741
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 742
742
CHAPTER 24 • Creating an Excel Application
‘define a variable to hold interim validation data Dim ValidDate As Boolean ‘set the value of the function to a date format error initially basVerifyHireDate = 1 ‘Format the Hire Date to General Date format dteHireDate = FormatDateTime(dteHireDate, vbGeneralDate) ‘determine if the hire date is in valid date format and in the past ‘if all conditions are met, set the value of the function to 0 ValidDate = IsDate(dteHireDate) If ValidDate = True Then If DateValue(dteHireDate) < Date Then basVerifyHireDate = 0 Else basVerifyHireDate = 2 End If End If End Function
Now, create a similar public function called basVerifyRetireDate in Module1. The code appears below. You can save time by using copy and paste. Copy the basVerifyHireDate code, paste it below the End Sub of the basVerifyHireDate subroutine, and edit so you end up with this code, which verifies that the passed argument is a date and that the date is in the future: Public Function basVerifyRetireDate(dteRetireDate As String) ‘This function validates the Retire Date. It returns 3 possible values: ‘ 0 if the date is valid ‘ 1 if the date is not in valid date format ‘ 2 if the date is not in the future ‘define a variable to hold interim validation data Dim ValidDate As Boolean ‘set the value of the function to a date format error initially
4002c24.qxd 7/18/01 1:29 AM Page 743
basVerifyRetireDate = 1 ‘Format the Hire Date to General Date format dteRetireDate = FormatDateTime(dteRetireDate, vbGeneralDate) ‘determine if the passed date is in valid date format and in the past ‘if all conditions are met, set the value of the function to 0 ValidDate = IsDate(dteRetireDate) If ValidDate = True Then If DateValue(dteRetireDate) > Date Then basVerifyRetireDate = 0 Else basVerifyRetireDate = 2 End If End If End Function
TIP
Get used to using the IsDate and DateValue functions. The text box control always returns text (go figure!), which must then be converted to a date.
Generating Error Messages In order to complete the verification code, the return conditions must be checked and error codes and messages generated. We’ll create one user-defined function, basErrorMsg, that does the following: • Receives the error type and error code as a passed parameter • Speaks the error message • Displays a message box containing details about the error • Returns the user to the Retirement Countdown form to correct their entry We haven’t written this function yet, but we can add the code to call the function basErrorMsg to the end of subroutine cmdOK_Click while we’re adding the return conditions check. At the same time, we will add a call to another as-yet-uncoded subroutine, CalcRetirement. To call a subroutine like CalcRetirement, use the command
743
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 744
744
CHAPTER 24 • Creating an Excel Application
Call, followed by the function name and the list of passed parameters in parentheses, much like an Excel function: Call CalcRetirement (txtName, dteHireDate, dteRetireDate)
This is how the cmdOK_Click subroutine will look when you are finished: Private Sub cmdOK_Click() ‘declare variables to hold validation results Dim NameValid As Integer Dim HireDteValid As Integer Dim RetireDteValid As Integer ‘check that a name was entered txtName.SetFocus If txtName.TextLength > 0 Then NameValid = 0 Else NameValid = 1 End If ‘If date fields were entered call user-defined functions to validate them dteHireDate.SetFocus If dteHireDate.TextLength > 0 Then HireDteValid = basVerifyHireDate(dteHireDate) Else HireDteValid = 3 End If dteRetireDate.SetFocus If dteRetireDate.TextLength > 0 Then RetireDteValid = basVerifyRetireDate(dteRetireDate) Else RetireDteValid = 3 End If ‘declare and initialize variables for error messages Dim ErrorType As Integer Dim ErrorNum As Integer ErrorType = 0 ErrorNum = 0
4002c24.qxd 7/18/01 1:29 AM Page 745
‘Call the error message function and return to the user form ‘if any validation errors were found ‘This only finds one error at a time ‘is there text in txtName? If NameValid > 0 Then ErrorType = 1 ErrorNum = NameValid Else ‘is txtHireDate valid? If HireDteValid > 0 Then ErrorType = 2 ErrorNum = HireDteValid Else ‘is txtRetireDate valid? If RetireDteValid > 0 Then ErrorType = 3 ErrorNum = RetireDteValid End If End If End If If ErrorType + ErrorNum > 0 Then ‘Houston, we have an error Call basErrorMsg(ErrorType, ErrorNum) GoTo ErrorExit End If ‘Call the Calculation Subroutine Call CalcRetirement (txtName, dteHireDate, dteRetireDate) ErrorExit: End Sub
The new code added to cmdOK_Click performs the following tasks: • Creates and initializes the ErrorType and ErrorNumber variables • Sets the ErrorType and ErrorNumber if any of the data entry fields was invalid • If any errors are found, calls the ErrorMessage user-defined function • Exits the subroutine and displays the Retirement Countdown form once again
745
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 746
746
CHAPTER 24 • Creating an Excel Application
There’s one more item to put in place before we can test our validation routines: the ErrorMessage function in Module1: 1. Create a public function called basErrorMsg in Module1, and define the passed arguments (ErrorType and ErrorNum) as integers. The error message to be spoken and the information to appear in the message box are formatted based on arguments sent to the function. While we could use an If/Then structure for this function, we’ll use the Case structure, a frequently used alternative to If/Then.
NOTE
For information on Case, If/Then, and other VB structures, see Appendix B, “VBA Quick Reference.”
Here is the code for basErrorMsg: Public Function basErrorMsg(ErrorType As Integer, ErrorNum As Integer) ‘Define variables to hold error message strings Dim SpeakMsg As String Dim ShowMsg As String ‘Parse error messages based on error type and number ‘Set focus on the field in error Select Case ErrorType Case 1 frmRetire.txtName.SetFocus SpeakMsg = “Please enter your name” ShowMsg = “The Name field is empty” Case 2 frmRetire.dteHireDate.SetFocus Select Case ErrorNum Case 1 SpeakMsg = “Please enter a valid hire date” ShowMsg = “The hire date format is mm/dd/yyyy” Case 2 SpeakMsg = “Please enter a date before today” ShowMsg = “The hire date must be in the past”
4002c24.qxd 7/18/01 1:29 AM Page 747
Case 3 SpeakMsg = “We need a hire date to calculate” ShowMsg = “The Hire Date field is empty” End Select Case 3 FrmRetire.dteRetireDate.SetFocus Select Case ErrorNum Case 1 SpeakMsg = “Please enter a valid retirement date” ShowMsg = “The retirement date format is mm/dd/yyyy” Case 2 SpeakMsg = “Please enter a date after today” ShowMsg = “The retirement date must be in the future” Case 3 SpeakMsg = “We need a retirement date to calculate” ShowMsg = “The Retirement Date field is empty” End Select End Select ‘Display the error message box and speak the error message Application.Speech.Speak (SpeakMsg) MsgBox (ShowMsg) End Function
2. Select Debug Compile VBA Project, and fix any syntax errors that the VB compiler found. Before going any further, test your validation code.
Testing Your Validation Code It is good programming practice to test new code in manageable chunks. Now that the validation process coding is complete, it is time to test your new code for any syntax or logic errors. The first step is to define the test cases to use to test all the possible error conditions. When you create test cases, test every type of correct and incorrect value. Table 24.1 shows different conditions to test on the Retirement Countdown form.
747
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 748
748
CHAPTER 24 • Creating an Excel Application
TABLE 24.1
Te x t C a s e s f o r Va l i d a t i n g R e t i r e m e n t C a l c u l a t i o n D a t a E n t r y
Field
Data Entered
Expected Result
Name
Blank
Name Required error
Name
Jeanne
Continue processing
Name
12345678
Continue processing
HireDate
Blank
Hire Date Required error
HireDate
Augoost 4, 98
Invalid Hire Date Format error
HireDate
3/31/04
Hire Date in Future error
HireDate
Today
Invalid Hire Date Format error
HireDate
December 8, 1965
Continue processing
HireDate
1/1/01
Continue processing
HireDate
12/31/99
Continue processing
RetireDate
Blank
Retire Date Required error
RetireDate
2/29/2003
Invalid Retire Date Format error
RetireDate
Next Week
Invalid Retire Date Format error
RetireDate
11/25/2000
Retire Date in Past error
RetireDate
January 27, 2015
Continue processing
RetireDate
2/29/04
Continue processing
When creating applications, for use in your organization or for others, the first way to ensure quality and robustness is to include thorough data entry verification and detailed error messages. Passing invalid data to a calculation can be hazardous to the health of your results! Open the frmRetire UserForm and click Run on the Standard toolbar. Test the Cancel button (an early, easy success), and then enter each of the test data combinations in the Name, Hire Date, and Retirement Date fields using Table 24.1 as a guide. Note that only one error message is generated at a time, so if invalid data is entered in all three fields, only the first error message encountered by the basErrorMessage function will display. More complex applications will allow multiple errors to be simultaneously displayed.
4002c24.qxd 7/18/01 1:29 AM Page 749
Calculate Retirement Values Now that pristine data is assured, let’s code the subroutines and functions needed to calculate the number of working days until retirement. The CalcRetirement subroutine is the core process that calls all of the user-defined functions, collects the values returned by the functions, and sends them to the DisplayOutput subroutine.
The CalcRetirement Subroutine Create a new subprocedure in Module1 by clicking on Module1 and selecting Insert Procedure. In the Add Procedure dialog box, select the Sub Type and Public Scope. Name the subprocedure CalcRetirement. CalcRetirement performs the following tasks: • Defines variables used in the procedure. • Performs simple calculations to extract required data such as total days between today and the retirement date, and the numeric values of the current month and retirement month. • Calls the user-defined function basYrsService, passing the argument dteHireDate to determine user’s seniority. The function returns intYearsService. • Calls the user-defined function basCalcVacation, passing the arguments intYearsService and dteRetireDate. basCalcVacation looks up eligible vacation days for each year from the current year until the year of retirement from the spreadsheet (refer back to Figure 24.10). With the lookup values, it calculates total future vacation days, with special logic for the current year (an input box is displayed to the user asking how many vacation days they have left in the current year) and the retirement year (the number of vacation days for a partial year is calculated using ratios). The function returns the total upcoming vacation days. • Calls the user-defined function basCalcHolidays, passing the argument dteRetireDate. CalcHolidays calculates total holidays and which users will be entitled to take those holidays, with special logic for current and retirement year (the number of holidays for a partial year is calculated using ratios). The function returns the total upcoming holiday days. • Calculates the total number of weekdays and weekends between the current date and the retirement date by calling the user-defined function basCountWeekends and passing the argument dteRetirementDate. The function returns the total weekend days.
749
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 750
750
CHAPTER 24 • Creating an Excel Application
• Calls the subroutine DisplayOutput, passing all of the accumulated totals. Depending on the output option chosen on the Retirement Countdown form, DisplayOutput will either generate a pie chart with total days until retirement (broken into working days, weekends, vacations, and holidays) or generate a form letter with the same information in prose form. It can also generate both. The code for the CalcRetirement subroutine is shown here: Public Sub CalcRetirement() ‘declare variables to use in calculations Dim intTotalVacDays As Integer Dim intTotalHolidays As Integer Dim intTotalWeekendDays As Integer Dim intTotalDays As Integer Dim intYearsService As Integer Dim dteToday As Date ‘get the total days until retirement dteToday = Date intTotalDays = DateValue(dteRetireDate) - dteToday ‘call the Years of Service function to determine seniority intYearsService = basYrsService(dteHireDate) ‘call the Calculate Vacation function to determine total vac days intTotalVacDays = basCalcVacation(intYearsService, dteRetireDate) ‘call the Calculate Holdiays function to determine total holidays intTotalHolidays = basCalcHolidays(dteRetireDate) ‘call the Count Weekends function to determine total weekend days intTotalWeekendDays = basCountWeekends(dteRetireDate) ‘call the Display Output subroutine, passing all of the accumulated totals Call DisplayOutput(intTotalDays, intTotalVacDays, intTotalHolidays, intTotalWeekendDays) End Sub
4002c24.qxd 7/18/01 1:29 AM Page 751
The Constants Worksheet The Vacation and Holiday functions will look up eligible vacation days and the number of holidays in a year on the Constants worksheet. To add the data needed for the Retirement Application, follow these steps: 1. Return to the Excel worksheet for the current project. Select Sheet1 and rename it Constants. 2. Add the following data as shown in Table 24.2, and shown in Figure 24.16:
TABLE 24.2
Constants Used in Retirement Countdown
Cell
Value
A2
Type of Day Off
A3
Annual Holidays
A4
Annual Sick/Personal Days
A5
Annual Available Days
B2
Total
B3
10
B4
14
B5
=SUM(B3:B4); Name this cell AnnualDays
D2
Minimum Years
D3
0
D4
5
D5
10
E2
Vacation Days
E3
10
E4
15
E5
20
Your spreadsheet should look like Figure 24.16. The formatting is for readability. Cell range A2 through B5 contains the annual holiday data. This will vary by organization. Cell range D2 through E5 contains the eligible vacation days based on seniority. In this example, employees with 0–4 years of seniority get 10 vacation days, those with 5–9 years get 15 vacation days, and those with over 10 years get 20 vacation days. By placing this data in a worksheet rather than in code, the application can be easily changed as the business rules of the organization change.
751
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 752
752
CHAPTER 24 • Creating an Excel Application
FIGURE 24.16 The Constants worksheet used by Retirement Countdown
The basCalcVacation Function The basCalcVacation function will calculate the number of unused vacation days remaining before retirement by performing the following tasks: 1. Calculate the total years of service at retirement. The current earned years of service is passed to the function as an argument. 2. Using an input box, get the number of vacation days remaining in the current calendar year.
3. For each full year until retirement the user is eligible for a full number of vacation days dependent on seniority at the time. In the sample there are three levels of vacation. If the user has at least 10 years of service they receive 20 vacation
4002c24.qxd 7/18/01 1:29 AM Page 753
days; with at least 5 years of service they receive 15 vacation days, and starting their first year (0 years of service) they receive 10 vacation days. The function will loop through the seniority years from next year until the year before retirement (all of the full years). For each full year, the number of vacation days corresponding with the years of seniority will be accumulated. 4. Calculate the partial year holidays for the retirement year. For this example, we will assume that a proportional number of vacation days are granted for each month worked. If there are 20 vacation days per year and 3 months total in the retirement year (i.e., the user will retire in March), the vacation days for the retirement year would be 5. 5. The total vacation days are accumulated, and the function sends back this value as an integer to the calling subprocedure, CalcRetirement. Here is the code required to accomplish the tasks related to calculating vacation days: Public Function basCalcVacation(intYearsService, dteRetireDate) As Integer ‘declare variables Dim currYear As Integer Dim retireYear As Integer Dim retireMonth As Integer Dim accumVacDays As Integer Dim currVacDays As Integer Dim retireVacDays As Integer Dim intRetireYearsService As Integer Dim dteToday As Date dteToday = Date ‘set the years and months used in calculations currYear = Year(dteToday) retireMonth = Month(DateValue(dteRetireDate)) retireYear = Year(DateValue(dteRetireDate)) ‘calc total years of service at retirement intRetireYearsService = intYearsService + retireYear - currYear ‘get current year vacation days ‘because this is just a sample application, assume they entered a ‘number. If nothing entered, value of currVacDays is 0.
753
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 754
754
CHAPTER 24 • Creating an Excel Application
currVacDays = inputbox(“How many vacation days do you have left this_ year?”, “Enter remaining vacation days”) ‘get full years vacation days For x = (intYearsService + 1) To (intRetireYearsService - 1) If x < Worksheets(“Constants”).Range(“D5”).Value Then If x < Worksheets(“Constants”).Range(“D4”).Value Then accumVacDays = accumVacDays + Worksheets(“Constants”).Range(“E3”).Value Else accumVacDays = accumVacDays +_ Worksheets(“Constants”).Range(“E4”).Value End If Else accumVacDays = accumVacDays +_ Worksheets(“Constants”).Range(“E5”).Value End If Next x ‘get retirement year vacation days If intRetireYearsService < Worksheets(“Constants”).Range(“D5”).Value Then If intRetireYearsService < Worksheets(“Constants”). Range(“D4”).Value Then RetireVacDays Round(Worksheets(“Constants”)._ Range(“E3”).Value*retireMonth/12, 0) Else retireVacDays = Round(Worksheets(“Constants”). Range(“E4”).Value *_ retireMonth/12, 0) End If Else retireVacDays = Round(Worksheets(“Constants”)._ Range(“E5”).Value*retireMonth/12, 0) End If ‘set the value of the function to the grand total basCalcVacation = currVacDays + accumVacDays + retireVacDays End Function
4002c24.qxd 7/18/01 1:29 AM Page 755
The basCalcHolidays Function The basCalcHolidays function will calculate the number of holidays (as well as personal/sick days) remaining before retirement by performing the following tasks: 1. Calculate the years between now and retirement. If the current year is 2001 and the Retirement Date is 2014, there are 13 years until retirement. 2. For each full year until retirement the user is eligible for a full number of holidays. Calculate the full years until retirement by subtracting 1 from the actual years until retirement. If there are 13 years until retirement, there are 12 full years until retirement. If there are 24 holidays and sick days in a year, the total full-year holidays value is 288. 3. Calculate the partial year holidays for the current year and the retirement year. For the sake of simplicity, we will assume that holidays and sick days are spaced proportionately throughout the calendar year. (Even though we know that August has never had, and desperately needs, a holiday. We’ve proposed a “Take Your VBA Programmer to Hawaii” holiday for August, but aren’t getting much support from management.) In this simplification, if there are 24 holidays and sick days per year, there are two per month. If there are 7 months left in the current year and 7 months total in the retirement year, there are a total of 14 holidays and sick days for both the current year and the retirement year. Using ratios does not give the exact amount, but for our sample application we will forgo referencing a calendar for actual holidays for every possible year between today and a user’s retirement.
TIP
If we were going to use exact holiday dates, we’d need a table in Excel or another database. Outlook only stores holidays six years in the future.
4. The total holidays are accumulated, and the function sends back this value as an integer to the calling subprocedure, CalcRetirement. Here’s the code needed to calculate holidays: Public Function basCalcHolidays(dteRetireDate) As Integer Dim currYear As Integer Dim retireYear As Integer Dim currMonth As Integer Dim retireMonth As Integer Dim intYrsTillRetire As Integer Dim intFullYears As Integer
755
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 756
756
CHAPTER 24 • Creating an Excel Application
Dim dteToday As Date dteToday = Date ‘set the years and months currMonth = Month(dteToday) currYear = Year(dteToday) retireMonth = Month(DateValue(dteRetireDate)) retireYear = Year(DateValue(dteRetireDate)) ‘calculate years till retirement and full years intYrsTillRetire = retireYear - currYear intFullYears = intYrsTillRetire - 1 ‘find the total Annual holidays on the Constants spreadsheet intAnnualHolidays=Worksheets(“Constants”).Range(“AnnualDays”).Value ‘calculate total holidays for full and partial years intFullHolidays = intAnnualHolidays * intFullYears intCurrHolidays = Round(intAnnualHolidays * (12 - currMonth)/12, 0) intLastHolidays = Round(intAnnualHolidays * retireMonth/12, 0) ‘set the value of the function to the grand total basCalcHolidays = intFullHolidays+intCurrHolidays+intLastHolidays End Function
The basCountWeekends and basYrsService Functions As you may recall, the basCountWeekends and basYrsService functions were created back in Chapter 23, “Do-It-Yourself Functions.” If you haven’t created them yet, do so now or download the UserDef Functions.xls workbook from the Sybex website. Both functions are called by CalcRetirement, and the values they return are crucial to the Retirement Countdown calculation.
The DisplayOutput Subroutine Last but not least, we have the DisplayOutput subprocedure. This routine encompasses most of the topics covered in Part VII, “Automating Excel 2002 with Macros and VBA.” In a nutshell, DisplayOutput performs the following tasks: 1. Turns off alerts so that Retirement Countdown can open, close, create, and delete documents, worksheets, and charts without those annoying “Are you sure?” message boxes.
4002c24.qxd 7/18/01 1:29 AM Page 757
2. Creates a temporary worksheet called TempSheet to hold the results from the Retirement Countdown calculations. TempSheet is used as input for creating the Pie Chart. 3. Interrogates the option buttons from the Retirement Countdown form to determine if an Excel chart, Word document, or both should be created. 4. If the user has requested a Chart, a new chart sheet named “Pie Chart” is inserted, and a pie chart is created using the data on the TempSheet worksheet. The ChartWizard method is used to initially format the new chart, but some of the SeriesCollection object properties require manual tweaking. The Retirement Countdown form is unloaded and the Pie Chart sheet is print previewed. The user can either print or close the window. Once action is taken on the Print Preview window, the Pie Chart sheet is deleted and execution continues. A sample Pie Chart is shown in Figure 24.17.
FIGURE 24.17 A sample Pie Chart
757
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 758
758
CHAPTER 24 • Creating an Excel Application
5. If the user has requested a letter, a new Word application object is created. The Visible property is set to True so the user can view the document before printing. A new temporary document named document1 is created, and some parsed text is inserted into the document using the InsertParagraphBefore method. Word is set to be the active window, and the document is print previewed. The user can either print or close the window. Word then quits without saving changes. A sample letter is shown in Figure 24.18.
FIGURE 24.18 A sample Retirement Countdown letter
6. The last function performed by DisplayOutput is the deletion of the worksheet TempSheet. After that, the coding is complete. The code for DisplayOutput is as follows: Public Sub DisplayOutput(intTotalDays, intTotalVacDays,_ intTotalHolidays, intTotalWeekendDays, txtName) ‘Hide annoying message boxes when trying to close and delete Application.DisplayAlerts = False ‘calculate total workdays
4002c24.qxd 7/18/01 1:29 AM Page 759
intTotalWorkDays = intTotalDays - intTotalVacDays - _ intTotalHolidays - intTotalWeekendDays ‘create a new worksheet object with Total workdays, total vacation _ days, ‘total holidays and total weekends in column A ActiveWorkbook.Worksheets.Add Before:=Sheets(1) Worksheets(1).Name = “TempSheet” Worksheets(1).Range(“a1”).value = “Work” Worksheets(1).Range(“a2”).value = “Vacation” Worksheets(1).Range(“a3”).value = “Holidays” Worksheets(1).Range(“a4”).value = “Weekends” Worksheets(1).Range(“b1”).value = intTotalWorkDays Worksheets(1).Range(“b2”).value = intTotalVacDays Worksheets(1).Range(“b3”).value = intTotalHolidays Worksheets(1).Range(“b4”).value = intTotalWeekendDays
‘declare variables to use with the option buttons on the UserForm Dim DoChart As Boolean Dim DoLetter As Boolean DoChart = False DoLetter = False ‘Get the Chart or Letter options from the Retirement Countdown ‘UserForm If (frmRetire.btnChart = True) Or _ (frmRetire.btnBoth = True) Then DoChart = True End If If (frmRetire.btnLetter = True) Or _ (frmRetire.btnBoth = True) Then DoLetter = True End If ‘Create a pie chart showing the number of days If DoChart = True Then
759
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 760
760
CHAPTER 24 • Creating an Excel Application
‘format the Chart Title txtChartTitle = “Retirement Countdown for “ & txtName & _ “
Only “ & intTotalDays & “ Days To Go!”
‘create a chart and make it pretty With Charts.Add .ChartWizard Source:=Worksheets(“TempSheet”).Range(“A1:B4”), _ Gallery:=xlPie, PlotBy:=xlColumns, CategoryLabels:=1, _ Title:=txtChartTitle, ValueTitle:=(“Days Until Retirement”), _ HasLegend:=True .SeriesCollection(1).DataLabels.ShowValue = True .SeriesCollection(1).DataLabels.ShowPercentage = False .Name = “PieChart” .ChartTitle.Font.Size = 24 End With ‘clean up your messes and print preview the chart Unload frmRetire ActiveWorkbook.Sheets(“PieChart”).PrintPreview Charts(“PieChart”).Delete End If If DoLetter = True Then ‘Build the body of the letter’ txtDate = Date txtGreeting = “Dear “ & txtName & “,” txtPara1 = “You only have “ & intTotalDays & “ until retirement! And even better, “ & _ “only “ & intTotalWorkDays & “ will be spent at work. You will have “ & _ intTotalVacDays & “ earned vacation days, as well as “ & intTotalHolidays & _ “Holidays and Personal days. That’s 24 days a year! Finally, do not “ & _ “forget the “ & intTotalWeekendDays & “ Saturdays and Sundays you get to” & _ “sleep in!”
4002c24.qxd 7/18/01 1:29 AM Page 761
txtClosing = “Sincerely,” txtSignature = “The Excel Maven” ‘create a new document to hold the form letter Dim appWord As New Word.Application Dim docNew As Document Set appWord = CreateObject(“Word.Application”) appWord.Visible = True appWord.DisplayAlerts = wdAlertsNone ‘Put the parsed text into the new Word document Set docNew = appWord.Documents.Add With docNew Set myRange = docNew.Range(0, 0) With myRange .InsertParagraph .InsertBefore txtSignature .InsertParagraphBefore .InsertParagraphBefore .InsertBefore txtClosing .InsertParagraphBefore .InsertParagraphBefore .InsertBefore txtPara1 .InsertParagraphBefore .InsertParagraphBefore .InsertBefore txtGreeting End With ‘close the Retirement Countdown form Unload frmRetire appWord.Activate .PrintPreview End With ‘quit Word (uncomment when .PrintPreview becomes .PrintOut
761
PART
VII Automating Excel 2002 with Macros and VBA
Creating the Code
4002c24.qxd 7/18/01 1:29 AM Page 762
762
CHAPTER 24 • Creating an Excel Application
‘appWord.Quit (wdDoNotSaveChanges) End If ‘delete the worksheet and chart previously inserted Application.Worksheets(“TempSheet”).Delete End Sub
All the code is now in place and is tested. The only thing missing is a custom button on a custom toolbar that will run the Retirement Countdown application.
Using Custom Command Bars As you create more and better custom Excel applications, users will surely clamor for easier access to your creations. One way to simplify Excel for the end user is to create custom command bars with custom command buttons that run the most popular user forms and applications for each particular group of users. Creating a custom toolbar was covered in Chapter 21, “Automating Excel 2002 with Macros,” so this section will just cover loading, unloading, and docking a custom toolbar.
Loading Custom Command Bars To load a custom command bar, the CommandBar object must be enabled and its Visible property set to True. Newly created custom command bars have their Visible property set to False by default, so as a rule, you should set the Enabled and Visible properties for custom command bars. The Enabled property must be set before the Visible property. Setting the Enabled property to True causes the name of the command bar to appear in the list of available toolbars when the user selects View Toolbars. To load and display a command bar named barFavorites , use these two lines of code: CommandBars(“barFavorites”).Enabled = True CommandBars(“barFavorites”).Visible = True
Unloading Custom Command Bars To unload a custom command bar, simply reverse the values and order of the properties that were used to load the command bar. Setting the Visible property to False hides the toolbar, and setting the Enabled property to False removes it from the list of toolbars. Use the following to unload command bar barFavorites: CommandBars(“barFavorites”).Visible = False CommandBars(“barFavorites”).Enabled = False
4002c24.qxd 7/18/01 1:29 AM Page 763
Docking Custom Command Bars To dock a custom command bar, use the Position Property of the commandbar object. The possible variables are any of the MsoBarPosition constants: • msoBarBottom • msoBarFloating • msoBarLeft • msoBarMenuBar • msoBarPopup • msoBarRight • msoBarTop Reference the custom command bar either by name or by the value of the BuiltIn property of the CommandBar object. For all custom command bars, BuiltIn is False. To dock custom command bar barRetire at the bottom of the application window, use the following: CommandBars(“barRetire”).Position = msoBarBottom
To cause all custom command bars to float in the active window, use this code: For Each x In CommandBars If x.BuiltIn = False Then x.Position = msoBarFloating End If Next
Life after Retirement Countdown The Retirement Countdown application was created to let you acquire and exercise VBA programming skills. Although the practical value of Retirement Countdown is limited, parts of its code can be cannibalized and used in other Visual Basic projects. The most important lessons you can take away from this exercise is to make your code as robust as possible by validating all data and making your forms as “idiot-proof” as possible and to test your work thoroughly and methodically. A related tidbit of wisdom is to comment your code, unless you want to be stuck with the maintenance of all your applications until they (or you) are finally retired!
763
PART
VII Automating Excel 2002 with Macros and VBA
Life after Retirement Countdown
4002c24.qxd 7/18/01 1:29 AM Page 764
This page intentionally left blank
4002appA.qxd 7/18/01 2:18 AM Page 765
PA R T
VIII APPENDICES
4002appA.qxd 7/18/01 2:18 AM Page 766
This page intentionally left blank
4002appA.qxd 7/18/01 2:18 AM Page 767
APPENDIX
A
CUSTOMIZING EXCEL 2002
4002appA.qxd 7/18/01 2:18 AM Page 768
ne of the keys to working effectively in Excel is to become familiar with the many options for controlling the Excel environment. Knowing what options are available not only makes Excel work the way you expect it to but also helps in troubleshooting and problem solving. If Excel isn’t doing what you expect, chances are there is an option that can be changed to accommodate your needs. In this appendix, we’ll review the major options in Excel 2002 and point you to chapters where more detail is provided about some of the most commonly used options. We’ll also show you how to manually recover a worksheet or the data in a worksheet in the event that other document recovery features of Office XP fail.
o NOTE
Customizing Excel’s toolbars and menus is covered in Chapter 21, “Automating Excel 2002 with Macros.”
Customizing Excel Options in the Options Dialog Box Most of the options that control how Excel operates are found in the Options dialog box, accessible from the Tools menu. Excel has a significant number of options that control everything from what you see on the screen to how it checks for errors in your worksheets. It’s worth the time to explore the options even if you leave the default settings so you know what the options are when you need them. As with many dialog boxes, if you have a question about what an option means, click the Help button at the top of the dialog box and then click the option you’d like help with. Excel displays a screen tip with a description of the option.
NOTE
Calculation options are covered in depth in Chapter 5, “Calculating with Functions,” and Chart and Color options are covered in Chapter 10, “Advanced Charting in Excel 2002.” As a result, we have not included those tabs in this appendix.
View Options The View options, shown in Figure A.1, control what you see when Excel starts up and as you use specific tools, such as Comments. Views are divided into four categories: Show, Comments, Objects, and Window Options.
4002appA.qxd 7/18/01 2:18 AM Page 769
Customizing Excel Options in the Options Dialog Box
769
FIGURE A.1 View options control what appears on screen when Excel is the active application.
PART
Show When Excel starts up, it displays the Startup task pane, the Formula bar, the Status bar and each workbook appears as a separate item in the Windows taskbar. Clear any of these options if you would rather not see one or more of these features. Comments When you insert a comment, Excel displays the Comment indicator in the top right corner of the cell. If you would rather not see the indicator at all or would rather see the comment and the indicator, select None or Comment & Indicator. Objects Objects include charts, clip art, drawing objects, and pictures that you insert into your worksheets. Choose Show Placeholders if you want to see where the object is placed and at the same time save system resources by not displaying it. Choose Hide All if you don’t want to see the objects displayed at all. Window The Excel window contains the following by default: gridlines, row and column headers, outline symbols, zero values, a horizontal scroll bar, a vertical scroll bar, and sheet tabs. If you would like to also display page breaks and formulas, select the corresponding check boxes. Activating Formulas is helpful when you are constructing a worksheet and you are more concerned about the formulas than the formula results. The Formula Auditing toolbar turns on by default when you choose this option. To change the default color of the gridlines in your workbooks, select a color from the Gridlines Color drop-down list.
Appendices
VIII
4002appA.qxd 7/18/01 2:18 AM Page 770
770
APPENDIX A • Customizing Excel 2002
NOTE
The View options are what make Excel look like Excel, rather than like a browser. See Chapter 14, “Creating Workbooks for Other Users,” for Excel workbooks that don’t use the default view options.
Edit Options Excel has a number of tools that are designed to make editing easier. However, there are times when these tools get in the way and actually make editing a frustrating experience. Table A.1 describes each of the editing options. The Edit tab is shown in Figure A.2 FIGURE A.2 Edit options can make editing easier or harder depending on your perspective.
TABLE A.1
Edit Options
Option
Description
Edit Directly in Cell
Clear this check box if you don’t want to switch to edit mode when you double-click a cell.
Allow Cell Drag and Drop
If controlling the mouse is not your specialty, clear this check box so drag and drop does not move cells.
Alert Before Overwriting Cells
If you allow drag-and-drop cell moving, Excel alerts you when you are going to drop on cells that have contents. Clear this check box to eliminate the warning.
4002appA.qxd 7/18/01 2:18 AM Page 771
Customizing Excel Options in the Options Dialog Box
Edit Options (continued)
Option
Description
Move Selection After Enter/Direction
When you press Enter, Excel moves the cell pointer to the cell below where you are. You can stay in the same cell by clearing this check box, or change the direction that Excel moves by leaving it enabled and choosing a direction from the drop-down list.
Fixed Decimal/Places
If you enter columns of numbers with decimals, you can save yourself a lot of keystrokes by letting Excel insert the decimal for you. Select the Fixed Decimal check box, and then enter the number of places you want to see. A positive number moves the decimal to the left and a negative number moves the decimal to the right.
Cut, Copy, and Sort Objects with Cells
Objects, such as charts and pictures, live on a separate layer above the worksheet. However, when you select a group of cells that contain an object, it is cut, copied, or sorted along with the cells that surround it. Clear this check box if you like to maintain the position of objects where you place them.
Ask to Update Automatic Links
Clear this check box if you don’t want Excel to ask you before updating automatic links between linked cells.
Provide Feedback with Animation
When you insert or delete columns or rows, Excel animates the action with the option checked. Clear this check box if system resources are at a premium. You probably won’t even miss the animation, but on a slower machine, its presence would be annoying.
Enable AutoComplete For Cell Values
AutoComplete fills in cell values in a column if you have entered the first few letters in column previously.
Extend List Formats and Formulas
NEW: When creating a list, Excel copies the format to new cell entries if you have used the same format in three of the previous five cells. Formulas are also automatically extended to new rows. Clear this check box if you do not want list formats and formulas extended.
Enable Automatic Percent Entry
With this option enabled, Excel multiplies by 100 all numbers less than 1 when you apply the Percentage format. If you clear this check box, Excel multiples by 100 all numbers even those greater than or equal to 1.
Show Paste Options Buttons
The Paste Options button appears whenever you paste in Excel to give you formatting and linking options. If this new feature is annoying, clear this check box.
Show Insert Options Buttons
When you insert rows, columns, or cells and want to choose the formatting that is applied to the new cells, enable this check box to have an Insert Options button appear.
PART
VIII Appendices
TABLE A.1
771
4002appA.qxd 7/18/01 2:18 AM Page 772
772
APPENDIX A • Customizing Excel 2002
General Options The General options, shown in Figure A.3 control Excel’s basic settings and startup options. Table A.2 describes the General options. FIGURE A.3 The General options control Excel basic settings and the General tab provides access to Web Options.
TABLE A.2
General Options
Option
Description
R1C1 Reference Style
Changes column names from alpha to numeric so cell addresses use the R1C1 format rather than the standard A1 format.
Ignore Other Applications
Prevents Excel from responding to requests using DDE (Dynamic Data Exchange), such as in a Word Mail Merge.
Function ToolTips
Displays descriptions of toolbar buttons and combo boxes when you point to them.
Recently Used File List
Controls the number of recently saved files that appear on the File list at the bottom of the File menu.
Prompt for Workbook Properties
When you save a new workbook for the first time, Excel prompts you to enter workbook properties. If you leave this option off, you can access Properties from the File menu.
Zoom on Roll with IntelliMouse
If you have a Microsoft IntelliMouse, this option lets you zoom when you roll the Wheel button rather than scrolling.
4002appA.qxd 7/18/01 2:18 AM Page 773
Customizing Excel Options in the Options Dialog Box
TABLE A.2
773
General Options (continued)
Option
Description
Sheets in New Workbook
Changes the number of worksheets that are contained in a new workbook.
Standard Font/Size
Changes the default font and size used in Excel workbooks from Arial 10 point.
Default File Location
Use this option to change the default file save and open location from the My Documents folder on your C drive.
At StartUp, Open All, Files In
If you work with the same workbooks all the time, you can set this option to have Excel open them on startup. To use this option, move all the workbooks you want to open into the same folder. If you want to open only one, make sure it is the only workbook in the folder you specify.
User Name
Enter the name you would like to appear in the workbook properties and other places where the username is recorded.
PART
Setting Web Publishing Options If you plan to publish the workbook or worksheets as a web page, you can set options specifically related to web publishing. Click the Web Options button on the General tab to open the Web Options dialog box. Use the tabs of this dialog box to set specific options for creating web pages in Excel. General Options Use these options to save any additional hidden data to maintain formulas in Excel when you publish a worksheet as a web page and to indicate whether the pictures should be displayed when you open pages in Excel that were created in another application. Both of these options are on by default. Browser Options If you are creating web pages for use on your company’s intranet, you probably have a pretty good idea which browser most people have access to. If you select that browser as the target browser on the Browsers tab, you can make sure everyone will have access to the cool stuff you add to your website. The options listed at the bottom of the tab turn on and off depending on which target browser you choose. Supported features are selected and unsupported features are unselected. Use the options on the Browsers tab to set how you want to display graphics. Advanced browsers like IE 5 support Vector Markup Language (VML) and Portable Network Graphics (PNG). Displaying graphics in VML and allowing PNG as an output format result in smaller web graphics, which download and save much more
Appendices
VIII
4002appA.qxd 7/18/01 2:18 AM Page 774
774
APPENDIX A • Customizing Excel 2002
quickly. If you’ve ever waited while your low-speed modem slowly downloaded a dozen graphics, you know that VML and PNG are very good news. The bad news is that when you use VML, users with older browsers like IE 4 won’t see any graphics at all—and IE 4 isn’t all that old.
TIP Internet Explorer 5.0 or later supports saving new web pages as web archives. Use this option to save snapshots of web pages in single MIME-encoded files using the .mht or .mhtml file format.
File Options The settings on the Files tab determine how the application saves files when you publish your document. The Organize Supporting Files in a Folder check box is enabled by default; this option creates a separate folder for supporting files (such as graphics) when the document is saved. The folder’s name is the workbook’s name with _files appended. For example, the folder of supporting files for XYZ Proposal is named XYZ Proposal_files. This option helps keeps your files organized and looking more like a website. If you clear it, be sure you can keep track of all of the files associated with the pages you create. Disable the Use Long File Names Whenever Possible option if you’re saving your presentation on a network file server (rather than a web server) and Windows 3.1 or non-Windows users on your network need to open your files. The Update Links on Save option automatically checks to make sure the links to supporting files such as graphics, background textures, and bullets are updated when the web page is saved. Clear the Check if Office Is the Default Editor for Web Pages Created in Office option only if you want to use a non-Office application as your default web page editor. Otherwise, Office will ask you every time you try to save a web page in Office if you want to make an Office application the default editor for the page. In Excel, use the Office Controls options to set a location from which you want to download Office Web Components from your corporate intranet. When you designate a file location, Office Web Components are loaded and installed automatically when you open an Excel workbook that uses them. This download location must be set up by your system administrator. Picture Options On the Pictures tab, you can set the size of a target monitor and number of pixels to improve layout and resolution. 800 × 600 is still the most common resolution used today, but the proliferation of laptops and high-resolution
4002appA.qxd 7/18/01 2:18 AM Page 775
Customizing Excel Options in the Options Dialog Box
775
monitors make this difficult to predict. 800 × 600 is probably still a safe bet for most web development. Encoding Options On the Encoding tab you can choose the language code you want to save with the web page. If you are using another language from the Office Language Pack to create the web page, be sure to save the corresponding encoding with the web page. Font Options The Fonts tab sets the appropriate character set (i.e., Arabic, Cyrillic, English/Western European, etc.) to use with your web page. This is also where you set the default font and font size on the web page. If a user opens the web page and they have the default font on their system, that’s the font the page will use. If they don’t have the default font, Windows substitutes another font. It’s a good idea to choose a common font that you can be confident most users will have available to them if you want your pages to display correctly.
Use the Transition options if you work in a mixed environment with pervious versions of Excel or Lotus 1-2-3. With these options, you can designate the default Save format and activate other menu, key, and sheet options that are consistent with Lotus 1-2-3.
Custom Lists Options In the Custom Lists tab, shown in Figure A.4, you can create your own lists that Excel will recognize with AutoFill. Click the List Entries text box and enter the list, pressing Enter after each value. Click the Add button when you have finished entering the list. FIGURE A.4 Use the Custom Lists tab to create your own lists that you can use with AutoFill.
PART
VIII Appendices
Transition Options
4002appA.qxd 7/18/01 2:18 AM Page 776
776
APPENDIX A • Customizing Excel 2002
If you already have a list, open the worksheet that contains the list and click in the Import List from Cells text box. Then select the range of cells that contains the list. Click the Import button to add the list. To delete a list you’ve created, select it from Custom Lists and click Delete. To use a list, enter the first value in a cell and use the Fill Handle to drag the list to the adjacent cells.
International Options If you are creating worksheets in languages other than United States English, you can use the International settings, shown in Figure A.5, to change how Excel displays numbers and prints documents. You can also set Excel’s default direction that controls how you view and move around the worksheet. FIGURE A.5 Use the International options to accommodate the needs of countries other than the United States.
Save Options As part of Office XP’s enhanced document recovery features, AutoRecover is now turned on by default in Excel 2002. In the Save options, shown in Figure A.6, you can set the frequency of the AutoRecover save and the save location. Although Excel attempts to open the autorecovered workbook when it reopens after a crash, knowing the location where this file is saved could help in the event it cannot open it and you need to attempt a manual recovery.
4002appA.qxd 7/18/01 2:18 AM Page 777
Customizing Excel Options in the Options Dialog Box
777
FIGURE A.6 Use the Save options to set up automatic file recovery in the event of a crash.
PART
WARNING
AutoRecover does not replace user-initiated file saves. The AutoRecover files are automatically deleted when a workbook is closed successfully.
Error Checking Options Excel’s automatic error checking features help to ensure that your worksheets are accurate and free of errors. Error checking can be enabled to occur in the background and, as you can see in Figure A.7, is turned on by default, and can also be activated manually. When Excel finds an error while it’s conducting a background review, it displays an indicator in the top-left corner of the cell. You can change the color of this indicator in the Error Indicator Color drop-down list on this tab.
Appendices
VIII You can disable AutoRecover for an individual workbook without affecting the options for other workbooks by selecting the Disable AutoRecover check box. You may want to use this option with a workbook that is consistently backed up and is so large that AutoRecover slows it down.
4002appA.qxd 7/18/01 2:18 AM Page 778
778
APPENDIX A • Customizing Excel 2002
FIGURE A.7 Error checking rules determine what Excel identifies when it checks your worksheets for errors.
Chapters 5, “Calculating with Functions,” and 19, “Solving Business Problems Using the Analysis Tools,” cover the process of error checking and the Formula Auditing toolbar in detail. Table A.3 describes the rules that the Error Checking feature uses when it reviews a worksheet.
TABLE A.3
Error Checking Options
Option
Description
Evaluates to Error Value
Displays a warning if a formula in a cell results in an error.
Text Date with 2-Digit Years
Displays a warning if dates formatted as text include 2digit rather than 4-digit years.
Number Stored as Text
Displays a warning if numeric data is formatted as text. This can occur, especially with imported data if the source data is not formatted as numbers.
Inconsistent Formula in Region
Identifies formulas that are different from other similar formulas in the same region, for example, if one formula sums four rows and an adjacent formula only sums three rows.
Formula Omits Cells in Region
Identifies formulas that omit adjacent cells, for example, if a formulas sums four rows and there is a value in the cell directly above the four rows.
Unlocked Cells Containing Formulas
This error appears if you have unlocked cells that contain formulas in a protected worksheet.
Formulas Referring to Empty Cells
Displays an error if a formula pertains to empty cells. This rule is not turned on by default so you can create worksheets and enter formulas without first entering values.
4002appA.qxd 7/18/01 2:18 AM Page 779
Customizing Excel Options in the Options Dialog Box
779
NOTE
When you review an error in a worksheet and decide to ignore it, you can have Excel identify the error again by clicking the Reset Ignored Errors buttons on the Error Checking tab.
Spelling Options Excel’s Spelling options, shown in Figure A.8, include an option to change the language the dictionary uses and to identify language-specific options for German, Korean, Hebrew, and Arabic. In order to use these options, you must have the appropriate languages installed from the Office XP CDs. Spelling checks the entire active worksheet, including cell values, comments, charts, text boxes, buttons, and headers and footers. However, Excel does not check protected worksheets, formulas, or text that results from a formula.
PART
VIII Appendices
FIGURE A.8 Spelling options include options for language other than English, spelling rules, and access to AutoCorrect options.
If you have created additional spelling dictionaries—Word documents with a .dic extension—you can choose which dictionary you want to add words to when Spelling identifies words not in its dictionary. You can then designate how you want Spelling to work by enabling or disabling these options: • Suggest Words from Main Dictionary Only limits Spelling to words found in the default Office XP Spelling dictionary.
4002appA.qxd 7/18/01 2:18 AM Page 780
780
APPENDIX A • Customizing Excel 2002
• Ignore Words in UPPERCASE tells Spelling not to identify words or abbreviations entered all in uppercase as potential spelling errors. • Ignore Words with Numbers has Spelling skip words that contain numbers. This option is enabled by default in Excel. • Ignore Internet and File Addresses instructs Spelling to disregard words it recognizes as Internet or file addresses.
Setting AutoCorrect Options Excel 2002 applies many of the same AutoCorrect options that you’ve found in the past several versions of Microsoft Word. Click the AutoCorrect Options button to open the AutoCorrect dialog box, shown in Figure A.9.
NOTE
You can also access AutoCorrect Options directly from the Tools menu.
FIGURE A.9 Excel’s AutoCorrect feature fixes common spelling and typing errors automatically.
Table A.4 describes the AutoCorrect options available in Excel. With AutoCorrect, you’ll always know that you’re not in Word. For example, the AutoCorrect Options button doesn’t appear for all features, and Excel does not capitalize the first letter of sentences. But when it kicks in, it works like stated in Table A.4.
4002appA.qxd 7/18/01 2:18 AM Page 781
Customizing Excel Options in the Options Dialog Box
AutoCorrect Options
Tab
Option
Description
AutoCorrect
Show AutoCorrect Options buttons
Displays an option button when Excel makes an AutoCorrection.
AutoCorrect
Correct TWo INitital Capitals
Automatically fixes errors caused by holding the Shift key too long.
AutoCorrect
Capitalize First Letter of Sentences
Automatically capitalizes the first letter of sentences you enter in a cell or text box.
AutoCorrect
Capitalize Names of Days
Changes the first letter of days of the week to uppercase.
AutoCorrect
Correct Accidental Use of cAPS LOCK Key
Reverses capitalization when text is typed with Caps Lock on and automatically turns Caps Lock off.
AutoCorrect
Replace Text as You Type
Replaces words and letters you type in the Replace column with words and symbols in the With column. Add words to the AutoCorrect dictionary by entering them in the Replace text box and entering their replacements in the With text box and then clicking the Add button. Remove words from the AutoCorrect dictionary by selecting them and clicking the Delete button.
AutoFormat as You Type
Internet and Network Paths with Hyperlinks
Converts Internet and file addresses in worksheets to active hyperlinks.
Smart Tags
Label Data with Smart Tags
Adds a Smart Tag indicator to the lower right corner of a cell when it recognizes one of the smart tags listed in the Recognizers list.
Smart Tags
Recognizers
Automatically recognizes and tags Recent Outlook E-mail Recipients and Smart Tag Lists (MSN MoneyCentral Financial Symbols).
Smart Tags
Show Smart Tags As
Choose among None, Button Only, and Indicator and Button to indicate when a smart tag has been recognized.
Smart Tags
Embed Smart Tags in This Workbook
Saves the smart tags with the workbook when the workbook is saved. This option is turned off by default. Enabling it means that smart tags do not have to be recognized each time the workbook is opened.
PART
VIII Appendices
TABLE A.4
781
4002appA.qxd 7/18/01 2:18 AM Page 782
782
APPENDIX A • Customizing Excel 2002
If you would like to force Excel to review the active worksheet to identify smart tags, click the Check Workbook button on the Smart Tags tab of the AutoCorrect dialog box, shown in Figure A.10. After Excel checks for smart tags, it reminds you that smart tags it recognized will not be saved with the workbook unless you enable the Embed Smart Tags in This Workbook option, and then it offers to enable it for you. Click Yes if you would like to save the smart tags. If you click No, you can click the Check Workbook button at a later time to have Excel recognize smart tags again. FIGURE A.10 In the Smart Tags tab, you can set options and find additional smart tag lists.
Microsoft is expecting a number of smart tag lists to be developed by third-party vendors. If you are interested in using additional lists, you can check out what’s available by clicking the More Smart Tags button. This takes you to the Smart Tags page of the Microsoft Office Assistance Center on the Web where you can download additional smart tag lists.
Security Options Security options, shown in Figure A.11, are designed to protect your workbooks from unwanted intruders. Excel offers a number of ways for you to do this depending on the level of security you need. Password to Open Requires a user enter a password before they can open the workbook. When you enter a password in the Password to Open text box, you are
4002appA.qxd 7/18/01 2:18 AM Page 783
Customizing Excel Options in the Options Dialog Box
783
prompted to confirm the password by reentering it. Click the Advanced button to assign a specific encryption type to the workbook. Password to Modify Requires a password if the user wants to makes changes to the workbook. When a user opens the workbook, a dialog box appears asking for the password to modify. If they don’t know the password or don’t want to change the original, they can still open it as read only.
Read-Only Recommended as read only.
Prompts users to open a password-protected workbook PART
Remove Personal Information from This File on Save from the properties associated with the file. FIGURE A.11 Use the Security options to control access to your workbooks and ensure that the macros are virus free.
Removes user information
Appendices
VIII
4002appA.qxd 7/18/01 2:18 AM Page 784
784
APPENDIX A • Customizing Excel 2002
Assigning a Digital Signature If you’d like to attach a digital signature to the workbook, click the Digital Signatures button to open the Digital Signatures dialog box, shown in Figure A.12. You must first have a digital signature that you have obtained from a commercial certification authority or from your company’s security administrator. Click the Help button in the Digital Signatures dialog box for more information about obtaining a digital signature. FIGURE A.12 Add a digital signature to a workbook in the Digital Signatures dialog box.
WARNING
You want to attach a digital signature to a workbook only after you have made all the changes in the workbook you intend to make and have saved the final version of the workbook. Saving a workbook removes all digital signatures attached to it.
Macro Security In the age of the macro virus, it’s become essential to assign a security level to workbooks that run macros. Click the Macro Security button to open the Security dialog box shown in Figure A.13.
NOTE
For more about macros and macro security, see Chapter 21, “Automating Excel 2002 with Macros.”
4002appA.qxd 7/18/01 2:18 AM Page 785
Customizing Excel Options in the Options Dialog Box
785
FIGURE A.13 You can assign a level of security to the workbook to protect it against macro viruses.
PART
TIP One of the best protections against macro viruses is up-to-date virus protection software. Notice that the dialog box in Figure A.13 indicates that no virus scanner is installed on this system. That makes this system especially vulnerable. Don’t let this happen to you. Make sure you have good virus protection on your system. Click OK to close the Security dialog box. This brings our tour of Microsoft Excel options to an end so if you have finished setting options, click OK to save the changes you made in the Options dialog box.
Appendices
VIII Choose from High, Medium, or Low security. High security prevents unsigned macros from running. Medium security gives you a choice when you open the workbook to run the macros in the workbook. Low security, clearly not recommended, lets any macro run. You can see a list of trusted sources by clicking the Trusted Sources tab. Excel assumes that installed add-ins and templates are safe so the Trust All Installed Add-ins and Templates option is selected by default. If you have any concern about add-ins and templates that you might install, consider clearing this check box. If you would like Microsoft Office to warn you when a macro accesses a Visual Basic Project, enable the Trust Access to Visual Basic Project check box.
4002appA.qxd 7/18/01 2:18 AM Page 786
786
APPENDIX A • Customizing Excel 2002
Recovering Files Manually in Excel 2002 In Chapter 1, “Working in Excel 2002,” we discussed the new and enhanced document- and application-recovery features of Microsoft Office XP. Because of the critical nature of data in an Excel workbook, Microsoft has gone a step further and offered a method to manually recover data from a corrupt workbook. Before attempting to manually recover data from a corrupt file, you want to first exhaust other methods. When Excel crashes unexpectedly, Excel attempts to reopen and repair the open workbooks. If Excel is not able to repair the file, it tries a second time but this time does not attempt to repair the file. Instead, Excel extracts cell values and formulas so at least the data is salvaged—all formatting will be lost, however. If, for some reason, Excel doesn’t go into recovery mode automatically, you can attempt recovery manually by following these steps: 1. Open the File menu and choose Open. 2. Select the file you want to open and click the drop-down arrow on the Open button. 3. Select Open and Repair from the drop-down list. 4. If this is the first time you have attempted to repair the file, choose Repair from the dialog box that opens.
5. If you have tried repairing and the file is still corrupt, choose Extract Data. 6. When you choose Extract Data, you’re given two more options. Choose Convert to Values if you are more concerned about having the data in the workbook. If you’d like to try to recover as much of the formulas as possible, choose Recover Formulas. In either case, Excel attempts to recover formulas but if it cannot, it, depending on your choice, either converts the formulas to values or displays as much of the formula as it can recover.
4002appA.qxd 7/18/01 2:18 AM Page 787
Recovering Files Manually in Excel 2002
787
7. Excel opens the workbook and displays the Repairs dialog box shown in Figure A.14. Click Close to view the workbook or click the link if you would like to see the log file listing repairs.
FIGURE A.14 Excel reports on the repairs it made to the corrupted workbook.
PART
Additional Methods for Recovering Data from Damaged Workbooks Excel includes other methods in addition to those described above to attempt to recover corrupted data from a workbook. It may take several attempts before you find the solution that works for your data but keep trying. Of course, the best defense against lost data is a good-quality and current backup. If you or your system administrator are not backing up critical files on a daily basis, we recommend that you immediately check into options for data backup. With a good backup system, the worstcase scenario results only in a day’s worth of data loss—a far better situation than losing it all. Before you give up on recovering your data, try these options: If the Workbook Is Open when It becomes Corrupted Choose File Open and select the file you have open. When Excel asks if you want to revert to the saved document, click OK. Obviously, you lose any changes you’ve made since the last save but you can resave an uncorrupted file. If You Can Open the Workbook File You can remove corruption that may be caused by a printer by saving the active worksheet as an SLYK (Symbolic Link) file and then resaving it as an Excel workbook. You must save each worksheet in the workbook separately when using this method. Follow these steps: 1. Open the workbook. 2. Choose File Save As.
Appendices
VIII
4002appA.qxd 7/18/01 2:18 AM Page 788
788
APPENDIX A • Customizing Excel 2002
3. Select SLYK (Symbolic Link) from the Save as Type drop-down list. 4. Click Save. 5. Click OK to the warning about saving individual sheets and Yes to the message that certain features may not be compatible with this file type. 6. Close the file. 7. Choose File Open. 8. Select All Files from the Files of Type drop-down list. 9. Select the SLK file you saved and click Open. 10. Resave the file, changing the Save as Type to Microsoft Excel Workbook. 11. Repeat steps 2 through 10 for each additional worksheet in the original workbook. If You Can Open the Corrupted File, You Also Might Try This You can try saving the workbook as a web page and then resaving it as a Microsoft Excel Workbook. You may lose some features, but data and formulas should be preserved. If You Can’t Open the File in Excel You might try opening the workbook with automatic calculation turned off. To do this, follow these steps: 1. Open a blank workbook. 2. Choose Tools Options and click the Calculation tab. 3. Select Manual in the Calculation section and click OK. 4. Try to open the corrupted workbook.
WARNING
If you cannot open a workbook file because of disk or network errors, you should move the file to a healthy disk or move it to your local drive before attempting to repair the file.
If You Can’t Open the Workbook, Try Linking to It Using External References Although this method won’t recover formulas or formatting, you might be able to recover the workbook’s data by creating an external reference to the data. Follow these steps to attempt this method: 1. Choose File Open and browse to the folder that contains the corrupted file. You don’t want to open the file, just the folder that contains it. 2. Click Cancel. 3. Open a new workbook by choosing File New Workbook.
4002appA.qxd 7/18/01 2:18 AM Page 789
Recovering Files Manually in Excel 2002
789
4. In cell A1, type =FileName!A1 replacing FileName with the name of the corrupted workbook. If the Select Sheet dialog box appears, select the appropriate sheet and click OK. 5. Select cell A1 and click the Copy button. 6. Select an area that is approximately the same size as the range of cells that contain data in the corrupted file, and click the Paste button. 7. If the data appears in the new workbook, you are safe. To remove the link to the data, with the range of cells still selected, click the Copy button. 8. Choose Edit Paste Special Values, and click OK. 9. Save the new workbook.
NOTE
The Excel 2002 version of the Microsoft Excel Viewer was not available at the time of publication.
With either of these methods, you will lose any chart, module, macro, dialog sheets, and any embedded charts. You will also lose formulas, but you will recover the formula results. Opening the workbook in WordPad is another choice worth trying, especially if you have Microsoft Visual Basic Code in modules and class modules. Search for Sub or Function to find the code.
PART
VIII Appendices
If You Can’t Open the File in Excel, Try Another Application Although opening a workbook in Word or the Microsoft Excel viewer limits what you can recover, if your prime motivation is to recover data, it’s worth a try. To open the workbook in Word, you need to have the Microsoft Excel converter installed—you can find it on the Office XP CD. You can download the Excel Viewer for various versions of Excel from office.microsoft.com/Downloads.
4002appA.qxd 7/18/01 2:18 AM Page 790
This page intentionally left blank
4002appB.qxd 7/18/01 2:51 AM Page 791
APPENDIX
VBA QUICK REFERENCE
B
4002appB.qxd 7/18/01 2:51 AM Page 792
his reference is for the last four chapters of Mastering Excel 2002, which demonstrate using Excel and Visual Basic to create and edit macros and user forms, display and hide toolbars and menus, and create an application based in Excel. The appendix is a quick reference guide to introduce the basics of VBA, the programming language for Excel 2002. The following topics are included in the appendix:
t
• Using comments, blank lines, and indentations to structure your code and make it human-readable • Understanding VBA syntax so you can tell the players apart: objects, collections, methods, properties, keywords, and so on • Using VBA operators: arithmetic and logic operators that you can use in Visual Basic • Understanding VB structures: the building blocks for applications, including conditional structures similar to the Excel IF function This is just a start. If you want to learn more about Visual Basic, see the list of recommended materials at the end of Chapter 22.
Using Comments, Blank Lines, and Indentation The lines that start with single quote marks (′) are comment lines (also known as remark lines) explaining the purpose of the code. The single quote tells VBA to ignore everything on this line after the single quote. You can use rem (short for remark) to indicate a comment line. You can add comments to the end of a line of code, as in the example below, but this typically makes the comments harder to read unless the lines of code are as short as the one in this example: Dim strColor ‘declare a variable to contain the product color
Documenting your code with comments is good programming practice. It has three main purposes: • It clarifies your thinking when you’re creating your code. • It helps others understand your code. • It helps you understand your code when you revisit it six months later. Most programmers hate documentation and, left to their own devices, would never add explanatory comments. However, most people who hire or manage programmers insist on documentation in case the programmer is moved to another
4002appB.qxd 7/18/01 2:51 AM Page 793
department, hit by a bus, or starts looking for an employer that doesn’t press charges. The most effective way to comment your code is to start creating code by creating an outline of comments describing what each part of the code should do. Then, as you create the code, describe particular actions in more detail; even add comments to yourself about workarounds you might have to take or alternatives worth trying. When you’ve finished the code, go back through and clean up the comments to make them clear and concise. Comments are easily recognizable in the VBA IDE because they are green. In our examples we used blank lines to separate the code into logical chunks. This is a visual convenience to make the code more human-readable; the Visual Basic interpreter simply ignores the blank lines. Likewise, programmers use indentation to indicate a hierarchy in a program. The Sub and End Sub statements mark the beginning and end of a subroutine, and appear at the left margin. Everything else is indented one or more tabs. Statements within a decision making or looping construct (If... Then, Do While, Do Until) are indented further to indicate that they are contained within that condition or loop. The indentation helps your eye move quickly from structure to the next. You don’t need to indent any of your code—but indentation makes it far easier to read. Typical practice is to indent one tab, or four or five spaces, for each level of indentation. The VBA IDE features intelligent indentation, so you can more easily type visually structured code. Longer VBA statements can be broken over two lines of code using the line-continuation character—an underscore preceded by a space. This also is for visual convenience only, so that you don’t have to scroll horizontally back and forth in the IDE window. VBA reads a line of code broken with the line continuation character as one logical line.
Understanding VBA Syntax To work with VBA, you need to know a little about the syntax. Just as most human languages have widely recognized parts (such as nouns, verbs, adjectives, and so on), scripting and programming languages break down into a number of parts that you put together in statements, arrangements defined by the syntax of the language. You put together statements by using combinations of keywords, objects, properties, methods, constants, and variables, together with required arguments and optional arguments specifying information. In the next sections, we’ll look at what these terms mean and how you work with them.
793
PART
VIII Appendices
Understanding VBA Syntax
4002appB.qxd 7/18/01 2:51 AM Page 794
794
APPENDIX B • VBA Quick Reference
Keywords A keyword is a word defined as having a meaning in Visual Basic. Keywords include object names, properties, methods, and argument names. It’s possible to create variables, constants, and procedures that have the same names as Visual Basic keywords. This is called shadowing a keyword and isn’t usually a good idea, as it becomes easy to get confused. For example, there’s an object called ChartTitle that represents an Excel chart title, so it’s a bad idea to create a variable, constant, or procedure named ChartTitle. As we’ll see in a little while, you can name your variables, constants, and procedures pretty much anything that strikes your fancy, so there’s no real reason to shadow a keyword—but it’s surprisingly easy to do unintentionally.
Objects An object is one of the elements that make up an application. You can look at Excel as being made up of a collection of objects that allow you to access different parts of the application. Objects can contain other objects, which makes for both power and confusion. Excel, as well as Word and PowerPoint, are constructed rather like Chinese boxes, with one object inside another inside another. (For example, in Excel, within the Application object you find the Workbooks object; within the Workbooks object you find the Worksheets object; within the Worksheets object you find the PageSetup object; and finally you reach properties that you can use to set the margins and page layout.) Objects are organized into a theoretical hierarchy known as an object model. See a detailed examination of the Excel object model later in this appendix.
Collections Groups of objects are organized into collections, which provide an easy way to access them. For example, the Worksheets collection contains a collection of Worksheet objects, each of which represents a worksheet in your current Excel session. Usually, the name of a collection is the plural of the object, as in the previous example, but there are some exceptions. For example, Microsoft Outlook uses a Folders collection that contains all the MAPIFolder objects.
TIP
Collections themselves are objects, too. To avoid confusion, from now on, we’ll refer to any collection as a “collection” rather than a “collection object.”
4002appB.qxd 7/18/01 2:51 AM Page 795
Understanding VBA Syntax
795
Properties Each object has a number of properties—named characteristics that define the object. For example, the Borders collection that contains the four Border objects and represents the borders of a range or style has several properties. These range from a Color property to the LineStyle property to a Weight property. A property appears after the name of the item it refers to, separated by a period. For example, to refer to the Color property of a Border object, you would use Border.Color.
Methods
Application.Calculate
Or just type Calculate
Most methods take one or more arguments, parameters that supply pieces of information necessary to the method. As with Excel’s functions, some arguments are required, while others are optional. For example, the SaveCopyAs method takes a required Filename argument that specifies the file in which to save the workbook. Other methods take no arguments. For example, when deleting an object, the Delete method takes no arguments because none are needed—Excel is deleting the specified item, and that’s all the information it needs.
Constants A constant is a named item in memory that keeps a constant piece of information while a program is executing. You can specify the appropriate constant in your code instead of the corresponding value, which provides an easy way of handling complex information or information that may change from computer to computer. Excel uses constants to signify frequently used information, such as the day of the week (for example, the constant vbThursday in the vbDayOfWeek group of constants represents Thursday). Each constant has a numeric value associated with it; for example, the constant vbFriday has the numeric value 6 associated with it.
PART
VIII Appendices
A method is a built-in action that you can perform on an object; more technically, a method is a procedure (a set of instructions) for an object. For example, the Worksheet object that we met a moment ago has a Calculate method that calculates all open workbooks, a specific worksheet in a workbook, or a specified range of cells on a worksheet, depending on how you structure the command. Like a property, a method appears after the name of the item it refers to, separated by a period. For example, to Calculate all open workbooks, type
4002appB.qxd 7/18/01 2:51 AM Page 796
796
APPENDIX B • VBA Quick Reference
An easy way to find the name or value of a constant is to use the Object Browser in the VBA IDE. The top of the Object Browser pane is used for searching. Type in the first few letters of the item you need and click the Search Button. Excel will return the Library, Class, and Member of all matching items. Click on the row of your matching item, and the information will appear on the bottom of the pane. In Figure B.1 a search was performed on “xlRow”. Of the eight items returned, xlRowItem was selected. The bottom pane shows that the constant value is 4 and that it is a member of Excel.XlLocationTable. Clicking on any of the hyperlinks in the bottom pane will bring up that Library or Class in the Object Browser main window pane.
FIGURE B.1
Variables A variable is a location in memory that you set aside for storing a piece of information while a procedure is running. You can create as many variables as you need, and you can give them any name that meets Visual Basic’s naming rules (see the “Visual Basic Naming Rules” sidebar). As we mentioned before, it’s a bad idea to shadow a keyword by giving a variable the same name.
4002appB.qxd 7/18/01 2:51 AM Page 797
Understanding VBA Syntax
797
Visual Basic Naming Rules Briefly, the rules for creating names for variables in Visual Basic, VBA, and VBScript are simple. A name • Can be up to 40 characters long. • Must begin with a letter (after that, it can include letters, numbers, and underscores in any combination). • Cannot include spaces or symbols (such as % or *). • Must be unique within its context so that it is not confused with another variable. (You’ll find out more about context in the next section, “Scope.”) PART
You can specify the scope of a variable—the area of the project in which the variable is available. Variables can have one of three levels of scope: Procedure-Level Scope Limits a variable to the procedure that creates it; this is also referred to as local scope. Module-Level Scope Makes a variable available to all procedures within the module. In VBScript, this is referred to as script-level scope. Public Scope
Makes a variable available to all procedures in the project.
A variable’s scope defines the context in which it must be unique. For example, say you’re working with a module that already contains a procedure myFirstProcedure, which contains the variable strColor. Then you add a second procedure to the module and call it mySecondProcedure. If you use local scope for your variables, each procedure can have a variable with the same name (for example, strColor). But if you use the broader module-level scope for a variable, you can have only one variable with a particular name; because the variable is available to any procedure in the module, it will conflict with any other variable that has the same name. And if you use public scope for a variable in a project, no other active variable can have the same name. We’ll look at how to specify the scope of a variable in “Creating a Variable,” a little later in this appendix.
Appendices
VIII
Scope
4002appB.qxd 7/18/01 2:51 AM Page 798
798
APPENDIX B • VBA Quick Reference
Data Subtypes Visual Basic and VBA offer different types of variables. For example, you would store a string of text, such as a word or phrase, in a string variable, while you would store an integer (whole number) value in an integer variable. Table B.1 lists the data types VBA supports.
TABLE B.1
V B A D a t a Ty p e s
Data Type
Description
Integer
An integer value. Integer variables can contain integer numbers between –32,768 and 32,767. Integers outside this range need to use the Long subtype.
Long
A long integer value (from –2,147,483,648 to 2,147,483,647).
Single
A single-precision floating-point (i.e., noninteger) number. Single-subtype variants can contain negative values from –3.402823E38 to –1.401298E–45 and positive values from 1.401298E–45 to 3.402823E38.
Double
A double-precision floating-point (noninteger) number. Double-subtype variants can contain values from –1.79769313486232E308 to –4.94065645841247E–324 for negative values and positive values from 4.94065645841247E–324 to 1.79769313486232E308 for positive values.
Currency
An 8-byte integer with 4 digits of decimal places, designed for working accurately with large and complex numbers. Currency values can range from –922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Decimal
A 14-byte number with different ranges based on whether or not the number has a decimal point. Decimal values with no decimal point range +/- 79,228,162,514,264,337,593,543,950,335 and +/- 7.922816251426433759354950335 with 28 places to the right of the decimal.
Date
A date value. VBA can handle dates from 1/1/100 to 12/31/9999.
String
A text string. A variable-length string has a range of 0 to approximately 2 billion, while a fixed length string has a range of 1 to approximately 65,400.
Object
An object (such as an application or an ActiveX control).
Boolean
A two-position variable: True (–1) or False (0).
Byte
An integer value between 0 and 255.
Variant
The data type for all variables that are not explicitly declared as some other type. It can contain any kind of data except fixed-length string data. Variants can also contain the special values Empty, Error, Nothing, and Null.
Array
An array of any data type contains multiple instances of any of the data types listed here.
4002appB.qxd 7/18/01 2:51 AM Page 799
Understanding VBA Syntax
799
Converting a Variable to a Different Type
VBA has several data conversion functions that can be used to convert an expression to a specific data type. Table B.2 lists conversion functions you can use to modify your data on the fly during runtime (when the application or code is running). Many of these functions are also used in Excel 2002 formulas. V B A C o n v e r s i o n Fu n c t i o n s
Function
Returns
Abs
Absolute value of the number or expression
Asc
ASCII value of the first character in the specified string
Chr
Character representing the ASCII value entered
Cbool
True if the expression is nonzero, otherwise False
Cbyte
Byte representation of the expression or number
Cdate
Date representation of the expression or number
DateSerial
Date variable of the date specified by year, month, and day
DateValue
Date variable from a text expression or a string
TimeSerial
Date variable of the time specified in hours, minutes, and seconds
TimeValue
Date variable from a text expression or a string
CInt
Integer representation of the expression or number
CLng
Long representation of the expression or number
CSng
Single-precision representation of the expression or number
CDbl
Double-precision representation of the expression or number
CStr
String representation of the number; also returns a string from a Boolean, Date, or error value
Fix
For positive values returns the next lower whole number; for negative values returns the next lower whole negative number
Int
For positive values returns the next lower whole number; for negative values returns the next higher whole negative number
Sgn
1 for positive value, –1 for negative value (the sign of the expression or number)
Hex
String containing hexadecimal representation of the expression or number
Oct
String containing octal representation of the expression or number
PART
VIII Appendices
TABLE B.2
4002appB.qxd 7/18/01 2:51 AM Page 800
800
APPENDIX B • VBA Quick Reference
Here are some examples using these conversion functions: • Asc(strCity) returns the ASCII value of the first character in the string strCity. • CBool(1000-900) returns True. • DateSerial(1998, 10, 31) - DateSerial(1998, 9, 19) returns 42, the number of days between the two dates. • Hex(16) returns 10, the hexadecimal representation of the decimal 16.
Choosing Consistent Names for Variables It is very important to use clear names for your variables in VBA—if you don’t, it’s all too easy to become confused about which variable is which and what type of information each variable should contain. Mistaking a variable containing the string data subtype for a variable containing a numeric subtype can cause problems in your code.
NOTE
The Visual Basic Integrated Development Environment (IDE) used for Visual Basic 6 and the Visual Basic Editor for the Office applications that support VBA provide a number of tools for monitoring the data type and contents of variables: the Locals window for monitoring the value of all local variables in a procedure, the Watch window and Quick Watch dialog box for monitoring Watch expressions, the Immediate window for Debug.Print statements, and the Data Tips feature for quickly checking the value of a variable or an expression by holding the mouse pointer over it for a moment.
To make clear the data subtype you intend each variable to contain, use a naming convention for each variable you create. Table B.3 describes the naming convention of three-letter prefixes for VBA variables.
TABLE B.3
S u g g e s t e d N a m i n g C o n v e n t i o n s f o r V B A Va r i a b l e s
Data Type
Prefix
Example Name
Array
arr
arrScores
Boolean
bln
blnOnlineOrder
Byte
byt
bytReps
Currency
cur
curIncome
Date
dte
dteTomorrow
Double
dbl
dblTan
Integer
int
intDaysLeft
4002appB.qxd 7/18/01 2:51 AM Page 801
Understanding VBA Syntax
S u g g e s t e d N a m i n g C o n v e n t i o n s f o r V B A Va r i a b l e s ( c o n t i n u e d )
Data Type
Prefix
Example Name
Long
lng
lngCompanies
Object
obj
objExcel
Single
sng
sngProjIntRate
String
str
strLocation
Variant
var
varMyVariant
User-Defined
udf
udfMyField
As in the above examples, try to make your variable names comprehensible at a glance without making them absurdly long. If you can condense a description of the variable’s function into six to a dozen or so letters (plus the three-letter prefix indicating the subtype), you’ll create variables that are easy to understand without being a chore to type. VBA is not sensitive to capitalization, but uppercasing the first letter of each word in variable names almost always makes them easier to read and is worth the additional effort. If you declare variables at the beginning of a VB procedure, the editor will fill in the remainder of variable names after you’ve entered unique characters. It’s advantageous, therefore, to make the first letters following the prefix unique: intTicketsNum and intOrdersNum rather than intNumTickets and intNumOrders.
Creating a Variable You can create a variable in two ways: by declaring it explicitly (creating it formally, so to speak) or by creating it implicitly (creating it by implication, as it were).
Declaring a Variable Explicitly To declare a variable explicitly, you use a Dim statement, a Private statement, or a Public statement, as follows: • To declare a variable with procedure-level scope, use a Dim statement within the appropriate procedure. The following statements contain a procedure named GetUserName. The first statement starts the subprocedure, and the last statement ends it. The second statement declares a variable called strFirstName (whose name indicates that it is intended as a string variable). The third statement displays an input box and assigns its result to the strFirstName variable. Sub GetUserName() Dim strFirstName strFirstName = InputBox(“Enter your first name.”) End Sub
PART
VIII Appendices
TABLE B.3
801
4002appB.qxd 7/18/01 2:51 AM Page 802
802
APPENDIX B • VBA Quick Reference
• To create a variable with script-level scope, use a Private statement outside any procedure in the script page. You can also use the Dim statement outside of any procedure in Excel, but other applications that use VBA may interpret a Dim statement as meaning global scope. The first of the following statements creates a script-level Boolean variable named blnClockOn. The first group of three statements contains a procedure named SetClockTrue that sets the blnClockOn variable to True. The second group of three statements contains a procedure named ToggleClock that uses Not to toggle the value of the blnClockOn variable to its opposite state: Private blnClockOn Sub SetClockTrue() blnClockOn = True End Sub Sub ToggleClock() blnClockOn = Not blnClockOn End Sub
• To create a variable with public scope, use a Public statement outside any procedure in the script page. The following statement creates an object variable named objMyWord with public scope: Public objMyWord
Creating a Variable Implicitly
Instead of declaring a variable explicitly, you can create it implicitly as needed in a module. The following statement implicitly creates the variable intMyValue by assigning the value 123 to it. (This example assumes the variable has not been explicitly declared elsewhere in the script or on the script page.) intMyValue = 123
When you create a variable implicitly, it has procedure-level scope. To create a variable with module-level scope (public scope), you need to declare the variable explicitly.
Should You Declare Variables Explicitly or Create Them Implicitly?
You’re probably wondering whether you should create procedure-level variables implicitly or declare them explicitly. While both methods are valid, declaring variables explicitly helps make your code easier to understand, easier to debug, and more professional looking. To force yourself to explicitly declare all the variables in your code, you can place an Option Explicit statement in the first line of any module. When a module begins with the Option Explicit statement, VBA will stop with a Variable Is Undefined error at any variable that is not explicitly declared in your code.
4002appB.qxd 7/18/01 2:51 AM Page 803
Understanding VBA Syntax
803
NOTE
If you don’t require explicit declaration, every typo becomes a new variable, and the VB editor won’t AutoComplete variable names.
You can place variable declarations anywhere in your code—they don’t have to occur before the variable is used in the code—but generally accepted practice for local variables is to place them at the beginning of the procedure in which they occur. For example, if the subprocedure myProcedure uses the string variables strVar1 and strVar2, you might declare them as follows: Sub myProcedure() Dim strVar1 as string Dim strVar2 as string ‘the rest of the subprocedure takes place here
For variables with module-level, private, or public scope, accepted practice is to place the declarations at the beginning of the script page that contains them, after the Option Explicit statement (if you use one).
WARNING
In VBA you are not allowed to declare a group of variables to be a particular data type by separating them with commas. For instance, if we wrote the Dim statement above as Dim strVar1, strVar2 as string only strVar2 would be defined as a string. The variable strVar1 would be declared as the default data type, Variant, by VBA.
Assigning a Value to a Variable To assign a value to a variable, use an equal sign after the variable name followed by the value. The following statement assigns the string “This is an example.” to the variable strMyString: strMyString = “This is an example.”
The following statement assigns the value 2025 to the variable intCount: intCount = 2025
To assign an object to a variable, you need to use a Set statement (using the Set keyword) rather than a simple assignment (one using the equal sign). The following statements declare the variable objMyExcel and assign the Excel application object to it: Dim objMyExcel Set objMyExcel = CreateObject(“Excel.Application”)
PART
VIII Appendices
‘including use of the variables End Sub
4002appB.qxd 7/18/01 2:51 AM Page 804
804
APPENDIX B • VBA Quick Reference
Procedures A procedure is a set of instructions for performing a particular action. The types of procedures we’re interested in here are subprocedures, macros, and functions.
Subprocedures A subprocedure is a named unit of code that performs an action. You can create your own subprocedures in Excel to perform custom actions on objects. For example, you could create a subprocedure that runs automatically when the user closes a worksheet; the subprocedure might warn the user if they had not saved the item and ask if they wanted to do so, or the subprocedure might save the item without consulting the user —not always a great idea since the user may be exiting without saving for good reason! Typically, subprocedures do not use arguments, as functions do. Subprocedures start with a Sub statement and end with an End Sub statement. The lines of code below show a procedure named Greeting that displays a message box greeting the user: Sub Greeting() MsgBox “Hello, and welcome to the show!” End Sub
Macros
A macro is a type of subprocedure. People disagree sometimes about what differentiates macros from other subprocedures; there’s certainly room for debate. Macros are often understood to be subprocedures that you record (using an automatic device, such as the Macro Recorder in Word, Excel, and PowerPoint) rather than subprocedures you write, but the term macro is also applied sometimes to written subprocedures. Like other subprocedures, macros start with a Sub statement and end with an End Sub statement.
Functions A function is a unit of code that performs an action and typically returns a value. For example, just like Excel 2002, Visual Basic has a function named Left that returns the specified number of characters at the left end of the given text string, and a corresponding Right function that returns the specified number of characters at the right end of the given text string. Functions are easy to recognize in code because they start with a Function statement and end with an End Function statement. The lines of code below show the
4002appB.qxd 7/18/01 2:51 AM Page 805
Understanding VBA Syntax
805
skeleton for a function named myFunction, with a comment line (‘Actions here) indicating where the actions would take place: Function myFunction() ‘Actions here End Function
You can create your own functions in Excel (see Chapter 23, “Do-It-Yourself Functions,” for writing user-defined functions).
Events
Methods, Properties, and Events for the Dog Object Here’s an absurd analogy that you may find useful in straightening out objects, methods, properties, and events. Say you have a dog. Consider your dog as a Visual Basic object called Dog. Here’s how the Dog object works: • The dog has various properties, such as its type (Dog.Type = ″Doberman″), size (Dog.Size = ″Large”), and age (Dog.Age = ″7″). • The dog has various methods—actions you can specify it perform—such as barking (Dog.Bark) and walking (Dog.Walk). Some of these methods take one or more arguments. For example, to specify how many times and how loudly the dog should bark, you might use a HowManyTimes argument and a Loudness argument (Dog.Bark HowManyTimes:=4, Loudness:=11). • The dog responds to various events, such as your scratching it behind the ears (Dog_OnEarScratch) or calling its name (Dog_OnNameCall). • In a complex object model, the Dog object might contain multiple other objects (Dog.Stomach.Contents = “DogChow”), some of which in turn might contain further objects (which we won’t explore here). Pushing the analogy past the absurd, you could say the dog fits into the object model of your home in much the same way that Excel objects fit in the Excel object model.
PART
VIII Appendices
An event is an action that happens to an object—typically, an action that the user takes with the application. For example, the Workbook object supports events such as Calculate (updating the values on the worksheets) and Change (changing cells by typing in a cell or updating an external link). You can create procedures that respond to events. For example, you could create a procedure that demanded a password when the user tried to open a particular object.
4002appB.qxd 7/18/01 2:51 AM Page 806
806
APPENDIX B • VBA Quick Reference
VBA Operators VBA provides a full complement of operators—items used for comparing, combining, and otherwise working with values. The operators fall into four categories: • Arithmetic operators (such as + for addition and / for division) for mathematical operations. • Logical operators (such as Or for disjunction and XOr for exclusion) for building logical structures (ways of deciding programmatically which of two or more courses of action to take). Logical operators work with Boolean expressions. • Comparison operators (such as = for equality and >= for greater than or equal to) for comparing values. • Concatenation operators (such as & for joining two string variables together). Table B.4 lists the operators in their categories, with brief examples of each and comments on the operators that are not self-explanatory.
TABLE B.4 Operator
Operators in VBA Meaning
Example
Comments
x = y - 1
Straightforward subtraction.
Arithmetic Operators
-
Subtraction
x = -y
Sets x to the negative of y. The example returns x = -100.
+
Addition
x = y + 1
*
Multiplication
x = y * 2
/
Division
x = y / 2
\
Integer division
x = y \ 2
^
Exponentiation
x = y ^ 2
Mod
Modulo arithmetic
10 Mod 7
Integer division truncates any remainder. Modulo returns the non-integer part of the division. The example returns 3.
4002appB.qxd 7/18/01 2:51 AM Page 807
VBA Operators
TABLE B.4 Operator
807
Operators in VBA (continued) Meaning
Example
Comments
Logical Operators
Conjunction
If x > 1 And y > 1 Then
Both conditions must be True for a True result.
Not
Negation
x = Not x
Not reverses the value of x (True becomes False).
Or
Disjunction
If x > 1 Or y > 1 Then
If either condition is True, the result is True.
XOr
Exclusion
If x > 1 XOr y > 1 Then
If one condition is True and the other is False, the result is True; the result is False if both conditions are True or both are False.
Eqv
Equivalence
If x Eqv y Then
Similar to And, but results True if both values are False as well as when both values are True.
Imp
Implication
If x Imp y Then
True if both values are True or the right-hand value is True.
The two variables have the same value.
Comparison Operators
=
Equality
If x = y Then
Inequality
If strTest “Cool” Then
Greater than
If x > y Then
= y Then
Like
Object similarity
If x Like y Then
The initial string (x) matches the pattern (y)
Is
Object equivalence
If x Is y Then
The two variables refer to the same object.
Concatenation Operators
&
Concatenation
strTest = ”Hello.” & “ ” & “How are you?”
strTest becomes “Hello. How are you?”
+
Concatenation
strTest = “Hello.” + “ ” + “How are you?”
strTest becomes “Hello. How are you?” The + operator works fine for concatenating strings, but is potentially confusing because of variant data types—it can look like addition instead of concatenation.
PART
VIII Appendices
And
4002appB.qxd 7/18/01 2:51 AM Page 808
808
APPENDIX B • VBA Quick Reference
VBA Programming Structures In this section, we’ll discuss some of the VBA programming structures that you can use in your modules. These programming structures fall into three types: • Sequential structures, in which one command is executed after another • Looping structures, in which a group of commands is repeated for a set number of times or a variable number of times • Conditional branching structures, in which program flow is directed depending on conditions
Sequential Structures Sequential structures are the simplest form of programming structure—statements that perform operations. Most of the sample statements that have appeared so far in this chapter are sequential structures. Sequential structures include calls to subprocedures and functions. (A call is when one procedure runs another procedure.)
Looping Structures VBA provides several looping structures for repeating groups of statements. These looping structures include For... Next loops, For Each... Next loops, and various flavors of Do loops. We’ll look at these in turn.
For… Next Loops A For... Next loop repeats for a specified number of times controlled by a counter variable. The syntax for a For... Next loop is the following: For counter = start To end [Step stepsize] [statements] [Exit For] [statements] Next [counter]
Here’s how it works: • counter is a numeric variable. The loop runs from the start value specified until it exceeds the end value specified. • If the current value of counter is less than or equal to the end value, VBA executes the statements in the loop. If the current value of counter is more than
4002appB.qxd 7/18/01 2:51 AM Page 809
VBA Programming Structures
809
the end value, VBA branches to the next statement after the loop. This code adds 20 worksheets to the active workbook: Sub Add_20_Worksheets() Dim I as Integer For i = 1 To 20 ActiveWorkbook.Sheets.Add Next
• On reaching the Next keyword that ends the loop, VBA increments the counter by 1 or by the value of the optional argument stepsize, which is introduced by the Step keyword. The following statements contain a loop that counts upwards from 100 to 200 in steps of 25 (100, 125, 150, 175, 200): For intMyCounter = 100 To 200 Step 25 MsgBox intMyCounter
• If stepsize is a negative number, VBA decrements the number until it is less than the end value. For example, the For... Next loop in the following statements counts down from 100 to 0 in steps of 10: For q = 100 To 0 Step -10 Msgbox q Next
You can exit a For... Next loop before counter reaches the end value by using an Exit For statement. Typically, you would use an Exit For statement after a certain condition was met. If necessary, you can use multiple Exit For statements to evaluate multiple conditions while the loop is running.
For Each… Next Loops The For Each... Next loop is essentially a For... Next loop linked to a collection. The loop repeats once for each of the objects in the collection and then terminates. A For Each ... Next loop looks like this: For Each object In collection [statements] [Exit For] [statements] Next [object]
VBA evaluates the number of objects in the specified collection and (provided there is at least one object) executes the statements in the loop for the first object. On
PART
VIII Appendices
Next
4002appB.qxd 7/18/01 2:51 AM Page 810
810
APPENDIX B • VBA Quick Reference
reaching the Next keyword, it returns to the start of the loop, evaluates the number of objects in the collection again, and repeats the loop if necessary. For example, the following statements iterate through the worksheets in the active workbook. Any actions between the For Each and Next statements are applied to each sheet in turn: For Each mySheet in ActiveWorkbook.Sheets ‘take actions here Next mySheet
Do… Loops While a For... Next loop is controlled by a counter, and a For Each... Next loop by the objects in the specified collection, a Do loop is controlled by a condition and enables you to repeat statements while or until the condition is True. There are four types of Do loops: Do While... Loop loops, Do... Loop While loops, Do Until... Loop loops, and Do... Loop Until loops. In the following sections, we’ll look at each type in turn.
TIP
Technically, there’s a fifth type of Do loop: one without an Until condition or a While condition. There’s no condition to evaluate—just one endless Do. This Do loop runs forever (or until you forcibly terminate it) and has little—if any—practical use outside burning-in a computer or component. You’d be well advised to avoid this type of Do loop.
Do While… Loop Loops The Do While... Loop loop repeats the statements in the loop while the specified condition is met. This loop tests the condition before running the statements in the loop for the first time. It uses the following syntax: Do While condition [statements] [Exit Do] [statements] Loop
As long as the condition is met, VBA executes the statements in the loop. After each loop, the Loop keyword returns execution to the Do While line, and the condition is evaluated again. For example, the Ten_Worksheets procedure shown below adds worksheets to the active workbook until it contains 10 worksheets. The procedure starts by using a With statement that works with the ActiveWorkbook object,
4002appB.qxd 7/18/01 2:51 AM Page 811
VBA Programming Structures
811
then uses a Do While… Loop loop that adds a new worksheet after the current last worksheet as long as the count property of the Worksheets collection is less than 10. Sub Ten_Worksheets() With ActiveWorkbook Do While .Worksheets.Count < 10 .Worksheets.Add _ After:=Worksheets(.Worksheets.Count) Loop End With End Sub
Do... Loop While Loops
The Do... Loop While loop runs the statements in the loop once, and then evaluates the specified condition at the While keyword and repeats the loop as long as the condition is met. The Do... Loop While loop uses the following syntax:
PART
[statements] [Exit Do] [statements] Loop While condition
VBA executed the commands contained in the loop, then evaluates the condition in the Loop While statement. If the condition is True, VBA returns to the Do line and executes the loop again; if the condition is False, VBA continues at the statement after the Loop While statement. The Enter_Price procedure shown below declares a variable named curPrice, starts a Do loop, and displays an input box to prompt the user for the price in dollars and cents. It then checks to see if curPrice is an empty string (″ ″), which results if the user clicks the Cancel button (or the Close button) on the input box or clicks the OK button without entering anything into the text box. If curPrice is an empty string, the Exit Do statement causes VBA to exit the Do loop. If not, the Loop While statement uses the IsNumeric function to make sure that the contents of curPrice are numeric. If IsNumeric returns False, execution returns to the Do statement and the loop repeats. Sub Enter_Price() Dim curPrice Do CurPrice = InputBox _ (“Enter the price in dollars and cents:”, “Price”)
Appendices
VIII
Do
4002appB.qxd 7/18/01 2:51 AM Page 812
812
APPENDIX B • VBA Quick Reference
If curPrice = “” Then Exit Do Loop While IsNumeric(curPrice) = False ‘take other actions here End Sub
Notice that in this case we do not declare curPrice as the Currency data type, though that’s the type of information we’d like to get in the variable. Here’s why: If curPrice is Currency and the user enters noncurrency information (such as a string), VBA will try to store the wrong type of data in the variable and an error will occur. If we let VBA create a Variant variable (as it does by default when you do not specify the data type for a variable), it can store any type of data in it without a problem.
Do Until… Loop Loops
The Do Until... Loop repeats the statements in the loop until the specified condition is met. Like a Do While... Loop loop, the Do Until... Loop loop tests the condition before running the statements in the loop for the first time; unlike a Do While... Loop loop, the Do Until... Loop loop repeats until the condition becomes True (that is, while the condition is False) rather than while the condition is True (until it becomes False).
TIP
You can essentially use a Do Until... Loop instead of a Do While... Loop by inverting the appropriate condition—and vice-versa.
The Do Until... Loop loop uses the following syntax: Do Until condition [statements] [Exit Do] [statements] Loop
For example, consider the following Another_Ten_Worksheets procedure, a mutation of the Ten_Worksheets procedure that we looked at for the Do While…Loop loop: Sub Another_Ten_Worksheets() With ActiveWOrkbook Do Until .Worksheets.Count >= 10 .Worksheets.Add _ After:=Worksheets(.Worksheets.Count) Loop End With End Sub
4002appB.qxd 7/18/01 2:51 AM Page 813
VBA Programming Structures
813
This loop runs until the Count property of the worksheets collection for the ActiveWorkbook object is greater than or equal to 10. (We need to check for Count being greater than 10 because the workbook may already contain more than 10 worksheets, in which case, checking for Count equaling 10 will not return True.)
Do… Loop Until Loops
The Do... Loop Until loop runs the statements in the loop, and then evaluates the specified condition and repeats the loop until the condition is met. The Do... Loop Until loop has a similar relationship to the Do... Loop While loop as the Do Until... Loop loop has to the Do... Loop While loop: it works in the same way, but until the condition becomes True rather than while the condition is True. The Do... Loop Until loop uses the following syntax: Do [statements] [statements] Loop Until condition
You can use one or more Exit Do statements to terminate the loop before the Until condition becomes True.
While… Wend Structures The While... Wend structure provides another way of repeating a number of statements while a condition is met. While... Wend uses the following syntax: While condition [statements] Wend
VBA evaluates the condition and, if it is met, executes the statements. On reaching the Wend keyword, VBA returns to the While statement, reevaluates the condition, and continues the loop as appropriate. The following statements use a While... Wend loop to increment the counter intCounter. The loop terminates when intCounter has a value greater than 10. intCounter = 5 While intCounter = 500 .Font.ColorIndex = 13 ‘purple End Select End With
VBA evaluates the Case statement in turn, so you need to either make them mutually exclusive or arrange them in an appropriate order. (Here, they are mutually exclusive.) Case Else is an optional clause that (if it is included) runs if none of the given expressions is matched. The example does not need a Case Else statement, because its Case statements handle the full range of numbers.
The Excel object model is the logical structure that describes how the Excel objects—the components of Excel—fit together. The Excel and Word object models are multilayered, with objects within objects within objects, resembling a set of Chinese boxes, with one object inside another inside another. Other than the application object (Excel), all the other Excel objects—cells, ranges, columns, rows, worksheets, menus, toolbars, and so forth—are subsidiaries of other objects. For example, a column is contained within a worksheet. When we talk about these two objects in human language or in VB code, the worksheet is the parent object of the column object, which is its child. Visual Basic is radically different than human society and more like a mother bear and her cubs. In Visual Basic, you can’t “talk” directly to a child object without first going through the parent object. While you don’t have to memorize the entire object model, you must be familiar with the concept of an object model and be able to navigate the model in order to program in Excel. There are two reasons for this. An object’s properties and methods are only accessible through the object. And child objects other than the current object are only accessible through their parent object. The object model describes the relationships between objects so you can navigate from a parent object to a child object. Here’s an example: You want to be able to work with a range of cells A1:A10 in the worksheet named Feb 01 in the Payroll.xls workbook. But you can’t refer to the range of cells until you switch to the parent object: the Feb 01 worksheet. If Payroll.xls is not the active workbook, you must first make it the active workbook, so you can refer to the child object Feb 01 worksheet, then to the range of cells A1:A10 on that worksheet.
PART
VIII Appendices
The Excel Object Model
4002appB.qxd 7/18/01 2:51 AM Page 820
820
APPENDIX B • VBA Quick Reference
NOTE The Excel object model has been updated for Excel 2002. There are several new objects, events, methods, and properties available for Visual Basic programming. See the “What’s New” section in the Excel Object Library Help File for the new items, and how and when to use them. Figure B.2 shows the representation of the Excel object model provided in the Excel Visual Basic Help file. To display the object model, open the Visual Basic Editor (Tools Macro Visual Basic Editor) and select Microsoft Visual Basic Help from the Help menu. If your Office Assistant is active, choose any topic to open the Microsoft Visual Basic Help dialog box. On the Index tab of the Microsoft Visual Basic Help dialog box, enter object as your keyword, and then choose the topic titled Microsoft Excel Objects. All the objects in the collection are hyperlinked to their Help topics, so you can access the Help topic for an object by clicking the picture of the object. The objects with an arrow to the right of the hyperlink contain their own object model. Click on the arrow to display the related object models. FIGURE B.2 The Excel object model, as shown in the Excel VB Help file. Click an object to see its Help topic.
In general, to work with an object, you access it through the object model, starting from the top. For example, to access the Border object, you could work through the Application object to the Workbook object to the Worksheet object to the Range object to the Style object from which you can reach the Borders collection and Border object. This is a bit oblique, however, so if you already know the name of the object
4002appB.qxd 7/18/01 2:51 AM Page 821
The Excel Object Model
821
you want to use, consider using the Answer Wizard in the help file to narrow your search. In the following sections, we’ll discuss the most important objects in the Excel object model and how to access them programmatically in your functions and subprocedures. Because the Excel object model contains a large number of objects and this book has a finite number of pages, we will not discuss every object, and for most of the objects we discuss, we will not examine every property and every method. However, you will be able to apply the principles you learn from the discussion in this chapter to the other objects you need to use, and to their properties and methods.
TIP
The Excel object model that is available on the Microsoft Developers Network website indicates which objects are new in Excel 2002.
PART
At the top of the Excel object model is the Application object, which represents the Excel application. You typically use the Application object to access Excel from another application—for example, when using a CreateObject statement to start an Excel session or a GetObject statement to return the current Excel session from Word or Outlook. The following statement starts an Excel session and assigns it to the variable objMyExcel: Set objMyExcel = CreateObject(“Excel.Application”)
This creates an Automation object of the class Excel.Application. In other words, it starts an Excel session that you can then access programmatically from Visual Basic or another application.
Using the Workbook Object A Workbook object represents an Excel workbook and is a member of the Workbooks collection. The Workbooks collection contains all the workbooks that are currently open. Three common properties are used to return a specific Workbook object: Workbooks(index), ActiveWorkbook, and ThisWorkbook. • Workbooks(index) returns a single workbook. The index can be the workbook name or index number. To refer to the first workbook created or opened, the reference is Workbooks(1), and the last workbook created or opened is Workbooks(Workbooks.Count). For example:
VIII Appendices
Using the Application Object
4002appB.qxd 7/18/01 2:51 AM Page 822
822
APPENDIX B • VBA Quick Reference
• To activate the last workbook created: Workbooks(Workbooks.Count). Activate • To close the workbook Finances.xls: Workbooks(“Finances”).Close • ActiveWorkbook returns the workbook that’s currently in the active window (generally the window on top). • To protect the currently active workbook: ActiveWorkbook.Protect() • ThisWorkbook returns the workbook where the Visual Basic code is running— usually, the active workbook. However, if you create an add-in with your code, ThisWorkbook returns the add-in workbook, rather than the active workbook because the code is running in the add-in. The Workbook object is the parent of most of the objects, properties, and methods in Excel. In addition there are two dozen events associated with the Workbook object—events that are triggered directly by a user’s interaction with the workbook. You can write code for any of the events to have your application respond to user actions like printing and closing. Here are details about four of the workbook events to give you some ideas about how to use events: SheetCalculate Event Occurs after a worksheet is recalculated. Use this event to perform actions on a newly calculated worksheet; for example, resorting a range that contains new values. BeforeClose Event Occurs before the workbook closes and before the user is asked to save changes. Use this event to perform any clean-up tasks or to force a save of a changed workbook rather than allowing the user to discard changes. BeforePrint Event Occurs before the workbook is printed. Use this event to recalculate worksheets before printing, force spell checking, or to set printing parameters without user intervention. WindowActivate Event Occurs when any workbook window is activated. Use this event to customize the user interface (for example, by setting the WindowState property to xlMaximized whenever a window is activated so that all the columns of a database are displayed).
Using the Worksheets and Sheets Collection A Worksheet object represents an Excel worksheet and is a member of the Worksheets collection as well as the Range collection and the Sheets collection. The Sheets collection contains all the sheets in the workbook, including chart sheets as well as
4002appB.qxd 7/18/01 2:51 AM Page 823
The Excel Object Model
823
worksheets. The Worksheets collection contains only the Worksheet objects in the specified or active workbook. The following are some common properties and methods used with the Worksheet object and Sheets and Worksheets collections: • Worksheets (index) returns a single worksheet. The index can be the worksheet name or index number. • To hide the first worksheet: ActiveWorkbook.Worksheets(1).Visible = False • To return the Workbook object for the specified worksheet: name = ActiveWorkbook.Worksheets(“constants”).Parent • The Worksheets property returns the entire worksheets collection.
• To create worksheets and add them to the Worksheets collection, use the Add method. This code adds a new worksheet as the last sheet in the active workbook. ActiveWorkbook.Worksheets.Add After:=Worksheets(Worksheets.Count) • The Sheets collection and Worksheets collection use the qualifier Array to return more than one sheet. Use the following to move two sheets to the beginning of the active workbook: Sheets(Array(“Calcs”,”Names”)).Move before:=Sheets(1)
The Worksheets and Sheets collections contain multiple objects, the most important being the Worksheet and Chart objects.
The Worksheet Object Worksheet objects are members of both the Worksheets and Sheets collections. The Worksheet is the workhorse of Excel, where the majority of Excel users devote their energies. Subsequently, there are many child objects, properties, methods, and events associated with the Worksheet object. We will examine a few in this section.
Objects and Collections These objects and collections are child objects and collections of the Worksheet object. To access these objects/collections, either you must reference the worksheet that contains the object or it must be the active sheet.
PART
VIII Appendices
• To copy a range to the same area on all other worksheets in the collection (useful when placing headings or labels on multiple sheets. To place the values in cell range A1 through J1 in the range A1:J1 on all the worksheets in the current workbook, use: Worksheets.FillAcrossSheets(Worksheets(1) .Range(“A1:J1”)
4002appB.qxd 7/18/01 2:51 AM Page 824
824
APPENDIX B • VBA Quick Reference
PageSetup Object The page setup description. This object contains all the page setup attributes as properties. Use PageSetup to format page properties such as margins, centering, headers and footers, paper size, and page orientation. PivotTable Object A Pivot Table Report on the worksheet. Because PivotTables are complex, we recommend that you record Pivot Table Report actions as macros, and then modify the recorded code in your modules. The PivotTable object, in turn, contains many objects, collections, properties, and methods. Range Collection and Object A cell, row, column, a selection of cells, or a 3D range. Ranges are described with A1 notation. The Cells property of the Range object is useful in referencing named cells and ranges.
NOTE
The UsedRange property returns the used range on the specified worksheet. Use this property to select all the used cells in worksheet while not selecting empty cells.
Properties The following frequently used properties are accessed through the worksheet object or worksheets collection. Cells Property Returns a range object that represents all the cells on the worksheet, not just the cells currently in use. For example, Worksheets(1).Cells(2,3).ClearContents clears the formula in Cell C2 on the first worksheet. Cells (2,3) refers to the cell at the intersection of row 2 and column 3. Worksheets(1).Cells.Font.Size = 10 sets the font size to 10 for all the cells on a worksheet. ActiveSheet Property Upon activating a worksheet using the Activate method, you can refer to the worksheet in your code using the ActiveSheet property. For example, these two lines of code activate a specific worksheet in the Worksheets collection, then save the sheet: Worksheets(“Constants”).Activate ActiveSheet.Save
Protection Property Returns the Protection object, which contains the protection properties of the worksheet. The Protection object’s properties define which actions are allowed on the worksheet (allow or disallow deletions, filtering, formatting, insertions, etc.). Rows and Columns Property Returns ranges containing all the rows or columns in the specified worksheet. The Rows and Columns are referenced with a numeric index that defines the column and row numbers.
4002appB.qxd 7/18/01 2:51 AM Page 825
The Excel Object Model
825
Visible Property Determines whether the sheet is visible. Visible is Boolean and can be set to True or False.
TIP If you need to hide a worksheet so the user can’t unhide it, check out the constant class XlSheetVisibility. There are three settings: xlSheetHidden, xlSheetVisible and xlSheetVeryHidden. xlSheetVeryHidden hides the sheet so that the only way for the sheet to be visible again is for the Visible property to be programmatically set to True—the user cannot make the object visible. Now that’s VERY hidden.
Methods
Calculate Method Calculates all open workbooks (Calculate), a specific worksheet in a workbook (ActiveSheet.Calculate), or a range of cells on a worksheet (ActiveSheet.UsedRange.Rows(1:3).Calculate). Delete Method Deletes the specified object. Can delete the entire worksheet (ActiveSheet.Delete) or just a range of cells (ActiveSheet.Range(“A1:B5”).Delete). Move Method Moves the worksheet to another location in the workbook. Specify either the sheet before or the sheet after which the moved sheet will be placed. You cannot specify both before and after. If you don’t specify either before or after, Excel creates a new workbook and puts the moved sheet into it. Worksheets(“mySheet”).Move after:=Worksheets(Worksheets.Count) moves mySheet to the end of the Workbook. Worksheets(“mySheet”).Move before:=Worksheets(“Sheet1”) moves mySheet before Sheet1 in the workbook.
The Chart Object The Chart object represents a chart in the workbook that can be either an embedded chart or on a separate chart sheet. Charts are members of the Sheets collection and ChartObjects (embedded charts) are part of the Worksheets collection. Confusing? Indeed, the Excel Object Model representation cannot fit on a single screen. Briefly, these are the referencing rules: • Workbooks contain the Charts collection. The Charts collection is a collection of all the chart sheets in the workbook. • The Charts collection contains Chart objects (among other objects). Chart objects are charts that live on their very own sheets. The Charts in the Charts collection are also included in the Sheets collection.
PART
VIII Appendices
Methods are actions that an object can perform, the behaviors of an object. Worksheets have lots of properties and objects, but only a few methods. This makes sense when you think about the limited number of things you can do with a worksheet. Following is the short list of often-used methods of worksheet objects.
4002appB.qxd 7/18/01 2:51 AM Page 826
826
APPENDIX B • VBA Quick Reference
• The Worksheets collection contains the ChartObjects collection. The ChartObjects collection contains all the charts embedded in the worksheet. • The ChartObjects collection is composed of ChartObject objects. The ChartObject acts as a container for a Chart object embedded on a worksheet. Properties and methods for the ChartObject object control the appearance and size of the embedded chart on the worksheet. Phew! Let’s look at some common objects, properties, and methods to use with Chart and ChartObject objects.
Chart Objects Chart objects are charts stored on chart sheets rather than embedded in worksheets. Use the properties and methods of a chart and the objects and collections it contains to create or modify a chart programmatically. ChartArea Object Represents the area of a chart. If the chart is 2D, the chart area contains the axes, the chart title, the axis titles, and the legend. A 3D chart only contains the chart title and the legend—the rest of the data resides in the PlotArea object. The ChartArea object has three child objects: Border, Font, and Interior. Legend Object Represents the legend in a chart. There can be only one. However, the Legend object contains the LegendEntries collection, which is made up of text and markers for each entry in the Legend. Legend entries are formatted using the LegendKey object. Shapes Collection Contains all of the Shape objects on the specified chart. A shape can be an AutoShape, freeform, OLE object, or picture. There is also a ShapeRange collection, which represents a subset of the shapes on the chart. ChartType Property The type of chart currently selected. The constant XlChartType is used to set the chart type. In Excel 2002 there are 73 predefined chart types, and you can create additional user-defined chart types. HasAxis Property Used to set which axes exist on the chart. HasAxis has two arguments, Index1 which is the axis type and Index2 which is the axis group. Axis type can be either a category, a value, or a series axis (used only on 3D charts). Axis group can be primary or secondary. SizeWithWindow Property Excel will resize the chart to match the size of the chart window if set to True. This property only applies to chart sheets, not the ChartObject described below.
Chart Methods As with most objects, Charts have fewer methods than properties, objects, or collections, because Charts don’t do that many things. They spend most of
4002appB.qxd 7/18/01 2:51 AM Page 827
The Excel Object Model
827
their time vogueing around the workbook, hoping someone will notice. Here are frequently used Chart methods: ChartWizard Method Unlike the Microsoft wizards so popular with end users, the ChartWizard method is noninteractive and is used to quickly format a chart without setting all of the individual properties. It does not contain all the possible chart properties, but it will get you started in creating or formatting a chart programmatically. Here is the syntax: MyChart.ChartWizard(Source, Gallery, Format, PlotBy, CategoryLabels, SeriesLabels, HasLegend, Title, CategoryTitle, ValueTitle, ExtraTitle)
For example, you could select a range of cells programmatically, then create a chart to illustrate the cells using the ChartWizard property.
NOTE
The Copy method is quite different for the ChartArea and ChartObject objects. For these types of objects, the Copy method copies the object to the clipboard.
ChartObject Objects
Now, we’ll turn to the objects that are embedded in worksheets: ChartObject objects. ChartObjects are containers that hold charts and other objects. ChartObject objects are more popular with programmers, because chart sheets have limitations about the types of controls they support. If you’re going to focus on one type of object or the other, start here with the ChartObject objects and their objects, properties, and methods. Border Object An entity that represents the borders on all sides of the ChartObject. The properties commonly modified are Color, LineStyle, and Weight. Chart Object The chart contained within the embedded ChartObject. The Chart object has objects and properties of its own such as titles, fonts, and plot areas, which are accessed through the Chart object. In this example, we use the Chart object to access the ChartTitle property and add a title to the embedded chart: With Worksheets(“Qtr1”).ChartObjects(2).Chart .HasTitle=True .ChartTitle.Text=”First Quarter Sales” End With
PART
VIII Appendices
Copy Method Copies the chart sheet to another location in the workbook. Specify either the sheet before or the sheet after which the copied sheet will be placed, just as with the method of the Worksheet object.
4002appB.qxd 7/18/01 2:51 AM Page 828
828
APPENDIX B • VBA Quick Reference
Interior Object Represents the interior of the object. Some common properties are Color and Pattern. A useful property of the Interior object is the InvertIfNegative property, used to draw attention to unexpected or out of range values. PivotLayout Object Represents the placement of fields in a Pivot Chart report. The properties and methods are similar to those in the PivotChart object. Locked Property A Boolean property set to True if the object is locked and False if the object can be changed even when the sheet it resides on is protected. RoundedCorners Property A Boolean property set to True if the embedded chart has rounded corners. Use this property to draw attention to a selected ChartObject. Placement Property Describes the way the ChartObject is attached to the cell below it, the same properties the user can change in the Format Object dialog box, which is used by other worksheet objects including pictures and text boxes. The xlPlacement values that can be used are xlFreeFloating (the chart is neither moved nor sized with its underlying cells), xlMove (the chart is moved with its underlying cell), and XlMoveAndSize (the chart is both moved and resized with its underlying cell).
Methods The methods of ChartObject objects are worth understanding, because the same methods are used by the drawing objects. BringToFront Method Brings the ChartObject to the front of the z-axis order. The converse method is SendToBack. The ChartObject all the way in the back has a ZOrder property of (1), and the ChartObject closest to the front has a ZOrder property of (ActiveSheet.ChartObjects.Count). Duplicate Method Duplicates a ChartObject. Other objects that can be duplicated are OLE objects and Shape objects. Select Method Selects the ChartObject. Used for selecting many types of objects. An optional parameter in the Select method is Replace. True replaces the current selection with the new selection. False adds the new selection to the current selection.
Working with Excel Events As discussed earlier, an event occurs when the user performs a particular action in an application. For example, an Open event occurs when a workbook or worksheet is opened, and a NewSheet event occurs when a new worksheet is created. By writing code attached to the correct event, you can automatically run an event procedure—a procedure keyed to that particular event—when the user takes the action. Excel supports the events listed in Table B.5. As you can see, the names describe the actions the user takes to trigger the events.
4002appB.qxd 7/18/01 2:51 AM Page 829
Working with Excel Events
TABLE B.5
829
VBA Events Supported by Excel
Event
Applies To
Activate
Chart Workbook
SheetActivate
Workbook Application
WorkbookActivate
Application
AddInInstall
Occurs When the User
Makes a visible object the active window Worksheet
Workbook Application
Installs the workbook as an add-in
Workbook Application
Uninstalls the workbook as an add-in
WorkbookAddInInstall
PART
WorkbookAddInUninstall AfterRefresh
QueryTable
Completes or cancels a query
BeforeClose
Workbook Application
Before the workbook closes and before the user is asked to save changes
WorkbookBeforeClose BeforeDoubleClick
Workbook Chart
SheetBeforeDoubleClick Workbook
Double-clicks the mouse, before the default double-click action
Application Workbook Application
Selects for the workbook (or anything on it) to be printed, before the printing occurs
BeforeRefresh
QueryTable
Occurs before any refreshes of the query table
BeforeRightClick
Worksheet Chart
BeforePrint
WorkbookBeforePrint
SheetBeforeRightClick
Workbook Application
Right-clicks the mouse, before the default right-click action
VIII Appendices
AddInUninstall
4002appB.qxd 7/18/01 2:51 AM Page 830
830
APPENDIX B • VBA Quick Reference
TABLE B.5
VBA Events Supported by Excel (continued)
Event
Applies To
Occurs When the User
BeforeSave
Workbook Application
Saves a workbook, before the save occurs
WorkbookBeforeSave Calculate SheetCalculate
Change
Worksheet Chart Workbook Application Worksheet Workbook Application
After user recalculates a worksheet or plots changed data on a chart
When user changes worksheet cells
SheetChange Deactivate
Worksheet Chart Workbook
SheetDeactivate
Workbook Application
WorkbookDeactivate
Application
Deactivates an activated object
DragOver
Chart
Drags a range of cells over a chart when a range of cells is dragged over a chart then dropped somewhere else.
DragPlot
Chart
Drags and drops a range of cells on a chart
FollowHyperlink
Workbook Workbook Application
Clicks on any hyperlink either on a worksheet or anywhere in Excel
MouseDown
Chart
Presses a mouse button
MouseMove
Chart
Changes the position of a mouse pointer
SheetFollowHyperlink
4002appB.qxd 7/18/01 2:51 AM Page 831
Working with Excel Events
TABLE B.5
831
VBA Events Supported by Excel (continued)
Event
Applies To
Occurs When the User
MouseUp
Chart
Releases a mouse button
NewSheet
Workbook Application
Creates a new sheet in a workbook
NewWorkbook
Application
Creates a new workbook
Open
Workbook Application
Opens a workbook
WorkbookNewSheet
WorkbookOpen PivotTableCloseConnection Workbook
PivotTableOpenConnection WorkbookPivotTable OpenConnection
Application Workbook
Occurs after a PivotTable report opens the connection to its data source Application Worksheet Workbook Application
Occurs after a PivotTable report is updated
Resize
Chart
Resizes a chart
Select
Chart
Selects a chart element
SelectionChange
Worksheet Workbook Application
Changes the selection on a worksheet
Chart
Changes the value of a chart data point
PivotTableUpdate
SheetPivotTableUpdate
SheetSelectionChange SeriesChange
VIII Appendices
WorkbookPivotTable CloseConnection
PART
Occurs after a PivotTable report closes the connection to its data source
4002appB.qxd 7/18/01 2:51 AM Page 832
832
APPENDIX B • VBA Quick Reference
TABLE B.5
VBA Events Supported by Excel (continued)
Event
Applies To
Occurs When the User
WindowActivate
Workbook Application
Activates any workbook window
WindowDeactivate
Workbook Application
Deactivates any workbook window
WindowResize
Workbook Application
Resizes any workbook window
Special Requirements for the Application, ChartObject, and QueryTable Objects Events Most of the events listed in the preceding table are immediately available. There are three exceptions: events for the Application, ChartObject, or QueryTable objects. You can use the properties, objects, and methods of these three objects with ease, but the events of these three objects require extra setup to expose their events. To do this, create a new class module and declare the new objects With Events, which adds the events to the drop-down list in the code window so you can use the events in code. The code won’t run until you take one other step: connect the object you declared WithEvents in the class module to the object. You can do this in any module. This is a bit complex, so we’ll walk through it. To set up Application, ChartObject, and QueryTable events, first create a new class module: 1. In the Visual Basic IDE, choose Insert Class Module from the menu. 2. Select the module in the Project Explorer. In the Properties Window, change the (Name) for the class module; we suggest EventClassModule. 3. In the Code Window, enter the following statements in the class module: ‘*define Application object Public WithEvents myApp as Application
‘* define QueryTable Object Public WithEvents myQueryTable as QueryTable
4002appB.qxd 7/18/01 2:51 AM Page 833
Working with Excel Events
833
‘* define ChartObject Object Public WithEvents myChartObject as Chart
Save the class module so you can call it from other modules in your application. Now, add the code to connect the three objects in the class module to the Application, QueryTable, and ChartObjects objects in your application. You can place the connection code in the class module. We prefer to place it in the module where we use the events of these objects so we remember to run the subroutines as part of our application: ‘* define the new class module - run from any module Dim myClassModule as New EventClassModule PART
Sub InitQueryEvent (QT as Object) Set myQueryTable = QT[Gini: tabs aren’t allowed in our code. Brianne][Brianne: OK. Kill it. Gini] End Sub
‘* connect the Application Object Sub InitApplication() Set myClassModule.myApp = Application End Sub
‘* connect the ChartObject Object Sub InitChart() Set myClassModule.myChartObject = Worksheets(1).ChartObjects(1).Chart End sub
After running the appropriate InitQueryEvent, InitApplication, or InitChart procedure, the event procedures that were coded in the class module will run when the events occur. Only use the procedures you need: if you’re not using any of the ChartObject events, there’s no reason to connect the ChartObject object at the beginning of every application. These events, and others, are explained in the following section. Events that are asterisked (*) are events of the Application, ChartObject, and QueryTable objects, and require declaration WithEvents before they can be used.
VIII Appendices
‘* connect the Query Table Object
4002appB.qxd 7/18/01 2:51 AM Page 834
834
APPENDIX B • VBA Quick Reference
Activate and Deactivate Events The Activate and Deactivate events are triggered when a UserForm object becomes the active window (gets focus) or is no longer the active window (loses focus). These events apply to UserForms collections and UserForm objects within Excel’s VBA modules. Merely loading an object into memory does not activate it, but it is activated when you use the Show method to display it. The following is the syntax for code that runs on the events of a UserForm named myForm: [Private] Sub myForm_Activate() ‘add code here End Sub [Private] Sub myForm_Deactivate() ‘add code here End Sub
Write code for the Activate and Deactivate events when you want to take an action while a form is active. For example, you could start a timer with the Activate event and stop it with the Deactivate event to determine how long it took a user to complete a form.
NOTE
The Activate and Deactivate events are triggered when the object focus is changed within Excel: for example, clicking on a worksheet when the UserForm had the focus. Moving the focus to or from another application’s objects (clicking something in Word when an Excel UserForm had the focus) will not cause the Activate and Deactivate events to trigger.
SheetActivate and SheetDeactivate The SheetActivate and SheetDeactivate events are triggered when a worksheet or chart object within a workbook or application object gets focus or loses focus. The SheetActivate and SheetDeactivate events are only triggered when the object focus is changed within Excel. Moving the focus to or from another application’s object will not cause them to trigger.
4002appB.qxd 7/18/01 2:51 AM Page 835
Working with Excel Events
835
The following is the syntax for a Workbook named myWorkbook and Worksheet Sheet1: [Private] Sub myWorkbook_SheetActivate(ByVal Sheet1 as Object) ‘code here End Sub [Private] Sub myWorkbook_SheetDeactivate(ByVal Sheet1 as Object) ‘code here End Sub
WorkbookActivate* and WorkbookDeactivate*
[Private] Sub ExcelApp_WorkbookActivate(ByVal myWorkbook as Workbook) ‘code here End Sub [Private] Sub ExcelApp_WorkbookDeactivate(ByVal myWorkbook as Workbook) ‘code here End Sub
AddinInstall and AddinUninstall Events The AddinInstall and AddinUninstall events are triggered when a workbook is installed or uninstalled as an add-in. The current workbook is inferred in the following syntax: [Private] Sub Workbook_AddinInstall() ‘code here End Sub [Private] Sub Workbook_AddinUninstall() ‘code here End Sub
PART
VIII Appendices
The WorkbookActivate and WorkbookDeactivate events are triggered when a Workbook object within an Application object gets or loses focus. The WorkbookActivate and WorkbookDeactivate events are only triggered when the object focus is changed within Excel. Moving the focus to or from another application’s object will not cause them to trigger. See “Special Requirements for the Application, ChartObject, and QueryTable Objects Events” earlier in this chapter for information on using events with the Application object. The following is the syntax for Application ExcelApp and Workbook myWorkbook:
4002appB.qxd 7/18/01 2:51 AM Page 836
836
APPENDIX B • VBA Quick Reference
WorkbookAddinInstall* and WorkbookAddinUninstall* The WorkbookAddinInstall and WorkbookAddinUninstall events are triggered when a Workbook within an Application object is installed or uninstalled as an add-in. These two events are events of the Application object, so see the “Special Requirements for the Application, ChartObject, and QueryTable Objects Events” sidebar for information on using events with the Application object. The following is the syntax for Application ExcelApp and Workbook myWorkbook: [Private] Sub ExcelApp_WorkbookAddinInstall(ByVal myWorkbook as Workbook) ‘code here End Sub [Private] Sub ExcelApp_WorkbookAddinUninstall(ByVal myWorkbook as Workbook) ‘code here End Sub
Calculate Events The Calculate event is triggered after a chart plots new or changed data or after a worksheet is recalculated; with automatic calculation enabled, this event is triggered frequently, and triggered with each change in focus if the worksheet includes a volatile function like NOW. The following is the syntax for a Worksheet: [Private] Sub Worksheet_Calculate() ‘code here End Sub
The following is the syntax for a Chart: [Private] Sub Chart_Calculate() ‘code here End Sub
SheetCalculate* The SheetCalculate event is triggered after a worksheet or chart is recalculated. The object can be either an Application or Workbook object. See the “Special Requirements for the Application, ChartObject, and QueryTable Objects Events” for information on using events with the Application object.
4002appB.qxd 7/18/01 2:51 AM Page 837
Working with Excel Events
837
The following is the syntax for Application ExcelApp and Worksheet Sheet1: [Private] Sub ExcelApp_SheetCalculate(ByVal Sheet1 as Object) ‘code here End Sub
The following is the syntax for Workbook myWorkbook and Chart Chart1: [Private] Sub myWorkbook_SheetCalculate(ByVal Chart1 as Object) ‘code here End Sub
Change Events
[Private] Sub Worksheet_Change(ByVal myChanges as Range) ‘code here End Sub
SheetChange* The SheetChange event is triggered when cells on a worksheet are changed by the user or by an external link. The object can be either an Application or Workbook object. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The following is the syntax for Application, Worksheet Sheet1, and Source myChanges: [Private] Sub Application_SheetChange(ByVal Sheet1 as Object, myChanges as Range) ‘code here End Sub
The syntax for a Workbook, Worksheet Sheet2, and Source myChanges is the following: [Private] Sub Workbook_SheetChange(ByVal Sheet2 as Object, myChanges as Range) ‘code here End Sub
PART
VIII Appendices
The Change event is triggered when the cells on a worksheet are changed by the user or by an external link. The range can be specified using the target parameter. The syntax for target myChanges is the following:
4002appB.qxd 7/18/01 2:51 AM Page 838
838
APPENDIX B • VBA Quick Reference
BeforeClose Events The BeforeClose event occurs before the workbook closes and before the user is prompted to save changes. The Cancel argument is set to False when the event occurs. If the event procedure sets the Cancel argument to True, the close operation stops. Use this syntax to address the BeforeClose event for the current workbook: [Private] Sub Workbook_BeforeClose(Cancel as Boolean) ‘code here End Sub
WorkbookBeforeClose* The WorkbookBeforeClose event occurs immediately before any open workbook closes. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The following is the syntax for Application ExcelApp and Workbook myWorkbook: [Private] Sub ExcelApp_WorkbookBeforeClose(ByVal myWorkbook as Workbook, Cancel as Boolean) ‘code here End Sub
DragOver and DragPlot Events The DragOver event is triggered when a range of cells is dragged over a chart but not dropped on the chart and can simulate the behavior of the worksheet when a range of cells is dragged around over the worksheet. The DragPlot event is triggered when a range of cells is dragged and dropped on a chart. Both events occur only with the Chart object. The syntax is for myChart is the following: [Private] Sub myChart_DragOver() ‘code here End Sub [Private] Sub myChart_DragPlot() ‘code here End Sub
4002appB.qxd 7/18/01 2:51 AM Page 839
Working with Excel Events
839
BeforeDoubleClick and BeforeRightClick Events For a Worksheet object, the BeforeDoubleClick event occurs when a worksheet is double-clicked, and the BeforeRightClick event occurs when the worksheet is rightclicked. For a Chart object, the BeforeDoubleClick event occurs when an embedded chart is double-clicked and the BeforeRightClick event occurs when the embedded chart is right-clicked. The syntax and arguments differ based on the type of object. For a Worksheet object, the Target argument is required. Target is the cell nearest to the mouse pointer when the double-click or right-click occurs. The optional Cancel argument is False when the event occurs, and can be set to True by the event procedure, which would stop execution of the default double-click or right-click action. Here are the BeforeDoubleClick and BeforeRightClick events at work: [Private] Sub Worksheet_BeforeDoubleClick(ByVal Target as Range, Cancel as Boolean) End Sub [Private] Sub Worksheet_BeforeRightClick(ByVal Target as Range, Cancel as Boolean) ‘code here End Sub
With a Chart object, however, the arguments are different for the double-click and right-click events. For the BeforeRightClick event, the only argument is Cancel, which is required. The following is the syntax: [Private] Sub Chart_BeforeRightClick(ByVal Cancel as Boolean) ‘code here End Sub
The BeforeDoubleClick event, on the other hand, contains a plethora of arguments. ElementID, Arg1, and Arg2 are three related arguments; the values of Arg1 and Arg2 are dependent on value of ElementID. See Excel’s Visual Basic Help for the topic “BeforeDoubleClick Event” to find out about the 31 possible Element ID’s and the associated arguments. The ElementID field contains the constant for a chart element, such as XlDataLabel or XlShape. The possible values for Arg1 and Arg2 are listed in Table B.6.
PART
VIII Appendices
‘code here
4002appB.qxd 7/18/01 2:51 AM Page 840
840
APPENDIX B • VBA Quick Reference
TABLE B.6
BeforeDoubleClick Event Arguments for a Chart Object
Argument
Description
Possible Values
AxisIndex
Specifies whether the axis is primary or secondary or a group. Constants are in XlAxisGroup.
xlPrimary xlSecondary
AxisType
Specifies the axis type: Category, Series, or Value. Constants are in the XlAxisType.
xlCategory xlSeriesAxis xlValue
DropZoneType
Specifies drop zone type: Column, Data, Page, or Row Field. Constants are in the XlPivotFieldOrientation.
xlColumnField xlDataField xlPageField xlRowField
GroupIndex
Specifies the offset within the ChartGroups collection.
1 to Chart.ChartGroups.Count
PivotFieldIndex
Specifies the offset in the PivotFields collection for a specific column, data, page, or row field.
1 to PivotFields.Count
PointIndex
Specifies the offset in the Points collection for a specific point in the series. The value -1 means all points are selected.
-1 or 1 to Points.Count
SeriesIndex
Specifies the offset in the SeriesCollection for a specific shape.
1 to SeriesCollection.Count
ShapeIndex
Specifies the offset in the Shapes collection for a specific shape.
1 to Shapes.Count
TrendlineIndex
Specifies the offset in the Trendlines collection for a specific trendline within a series.
1 to SeriesCollection(1) .Trendlines.Count
The optional Cancel argument is False when the event occurs, and can be set to True by the event procedure, which would stop execution of the default double-click action. For a BeforeDoubleClick event with ElementID xlAxis, Arg1 must be AxisIndex, and Arg2 must be AxisType. The following is the subprocedure syntax: [Private] Sub Chart_BeforeDoubleClick(ByVal ElementID as Long, ByValArg1 as Long, ByVal Arg2 as Long, Cancel as Boolean) ‘code here End Sub
4002appB.qxd 7/18/01 2:51 AM Page 841
Working with Excel Events
841
SheetBeforeDoubleClick* and SheetBeforeRightClick* The SheetBeforeDoubleClick and SheetBeforeRightClick events occur when any worksheet is double-clicked or right-clicked before the default actions. This event applies to Workbook and Application objects. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. Both events require the Target argument, the cell nearest the mouse pointer for a double-click event. They also can contain an optional Cancel argument, which is False when the event occurs and can be set to True by the event procedure in order to stop execution of the default doubleclick action. The following is the syntax for Application ExcelApp and Worksheet Sheet1: [Private] Sub ExcelApp_SheetBeforeDoubleClick(ByVal Sheet1 as object, ByVal Target as Range, ByVal Cancel as Boolean)
The following is the syntax for Workbook myWorkbook and Worksheet Sheet1: Target as Range, ByVal Cancel as Boolean)
FollowHyperlink Events The FollowHyperlink event is triggered when any hyperlink is clicked on a worksheet. The current worksheet is inferred in the syntax, and the Target argument contains the Hyperlink object that represents the destination of the hyperlink: [Private] Sub Worksheet_FollowHyperlink(ByVal Target as Hyperlink)
SheetFollowHyperlink The SheetFollowHyperlink event is triggered when any hyperlink is clicked in Excel. The worksheet containing the hyperlink is a required argument, as is the Target argument containing the Hyperlink object that represents the destination of the hyperlink. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The following is syntax for Application ExcelApp and Worksheet Sheet1: [Private] Sub ExcelApp_SheetFollowHyperlink(ByVal Sheet1 as Object, ByVal Target as Hyperlink)
The following is the syntax for the active Workbook and Worksheet Sheet2: [Private] Sub Workbook_SheetFollowHyperlink(ByVal Sheet2 as Object, ByVal Target as Hyperlink)
PART
VIII Appendices
[Private] Sub myWorkbook_SheetBeforeRightClick(ByVal Sheet1 as object, ByVal
4002appB.qxd 7/18/01 2:51 AM Page 842
842
APPENDIX B • VBA Quick Reference
MouseDown, MouseMove, and MouseUp Events The MouseDown, MouseMove, and MouseUp events are all triggered by mouse actions over a chart sheet or imbedded chart (a ChartObject). Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. MouseDown occurs when a mouse button is pressed, MouseMove occurs when the position of a mouse pointer changes, and MouseUp occurs when a mouse button is released. They all have the same syntax and require the same arguments. The Button argument is the mouse button pressed. The possible values are xlNoButton, xlPrimaryButton, xlSecondaryButton, or xlMiddleButton. The Shift argument describes the state of the Shift, Ctrl, and Alt keys at the time of the mouse event. Like in the arguments for a MsgBox, the value of Shift can be any of the values associated with the Shift, Ctrl, or Alt keys or a sum to indicate multiple keys were pressed. The X argument is the X coordinate of the mouse pointer in the chart and the Y argument is the Y coordinate of the mouse pointer in the chart. For Chart myChart the syntax is the following: [Private] Sub myChart_MouseDown(ByVal XlPrimaryButton as Long, ByVal Shift as Long, ByVal X as Long, ByVal Y as Long)
NewSheet and NewWorkbook Events The NewSheet event occurs when a new sheet is created in the current workbook. (See WorkbookNewSheet if you need to create a sheet in a workbook that is not the active workbook.) This event only applies to a Workbook object. The current workbook is inferred in the syntax, and the new sheet can be a Worksheet or Chart object. To add a new Chart called myChart, use the following syntax: [Private] Sub Workbook_NewSheet(ByVal myChart as Object)
WorkbookNewSheet The WorkbookNewSheet event is triggered when a new sheet is created in any open workbook within an Application object. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The workbook that contains the new sheet is passed as an argument and the new sheet can be a worksheet or chart object. To add a new Worksheet called mySheet, with Workbook myWorkbook and Applicaton ExcelApp, use the following syntax: [Private] Sub ExcelApp_WorkbookNewSheet(ByVal myWorkbook as Workbook, ByVal mySheet as Object)
4002appB.qxd 7/18/01 2:51 AM Page 843
Working with Excel Events
843
NewWorkbook The NewWorkbook event is triggered when a workbook is created. This event only applies to an Application object. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The name of the new Workbook is passed as an argument. For the Application object ExcelApp and Workbook myWorkbook, use the following syntax: [Private] Sub ExcelApp_NewWorkbook(ByVal myWorkbook as Workbook)
Open Events The Open event is triggered when a workbook is opened. The current workbook is inferred in the following syntax: [Private] Sub Workbook_Open()
The WorkbookOpen event is triggered when a workbook within an Application object is opened. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The following is the syntax for Application ExcelApp and Workbook myWorkbook: [Private] Sub ExcelApp_Open(ByVal myWorkbook as Workbook)
NOTE
Close is a method, not an event. Use the BeforeClose event to perform processing related to closing an object.
PivotTable Events PivotTables have many of the same events that other Excel objects have, but there are a number of events specific to pivot tables. Charts, for example, update automatically, while pivot tables must be refreshed, either manually or through an automated process. The following events apply specifically to pivot tables.
PivotTableCloseConnection and PivotTableOpenConnection The PivotTableOpenConnection and PivotTableCloseConnection events are triggered after a Pivot Table report opens or closes the connection to its data source. These events apply to a Workbook object. The only argument passed is the Target, which
PART
VIII Appendices
WorkbookOpen
4002appB.qxd 7/18/01 2:51 AM Page 844
844
APPENDIX B • VBA Quick Reference
is the selected Pivot Table report as a PivotTable object. For the Workbook myWorkbook the syntax is the following: [Private] Sub myWorkbook_PivotTableCloseConnection(ByVal Target as PivotTable) ‘code here End Sub [Private] Sub myWorkbook_PivotTableOpenConnection(ByVal Target as PivotTable) ‘code here End Sub
WorkbookPivotTableCloseConnection and WorkbookPivotTableOpenConnection The PivotTableOpenConnection and PivotTableCloseConnection events are triggered after a Pivot Table report opens or closes the connection to its data source. These events apply to an Application object. See the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar for information on using events with the Application object. The arguments passed are Workbook, which contains the PivotTable in question, and Target, which is the selected PivotTable report as a PivotTable object. For Application ExcelApp and Workbook myWorkbook the syntax is the following: [Private] Sub ExcelApp_PivotTableCloseConnection(ByVal myWorkbook as Workbook, ByVal Target as PivotTable) ‘code here End Sub [Private] Sub ExcelApp_PivotTableOpenConnection(ByVal myWorkbook as Workbook, ByVal Target as PivotTable) ‘code here End Sub
PivotTableUpdate The PivotTableUpdate event is triggered after a Pivot Table report is updated on a worksheet. This event applies to a Worksheet object. The only argument passed is the Target, which is the selected Pivot Table report as a PivotTable object. For the Worksheet mySheet1 the syntax is the following: [Private] Sub mySheet1_PivotTableUpdate(ByVal Target as PivotTable) ‘code here End Sub
4002appB.qxd 7/18/01 2:51 AM Page 845
Working with Excel Events
845
SheetPivotTableUpdate* The SheetPivotTableUpdate event is triggered after a sheet containing a Pivot Table report has been updated. The event applies to Worksheet and Application objects. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The arguments passed are Worksheet, which contains the PivotTable, and Target, which is the selected Pivot Table report as a PivotTable object. For Application ExcelApp and Worksheet mySheet1 the syntax is the following: [Private] Sub ExcelApp_SheetPivotTableUpdate(ByVal mySheet1 as Object, ByVal Target as PivotTable) ‘code here End Sub
AfterRefresh* and BeforeRefresh* Events
[Private] Sub QueryTable_AfterRefresh(Success as Boolean) ‘code here End Sub
The BeforeRefresh event occurs before the QueryTable is refreshed. It can be refreshed by calling the Refresh method, from opening the QueryTable’s workbook, or by user’s actions. This event applies to a QueryTable object. The only argument passed is Cancel, a Boolean variable that defaults to False when the BeforeRefresh event occurs and can be set to True in order to stop the refresh action from occurring. The current QueryTable is inferred in the following syntax: [Private] Sub QueryTable_BeforeRefresh(Cancel as Boolean) ‘code here End Sub
BeforePrint Events The BeforePrint event occurs before anything in the workbook is printed. This event applies to the Workbook object and the current workbook is inferred in the syntax. The only argument passed is Cancel, a Boolean variable that defaults to False when
PART
VIII Appendices
The AfterRefresh event is triggered after a query completes or is canceled. This event applies to a QueryTable object. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The only argument passed is Success, a Boolean variable that is set to True if the query completed successfully and False if it failed or was canceled. The current QueryTable is inferred in the following syntax:
4002appB.qxd 7/18/01 2:51 AM Page 846
846
APPENDIX B • VBA Quick Reference
the BeforePrint event occurs and can be set to True in order to stop the print action from occurring. [Private] Sub Workbook_BeforePrint(Cancel as Boolean) ‘code here End Sub
WorkbookBeforePrint* The WorkbookBeforePrint event occurs before any open workbook is printed. This event applies to the Application object. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The two arguments passed are the Workbook being printed and Cancel, a Boolean variable that defaults to False when the WorkbookBeforePrint event occurs and can be programmatically set to True in order to stop the print action from taking place. For Application ExcelApp and Workbook myWorkbook the syntax is the following: [Private] Sub ExcelApp_WorkbookBeforePrint(ByVal myWorkbook as Workbook, ByVal Cancel as Boolean) ‘code here End Sub
BeforeSave Events The BeforeSave event occurs before the workbook is saved. This event applies to the Workbook object, and the current workbook is inferred in the syntax. The arguments passed are SaveAsUI, a Boolean variable set to True if the Save As dialog box will be displayed, and Cancel, a Boolean variable that defaults to False when the BeforeSave event occurs and can be set to True in order to stop the Save action from occurring. [Private] Sub Workbook_BeforeSave(ByVal SaveAsUI as Boolean, ByVal Cancel as Boolean) ‘code here End Sub
WorkbookBeforeSave* The WorkbookBeforeSave event occurs before any open workbook is saved. This event applies to the Application object. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The three arguments passed are the Workbook being saved, SaveAsUI (a Boolean variable set to True if the Save As dialog box will be displayed), and Cancel (a Boolean variable that defaults to False when the WorkbookBeforeSave event occurs and can be programmatically set to True in order
4002appB.qxd 7/18/01 2:51 AM Page 847
Working with Excel Events
847
to stop the save action from taking place). For Application ExcelApp and Workbook myWorkbook the syntax is the following: [Private] Sub ExcelApp_WorkbookBeforeSave(ByVal myWorkbook as Workbook, ByVal SaveAsUI as Boolean, ByVal Cancel as Boolean) ‘code here End Sub
SelectionChange and SeriesChange Events The SelectionChange events are triggered when a user selects a different range of cells in a worksheet—a common phenomenon. The SeriesChange events are triggered for a series when the value of a data point in the series changes because the data point’s value changed in the worksheet.
The SelectionChange event is triggered when a worksheet’s selection changes. This event applies only to the Worksheet object (not a Chart object) and the current worksheet is inferred in the syntax. The only argument passed is Target, a Range object that contains the new selected range. The syntax for the SelectionChange event is the following: [Private] Sub Worksheet_SelectionChange(ByVal Target as Range) ‘code here End Sub
SheetSelectionChange The SheetSelectionChange event is triggered when any worksheet’s selection changes and is not triggered by changes to the selection on a chart. This event applies to the Application and Workbook objects. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The two arguments passed are the Worksheet containing the new selection and Target, a Range object that contains the new selected range. The following is the syntax for Application ExcelApp and Worksheet mySheet1: [Private] Sub ExcelApp_SheetSelectionChange(ByVal mySheet1 as Object, ByVal Target as Range) ‘code here End Sub
PART
VIII Appendices
SelectionChange
4002appB.qxd 7/18/01 2:51 AM Page 848
848
APPENDIX B • VBA Quick Reference
The following is the syntax for Workbook myWorkbook and Worksheet mySheet2: [Private] Sub myWorkbook_SheetSelectionChange(ByVal mySheet2 as Object, ByVal Target as Range)
SeriesChange The SeriesChange event is triggered when the value of a chart data point is changed. This event applies to chart sheets and imbedded charts (ChartObject). Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. The arguments passed are SeriesIndex and PointsIndex. SeriesIndex is the offset within the Series collection for the series that was changed, and the PointIndex is the offset within the Points collection (which is part of the Series object referred to in SeriesIndex) for the point that was changed. For Chart myChart1, the syntax is the following: [Private] Sub myChart1_SeriesChange(ByVal SeriesIndex as Long, ByVal PointIndex as Long) ‘code here End Sub
Window Events* Window events are triggered when a user interacts with the window, either by switching windows or resizing a window.
WindowActivate*, WindowDeactivate*, and WindowResize* The WindowActivate and WindowDeactivate events are triggered when any workbook window is activated. The WindowResize event is triggered when any workbook window is resized. These events apply to Workbook and Application objects. Also see the “Special Requirements for Application, ChartObject, and QueryTable Events” sidebar. When the Workbook object is used, the current workbook is inferred in the syntax. When the Application object is used, the workbook displayed in the active window is passed as an argument. The Window argument, a Window object, is always used in these events. For the current Workbook and myWindow, the syntax is the following: [Private] Sub Workbook_WindowActivate(ByVal myWindow as Window) ‘code here End Sub
4002appB.qxd 7/18/01 2:51 AM Page 849
Working with Excel Events
849
[Private] Sub Workbook_WindowDeactivate(ByVal myWindow as Window) ‘code here End Sub [Private] Sub Workbook_WindowResize(ByVal myWindow as Window) ‘code here End Sub
For Application ExcelApp, Workbook myWorkbook, and Window myWindow, use the following sytax: [Private] Sub ExcelApp_WindowActivate(ByVal myWorkbook as Workbook, ByVal myWindow as Window) ‘code here End Sub PART
myWindow as Window) ‘code here End Sub [Private] Sub ExcelApp_WindowResize(ByVal myWorkbook as Workbook, ByVal MyWindow as Window) ‘code here End Sub
VIII Appendices
[Private] Sub ExcelApp_WindowDeactivate(ByVal myWorkbook as Workbook, ByVal
4002appB.qxd 7/18/01 2:51 AM Page 850
This page intentionally left blank
4002appC.qxd 7/17/01 12:34 PM Page 851
APPENDIX
C
USING MAPPOINT 2002 WITH EXCEL 2002
4002appC.qxd 7/17/01 12:34 PM Page 852
xcel 97 and Excel 2000 included a Data Map applet, used to illustrate geographic data: data based on countries, states, and provinces. For an extra hundred bucks, you could purchase the United States zip code database and map data down to the zip code level. Like Clippit, Data Map has been retired in Excel 2002. Unlike Clippit, you can’t click a button and bring Data Map back.
e
NOTE
If you have worksheets that include data maps, you can’t update the maps in Excel 2002.
In our opinion, losing Data Map isn’t much of a loss. The Data Map tool was incredibly limited. Its clunkiness was particularly evident because it ran within Excel, perhaps the most intuitive Microsoft desktop application. The Data Map maps, while not precisely ugly, were not things of beauty. They were difficult to format and suffered when compared to almost any Excel chart object. So when Microsoft removed Data Map from Excel 2002, we were delighted, if only because it freed up a few bytes of memory that most users have far better uses for. We don’t use Data Map, but we do map geographic data. Even though Data Map was included in Office 2000, when we migrated, we also switched to Microsoft’s other mapping application, MapPoint. MapPoint imports data directly from Excel. We use MapPoint to create beautiful maps that we aren’t ashamed to include in proposals, display in a PowerPoint presentation, or post on a website. The map in Figure C.1 was an ad hoc response to the question: What will the population surrounding Santa Clarita, California, look like in five years? Within 10 minutes, our client had a mapped answer in their Inbox. MapPoint is to Data Map what Excel is to that wimpy spreadsheet included in Microsoft Works: a product that’s good enough for business use. Whether or not you used Data Map, if you need a serious tool to map data that integrates with Excel 2002 and Office XP, MapPoint is worth a closer look.
NOTE
Apologies in advance for sounding like a Microsoft commercial—we like MapPoint as much as we disliked Data Map. This is great software and fills the only real gap in Microsoft Excel: summarizing and analyzing geographic data.
4002appC.qxd 7/17/01 12:34 PM Page 853
MapPoint 2002
853
FIGURE C.1 This projected population map took less than 10 minutes to prepare in MapPoint 2002. Although not visible in this figure, a key displayed on the MapPoint screen identifies the population ranges in each of the shaded zip codes.
PART
MapPoint has one disadvantage: it consumes lots of resources. The minimum drive space for installation is a half a gigabyte. If you want to use the Territories feature, you’ll need about 1GB of hard drive space and a minimum of 192MB of memory to run MapPoint efficiently.
MapPoint 2002 The new version of MapPoint, MapPoint 2002, was released concurrently with Office XP. If you were one of the 100,000+ people who attended the Office XP launch, you received a free copy of MapPoint 2002. At the full retail price of $249, MapPoint is still a steal: it includes thousands of dollars of demographic data from Claritas including current population and projected population growth disaggregated by age, education, gender, race/ethnicity, and income. Combine this data with your Excel data to create maps that help you analyze a wide range of business issues: • Where are our customers now? • Where will they be in five years? • Does our location inhibit our business growth? • Where should we put our new office?
Appendices
VIII
4002appC.qxd 7/17/01 12:34 PM Page 854
854
APPENDIX C • Using MapPoint 2002 with Excel 2002
MapPoint 2002 has a number of features that are important to Excel users: • Import Data Wizard for Excel data. • Export to Excel feature that sends mapped data to an Excel workbook. • Tight integration with Excel 2002, including a MapPoint button on the Standard toolbar and smart tag support for geographic terms like state, city, and zip code. • Mapping down to the street address level so none of your data is wasted. • Data Mapping Wizard that walks you through the map creation process. • Create Territories Wizard you can use to define custom areas for your business: for example, sales areas, shipping zones, franchise areas, or employee coverage areas.
Importing and Mapping Excel Data With MapPoint 2002, you can import Excel worksheets and named ranges. Choose File New in MapPoint and choose the Import Data Wizard. In a few steps, you’ll see a dialog box much like Excel’s Import Spreadsheet Wizard (see Figure C.2). FIGURE C.2 Use the Import Data Wizard to import geographic data from Excel.
NOTE
If you haven’t saved the Excel workbook before clicking the MapPoint Map button, Excel prompts you to do so before launching the Link Data Wizard.
4002appC.qxd 7/17/01 12:34 PM Page 855
MapPoint 2002
855
After you select the fields you want to include in your data set, click Finish and MapPoint begins importing the data. Data is mapped at the most discrete level. If your data set includes street addresses, MapPoint will attempt to map each address. You’re allowed to either provide matches for addresses that aren’t in the MapPoint data (in our experience, about 3–4 percent of a relatively clean data set) or skip the records that can’t be matched.
PART
VIII Appendices
When all the records have been identified or skipped, MapPoint prompts you to select the map style:
Choose a column to map, and a summation method (count, sum, average), and MapPoint aggregates the data and creates the map. The map in Figure C.3 summarizes a 1,100-record Excel database of retail outlets so you can easily compare the number of outlets in each state—the darker the shading, the greater the number of retail outlets
4002appC.qxd 7/17/01 12:34 PM Page 856
856
APPENDIX C • Using MapPoint 2002 with Excel 2002
FIGURE C.3 This map of an Excel database shows the distribution of retail outlets by state.
Exporting Data to Excel Choose Data Export to Excel in MapPoint, and the summarized mapped data is exported to an Excel workbook. The data in Figure C.4 was exported from the map in Figure C.4. FIGURE C.4 Export to Excel sends the summarized map data to an Excel workbook.
4002appC.qxd 7/17/01 12:34 PM Page 857
MapPoint 2002
857
To copy a map to Excel, choose Edit Copy Map and paste the map in Excel as a bitmap.
Integration with Excel When MapPoint is installed, a MapPoint button is added to Excel’s Standard toolbar. Select geographic data and click the button to create a MapPoint map: just like you used to do with Data Map, but with better results. MapPoint walks you through the Link Data Wizard as described earlier in this chapter. There’s not a lot of data in the worksheet shown in Figure C.5: just two cities. If you select this data and insert a MapPoint map, and you can do the following: • Calculate the distance between the two points “as the crow flies.” • Show nearby hotels, motels, airports, and attractions. • Generate driving directions between the two points, as shown in Figure C.5.
PART
Appendices
VIII FIGURE C.5 MapPoint generates driving directions for any route.
4002appC.qxd 7/17/01 12:34 PM Page 858
858
APPENDIX C • Using MapPoint 2002 with Excel 2002
To generate driving directions between the identified points, choose Route Route Planner, click each point on the map and click Add to Route.
TIP
MapPoint also installs smart tag recognizers for geographic column names such as city, state, and zip code.
For more information on MapPoint, visit the Microsoft website for tutorials and tours. Better yet, order the 60-day, full-feature demo and spend some time with MapPoint and Excel.
NOTE
You can order the full-featured, 60-day MapPoint demo CDs from the Microsoft site at www.microsoft.com/office/mappoint/evaluation/trial.htm.
4002appD.qxd 7/19/01 3:23 PM Page 859
APPENDIX
D
CREATING SIMPLE SMART TAGS FOR EXCEL 2002
4002appD.qxd 7/19/01 3:23 PM Page 860
xcel ships with two smart tag recognizers: MSN MoneyCentral Financial Symbols and the recognizer for people’s names. You can create your own smart tags and extend the functionality of Excel 2002. Smart tags can return information from a database or from the Web and automate other applications to provide up-to-the minute information from a database or website, or they can open a pre-addressed message form.
e
NOTE
See Chapter 18, “Using Excel 2002 with the Web,” for information on using smart tags.
There are two broad types of smart tags, which Tina Turner would probably classify as “nice” and “rough.” The rough kind of smart tag is stored in a dynamic link library (DLL) and requires an intermediate level of programming skill to create. The “nice” smart tags don’t need DLLs. They rely on the MOFL.DLL that is included with Office and are created as XML documents stored in a specific folder: C:\Program Files\ Common Files\Microsoft Shared\Smart Tag\Lists\. Any XML document in the Lists folder is a smart tag list, so you can create smart tags by copying and modifying an existing file or by creating an XML document from scratch. Simple smart tags open URLs. In this appendix, we’re going to focus on creating simple smart tags. If you’re not a programmer (or if you are, but want to find out how to create simple smart tags quickly and easily) then stick around—this appendix is for you.
Tools for Creating Smart Tags
www
There are free tools for creating smart tags. You can download the free SmartTag SDK (software development kit) from the Microsoft website. The SDK, including the SDK help file, is meant for software developers. Microsoft was criticized because the Smart Tag SDK did not include a simple tool for creating XML lists. If you were underimpressed with the Smart Tag SDK, you weren’t alone. Chris Kunicki, an Office developer, created an Excel template to create XML smart tag lists. The SmartTagMOSTLGenerator (which Chris also calls “smart tags for wimps”) is one of the three tools of the advanced smart tag development tools on the Office Developer’s site. Download the tools and documentation from www.microsoft.com/OfficeDev/XP_06_2001/odc_stadvtools.htm.
4002appD.qxd 7/19/01 3:23 PM Page 861
Tools for Creating Smart Tags
861
NOTE
The most widely used smart tag tool is on your computer already: Notepad. Most XML files are created in Notepad or another plain text editor.
In the next two sections, we’ll look at a smart tag list file that was created in Notepad, and then we’ll create the same file using the SmartTagMOSTLGenerator.
The Smart Tag Schema The XML file includes required elements and optional elements. The elements are listed in order of appearance in the following section: A friendly name for the recognizer; required.
lcid Comma-separated list of languages that the smart tag will be recognized in; if omitted the value is 0 (all languages). U.S. English is 1033. description moreinfourl
Description of the smart tag for internal documentation; optional. URL for more information on the smart tag or recognizer; optional.
smarttag type The smarttag element has a required type attribute that defines a unique namespace for this smart tag. caption Title for the Smart Tag Options Menu; optional, but if omitted, the default is used. terms A collection that serves as the parent element for a termfile or termlist; required. termfile Binary file that contains terms; either termfile or termlist is required. If both are specified, termlist is used. termlist
Comma-separated list of terms; either termfile or termlist is required.
actions
The collection that serves as the parent element for action; required.
action id The action element has a required attribute, id, which is a unique string that identifies the action. url The url activates when the user chooses the action; the url supports two tokens, {TEXT}, the recognized document text, and {LCID}, the user’s language; required. caption The action caption for the smart tag option button menu; if omitted, the default caption is used.
PART
VIII Appendices
name
4002appD.qxd 7/19/01 3:23 PM Page 862
862
APPENDIX D • Creating Simple Smart Tags for Excel 2002
Creating the List File in Notepad For our illustration, we’re going to create smart tags with a simple purpose: recognizing and providing basic information on Women’s National Basketball Association (WNBA) teams. The smart tag will have three actions: • Display the team’s website in a browser • Display the summary statistics for all teams • Display the team’s schedule Figure D.1 shows the smart tag being used in a Word document. FIGURE D.1 The WNBA smart tag has three actions.
A smart tag list file is a well-formed XML file. Our file, WNBA.XML, is available for download from the Sybex website, or you can enter yourself it in Notepad. WNBA Team Lookup Retrieves team information from WNBA.com http://www.triadconsulting.com/smarttags.html WNBA Team Comets,Sting,Sparks,Rockers,Lynx,Shock,Mercury,Fever,Fire,Sol,M onarchs,Liberty,Storm,Miracle,Starzz,Mystics Lookup Team Site
4002appD.qxd 7/19/01 3:23 PM Page 863
Creating the List File in Notepad
863
http://www.Wnba.com/{TEXT}/ View Standings http://www.wnba.com/score_stat/standings.html Team Schedule http://www.wnba.com/{TEXT}/schedule.html
The first four lines of the file declare the namespace for the XML file and provide the smart tag list’s name and documentation. The first line of the file identifies an XML namespace that serves as the reference for smart tags: urn:schemas-microsoft-com: smarttags:list. FL refers to this namespace, so every start tag that begins with FL: is referencing the smart tag namespace. You can refer to a different namespace rather than FL if you prefer. You can use any other short abbreviation to refer to the namespace. The namespace declaration must be the first line of your smart tag list file:
Every element in this XML file has a start tag and an end tag. For example, the second line identifies the name of the smart tag application. The name is simply a descriptive text string. The start tag, , precedes the name. The name is followed by an end tag, which looks exactly like the start tag with one exception: it starts with a slash symbol. WNBA Team Lookup
XML files are hierarchies, so the end tag for the first line is the last line in the file. All of the elements in the file are included in (child elements of) the smarttaglist element.
NOTE
Unlike HTML, XML does not allow you to omit end tags.
PART
VIII Appendices
Namespace, Name, and Description
4002appD.qxd 7/19/01 3:23 PM Page 864
864
APPENDIX D • Creating Simple Smart Tags for Excel 2002
Names of elements (like name in the second line of the file) can be uppercase or lowercase, but the case must be consistent. If it’s uppercase in the start tag, it must be uppercase in the end tag. The third and fourth lines are documentation—a description of the smart tag list and a URL for more information about the smart tag. Retrieves team information from WNBA.com http://www.triadconsulting.com/smarttags.html
The meat of the file begins with the fifth and sixth lines. The fifth line creates the smarttag element with the required attribute type, used to define a unique namespace for the smart tag. The caption element in the sixth line provides the text for the top of the smart tag options menu. WNBA Team
Creating the Recognizer Lines 7 though 9 define the terms that Excel will recognize as WNBA teams. Line 7 creates a terms element. The termlist element is a child of terms. Individual items in the termlist—the names of the 16 WNBA teams—are separated with commas. Line 9 is the end tag for the terms element: Comets,Sting,Sparks,Rockers,Lynx,Shock,Mercury,Fever,Fire, Sol,Monarchs,Liberty,Storm,Miracle,Starzz,Mystics
Creating the Actions The next section of XML, the actions, describes the actions associated with this list of terms. First, we declare an actions element:
4002appD.qxd 7/19/01 3:23 PM Page 865
Creating the List File in Notepad
865
Each action has a unique id attribute. The first action, WNBALookup, is captioned Lookup Team Site on the smart tag options menu: Lookup Team Site The action opens a URL. The token {TEXT} is the text that the user entered from the term list. The token is replaced with the actual text (and spaces stripped out if needed), so if the user enters Comets (the team in Houston), the default browser opens and displays http://www.wnba.com/comets/, the home page for the Houston Comets. This is the end of the action, so the url is followed by the action’s end tag. http://www.Wnba.com/{TEXT}/
The second action uses no variable and is the same for every team: View Standings http://www.wnba.com/score_stat/standings.html
The third and final action displays the team’s schedule, using the {TEXT} token to navigate to the correct page. The actions end tag closes the section: Team Schedule http://www.wnba.com/{TEXT}/schedule.html
With the terms and actions completed, the last two lines close the smarttag and smarttaglist elements:
Saving the File Save the file in the smart tags list folder: C:\Program Files\Common Files\Microsoft Shared\Smart Tag\Lists. If you created the file in Notepad, put the filename in quotes—“WNBA.XML”—to prevent Notepad from adding a TXT extension. Smart tags are loaded when an application launches, so if Excel is open, close it and launch it again. Choose Tools AutoCorrect Options to open the AutoCorrect dialog box. On the Smart Tags tab, make sure the Label Data with Smart Tags check box is enabled and that Smart Tags Lists is enabled in the Recognizers list.
PART
VIII Appendices
4002appD.qxd 7/19/01 3:23 PM Page 866
866
APPENDIX D • Creating Simple Smart Tags for Excel 2002
NOTE
Why did we choose WNBA teams for this example? We’re fans, for sure, but we were also looking for an Internet site with a symmetrical structure, with multiple folders with human language names at the same level for parallel items such as the team folders on wnba.com. If you’re creating a website, pay attention to the structure and symmetry; it makes all kinds of automation, including smart tags, easier to implement. Go Detroit Shock!
Creating the File Using SmartTagMOSTLGenerator The SmartTagMOSTLGenerator (Smart Tag Microsoft Office Smart Tag List Generator, hereafter referred to as “the generator”) is an Excel template that creates well-formed XML list files and saves them in the /Smart Tags/Lists folder. Download the generator and the other advanced smart tag development tools from the Microsoft website. The download is a zipped application file that you have to extract. It’s helpful to extract to a new folder so you can easily find the new files. When you open the generator, you must enable the macros. The generator includes four worksheets. The first worksheet explains the generator, and the last is the XSL file used to transform the input from the second and third sheets into an XML list file. The second sheet, SmartTagDetails, is shown in Figure D.2. FIGURE D.2 Fill in the data in the generator and click EXPORT MOSTL XML to generate the file.
4002appD.qxd 7/19/01 3:23 PM Page 867
Creating the File Using SmartTagMOSTLGenerator
867
The generator uses named ranges to create the file. The named range for terms includes nearly 2,000 cells; actions are a three-row range. If you have more than 1,990 terms or insert rows for additional actions, open the Define Name dialog box (Insert Name Define) and verify or edit the ranges for the following names: • actioncaption • actionid • actions • actionurl • term To create the XML file, enter values for each of the MOSTL properties. When you have finished, click the EXPORT MOSTL XML button to create the file.
PART
Appendices
VIII
40012ndex.qxd 7/27/01 11:01 AM Page 868
INDEX Note to the reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations.
Symbols & Numbers & (ampersand) for concatenation, 178 for keyboard accelerator, 661 ###### error, 159 #DIV/0 error, 159, 160 #N/A error, 159, 206 handling, 214 #NAME error, 159 #NULL error, 160 #NUM error, 160 #REF error, 160 #VALUE error, 160, 179 $ (dollar sign) for absolute cell references, 155 ‘ (apostrophe) for comments, 652, 792 ( ) (parentheses) for functions, 690 * (asterisk) as Find and Replace wildcard, 51 = (equal sign) to begin formula, 54 to begin function, 148 ? (question mark), as Find and Replace wildcard, 51 / (slash), 117 3-D View dialog box, 261, 261 3D area chart, 267, 268 3D effect, for drawing objects, 307–309 3D name, 130 3D pivot analysis with OLAP, 512–522 3D views in charts, 260–261 16-bit ODBC drivers, 493 32-bit ODBC drivers, 493 100 percent stacked area chart, 268, 268, 271
A Abs function (VBA), 800 absolute cell reference, 155–156 in macros, 647
absolute URL, 140 Access converting Excel worksheet to database, 486–489 copying data from Excel to, 484–485 vs. Excel for databases, 343–345 forms for Excel database, 367 templates linking worksheet cells to fields, 477 using forms and reports in Excel, 489–490 working with Excel and, 483–490 accessibility options, 14 AccessLinks add-in, 477, 484 accounting, formatting for, 65 accuracy in model, 588–591 Activate event (VBA), 829, 834–835 active cell, 44, 44 scrolling and, 45 ActiveSheet property of Worksheet object, 824 ActiveWorkbook property of Workbook object, 822 ActiveX controls, 454–455 vs. form controls, 457 Add Custom Chart Type dialog box, 282, 282–283 add-ins removing unused, 483 user-defined functions as, 705–706 Add-Ins dialog box, 706 Add Network Place Wizard, 553 Add Procedure dialog box, 697 Add Scenario dialog box, 603 Add Watch dialog box, 711 AddinInstall event (VBA), 829, 835–836 AddinUninstall event (VBA), 829, 835–836 Advanced Filter dialog box, 357 Advanced Search task pane, 12–13, 13 AfterRefresh event (VBA), 829, 845 alignment of command buttons, 462–463 of controls, 735
40012ndex.qxd 7/27/01 11:01 AM Page 869
alignment of text • AVERAGE function
of drawing objects, 310 of flowchart objects, 300 alignment of text, 89–93 direction of text, 93 horizontal and vertical, 91 indent, 92 merge, shrink to fit, wrap, 92–93 rotating text, 91–92 Allow Users to Edit Ranges dialog box, 438 amortization table, 222–227, 223 modified, 225, 225–227 ampersand (&) for concatenation, 178 for keyboard accelerator, 661 Analysis Toolpack, 148 installing, 187–188 analysis tools data tables, 584, 584–587 with two variables, 586, 586–587 forecasting and modeling, 587–591 accuracy in model, 588–591 assumptions, 588 Goal Seek, 592–593 reports, 609–610 Scenarios, 603–607 merging, 604–606 summarizing, 606–607 Solver, 594–603 Evaluate Formula feature, 596–598 with multiple variables, 598–602 saving models, 602–603 views, 608–609 AND in filter criteria, 353, 355 IF functions with, 202 for parameter query, 510 in VBA, 807 animations, 321 during editing, 771 of Excel charts, 539 annuity future value, 230–232 Answer Wizard, 719, 720 anti-virus software, 649 apostrophe (‘) for comments, 652, 792 applets, 670 application errors, 714 Application object in Excel object model, 652, 821 creating, 726 special requirements, 832–833
area charts, 244, 264, 266 creating, 265–269 arguments for functions, 152–153 arguments for VBA methods, 795 arithmetic mean, 157 arithmetic operators, in VBA, 806 Arrange Windows dialog box, 134 arranging drawing objects, 309–310 array data type (VBA), 798 array formulas, 379–382 arrows, 301 styles, 307 Asc function (VBA), 800, 801 ascending sort order, 346 Ask a Question, 20–21, 42, 43 Assign Hyperlink: Insert Picture dialog box, 663, 663 Assign Hyperlink: Open dialog box, 663 Assign Macro dialog box, 460, 460, 662, 662 assumptions in forecasting, 588 Attach Toolbars dialog box, 666 AutoComplete, 47, 771 AutoCorrect, 116–117 reversing or disabling, 25 settings, 780–782 AutoCorrect dialog box, 780 AutoCorrect tab, 116 Smart Tags tab, 144, 782 AutoFill, 60–62 custom lists for, 775–776 Options menu, 60 AutoFill Options button, 23 AutoFilter, 349–354 AutoFormat dialog box, 98, 99 for pivot tables, 411, 412 Automatic Language Detection, 116 automation. See Visual Basic for Applications AutoNumber fields in Access, 484 AutoOutline, 388, 391 AutoRecover, 776 AutoShapes, 297–298, 298 changing, 307 Curve objects, 298–299 for flowcharts, 299–300, 300 FreeForm objects, 298–299 Line art objects, 300–303 Scribble objects, 298–299 AVERAGE function, 56, 156, 157
869
40012ndex.qxd 7/27/01 11:01 AM Page 870
870
axes on chart • cell entries
axes on chart, 245 adding second, 283–284, 285 time-scale, 278
buttons. See also Command buttons creating, 661 byte data type (VBA), 798
B
C
background error checking, 163 backups, 787 bar charts, 244–246, 245, 246 basCalcHolidays function, 755–756 basCalcVacation function, 752–754 basCountWeekends function, 756 base field, in custom calculation for pivot table, 419 base item, in custom calculation for pivot table, 419 Basic Search task pane, 11, 11–14 basYrsService function, 756 BeforeClose event (VBA), 822, 829, 838 BeforeDoubleClick event (VBA), 829, 839–841 BeforePrint event (VBA), 822, 829, 845–846 BeforeRefresh event (VBA), 829, 845 BeforeRightClick event (VBA), 829, 839–841 BeforeSave event (VBA), 830, 846–847 black and white printing, 82 blank lines in VBA, 792–793 blue underscore for corrections, 25 for hyperlinks, 23 boolean data type (VBA), 798 Boolean values, functions to return, 215 Border object, 827 borders for graphics, 331 for templates, 433 for text, 94–96 branching, conditional in VBA, 815–819 breakpoint clearing, 712 in programming code, 707 brightness for graphics, 331 BringToFront method of ChartObject object, 828 broken links from moving files, 535 bubble charts, 264, 273, 273–274 displaying source data with, 292 Buddhist calendar, 72 bugs in programming, 678 building application, 678 business rules for data validation, 382–385 Button form control, 458
.cab file extension, 728 cabinet files, creating, 728 CalcRetirement subroutine, 749–750 Calculate event (VBA), 830, 836–837 Calculate method of Worksheet object, 825 calculated fields in pivot tables, 420–421, 422 calculations. See formulas calendars, 72 call in VBA, 808 Call stack, 710 callout AutoShapes, 298 camera importing clips from, 326 inserting graphics from, 335–336 Camera in Excel, 575–577 Cancel command button, code for, 738 canceling data entry, 46 capitalization AutoCorrect for, 781 in VBA variable names, 801 Caption property of UserForm, 687 captions for clips, 324 Cartesian charts, 272, 273 case of text, function to change, 174 case sensitivity of Excel sort, 347 of filter criteria, 358 Visual Basic and, 645 Cbool function (VBA), 800, 801 Cbyte function (VBA), 800 Cdate function (VBA), 800 CDbl function (VBA), 800 CEILING function, 234 cell address, 44 cell entries AutoComplete, 47 deleting contents, 48–49 entering and editing, 42–52 filling formulas, numbers and dates, 53–62 AutoFill, 60–62 Find and Replace, 50–52 moving and copying, 106–109
40012ndex.qxd 7/27/01 11:01 AM Page 871
cell pointer • CLng function (VBA)
numbers, 52–59 formatting, 62–73 formulas, 53–59 Pick From List, 48 revisions, 48 selecting multiple cells, 49–50 text and numbers, 46–49 cell pointer, 44, 44 moving, 45–46 cell references in conditions for formatting, 373–374 in macros, 647 cells in worksheet, 44, 44. See also range of cells camera to capture data image, 575–577 finding conditional formatting, 378–379 formula references to, 58 inserting and deleting, 106 Locked property of, 436 mixed cell references, 156 relative and absolute references, 153–156 selecting multiple, 49–50 unlocking, 437 Cells property of Worksheet object, 824 centering text in cell, 90 worksheet on printed page, 78 Change event (VBA), 830, 837 change history for shared workbook, 620 highlighting changes, 619 and merging workbook copies, 622 tracking, 618 chart area, 254, 255 Chart component, 557, 565–566, 566 Chart menu, 3-D view, 261 Chart object in Excel object model, 825–828 Chart Options dialog box, Titles tab, 284 chart sheets, controls for, 455 ChartArea object, 826 ChartObject objects, 827–828 special requirements, 832–833 charts adding second axis, 283–284, 285 creating, 246–252 with Chart Wizard, 248–252, 248–252, 280 data selection, 247, 247–248 editing and formatting, 252–261 3D views, 260–261 adding data series, 253–254 with Chart Toolbar, 255–256
deleting data series, 254 exploding pies, 259–260 individual objects, 256–258 moving, sizing and printing, 252–253 resizing and deleting objects, 254–255 titles, 258–259 fill and line colors, 288–289 custom fills, 289–291, 290 options, 285–288 displaying tips, 288 plotting hidden cells, 287 plotting missing values, 286, 286–287 sizing, 288 pictures of data, 291–293 reversing series and category order, 269 setting default, 282–283 storing, 293 tip display, 271, 288 types, 264–265 bubble charts, 273, 273–274 column and bar charts, 244–246, 245, 246 combination charts, 279–281, 281 creating and saving, 282–283 donut charts, 270–272, 271 line, ribbon, area charts, 244, 244, 265–269 pie charts, 243, 243 radar charts, 275, 275–277, 276 scatter charts, 272, 273 series charts, 243–246 stock charts, 277–278, 278 surface charts, 270, 270 value of, 242 ChartType property of Chart object, 826 ChartWizard method, 827 check box controls, 453, 458, 471–472 child objects, 819 Choose Data Source dialog box, Databases tab, 499 Chr function (VBA), 800 CInt function (VBA), 800 circle, 301 circular references, troubleshooting, 166–167 class modules, 681 CLEAN function, 171 Clip Art Gallery. See Microsoft Clip Organizer clip art, searching in Excel for, 13–14 Clipboard, 9–10, 10, 107–108 to copy formatting, 179 Clippit, 20 CLng function (VBA), 800
871
40012ndex.qxd 7/27/01 11:01 AM Page 872
872
closing • constants
closing Excel 2002, 40 task panes, 7 workbooks, 40 Code Editor window in VB IDE, 689, 689 collaboration, 26. See also SharePoint Team Services; workgroups virtual meetings, 638–640 collections in VBA, 794 collections of clips, 320–321 based on projects, 325 creating, 322–323 color for border, 94 for charts, 288–289 for conditional formatting, 372 in custom format, 71 for drawing objects, 306 for errors, 163 for graphics, 331 for templates, 433 for text, 94–96 for worksheet tab, 120 column charts, 244–246 Column Width dialog box, 102 columns in worksheets, 44, 44 ###### error and, 159 arranging for outlining, 392–393 blank to designate database end, 341 freezing, 104 hiding, 105 inserting and deleting, 103–104 painting widths, 97 printing letters for, 82 problems from blank, 102 repeating on printout pages, 81 selecting, 49 summarizing, 57 testing for empty, 103 transposing to rows, 112, 112 width, 101–102 combination charts, 279–281, 281 Combination controls, 459 combo box controls, 453, 458, 467–468 vs. data validation, 468–469 vs. list boxes, 464 properties, 465
command bars customizing, 657–667 docking, 763 Command buttons, 453, 459–463 moving and sizing, 461 properties, 461–463 CommandBar object, 762 CommandButton control (VBA) adding to UserForm, 684, 685 properties, 688 in Retirement Countdown application, 737, 737 Commands and Options dialog box, Format tab, 561 comments indicator, 769 in macros, 652 printing, 82 in templates, 430, 433 in VBA, 792–793 in worksheets for forecasting, 590 comparison operators in VBA, 806, 807 “Compile Error: Method or Data member not found”, 692 compiling, 678, 692, 710 complex formulas, 55–56 compound interest, 227, 228–230 compressing graphic files, 331 CONCATENATE function, 178, 178–179 concatenation operators in VBA, 806, 807 conceptual diagrams, 315–316 conditional branching, 815–819 conditional expressions in formulas, 186 conditional formatting cell references in conditions, 373–374 with custom formats, 71 for database records, 370–379 deleting, 373 finding cells containing, 378–379 formulas as conditions, 374–378, 375 with formulas including functions, 377–378 Conditional Formatting dialog box, 371 with formula, 375 multiple conditions, 372–373, 373 Conditional Sum Wizard, 379, 379–385, 380, 381 Confirm Password dialog box, 436 consolidation of worksheets, 416–419 consolidation ranges, pivot table creation from, 413–417 constants names to store, 132–133 in VBA, 795–796
40012ndex.qxd 7/27/01 11:01 AM Page 873
constants worksheet • Data menu
constants worksheet, 751 constraints for Goal Seek, 598–599 for Solver, 600 contrast for graphics, 331 Control Panel (Windows), Regional Options, 67 controls, 453, 671 adding to UserForm, 683–686, 733–737 sizing and aligning, 735 to close window, 674 creating, 671–672 properties, 672, 686–688 in Retirement Countdown application, 733–737 sizing, 684, 686 Convert Text to Columns Wizard, 176–177, 177 converting objects, 525–529 copy and paste, 23–25, 107–108 to convert data, 525, 526 paste options, 24, 527 Copy method of Chart object, 827 copying cell contents, 106–109 clips to collections, 322 data from Excel to Access, 484–485 database subtotals, 363–364 filling formulas, numbers and dates, 59–62 maps to Excel from MapPoint, 857 with Paste Special, 110 styles between workbooks, 100–101 worksheets, 122–123 COUNT function, 56, 156 Count Weekends user-defined function, 700–702 COUNTA function, 156 COUNTBLANK function, 158 COUNTIF function, 202, 203–204 crash of system, minimizing, 38–40 Create Names dialog box, 127 Create New Data Source dialog box, 500 default table in, 501 for OLAP, 515 CreateObject function, 726 criteria range for filter, 354 cropping graphics, 331 cross join, 506 cross-tab reports, 412. See also pivot tables CSng function (VBA), 800 CStr function (VBA), 800 .cub file extension, 520
currency formatting, 65 symbols in custom format, 71 currency data type (VBA), 798 current date and time, 189 Curve objects, 298–299 Custom AutoFilter dialog box, 352 custom charts, saving settings, 282–283 custom dictionaries, modifying, 115 custom formats for numbers, 68–73 Custom Views dialog box, 608, 609 Customize dialog box Commands tab, 453, 576, 577, 658 Modify Selection shortcut menu, 660, 661 Toolbars tab, 453, 665 customizing. See also Options dialog box Places bar, 18–19 toolbars, 14–16 Cut and paste, 107 Cycle diagrams, 312
D dash style for drawing objects, 306 data new features, 5 selecting for chart creation, 247, 247–248 Data Connection Wizard, 497 data entry, 46 common data in multiple worksheets, 121–122 data integrity, Excel vs. Access, 344 Data Link Properties dialog box, Provider tab, 497 Data Map applet, 852 Data menu Filter AutoFilter, 349, 353 Show All, 350 Form, 365 Group and Outline Auto Outline, 391 Clear Outline, 362 Group, 394 Settings, 393 Ungroup, 394 Import External Data Edit Query, 505 Import Data, 412, 491, 494 New Database Query, 498, 499, 516 New Web Query, 574
873
40012ndex.qxd 7/27/01 11:01 AM Page 874
874
data points on charts • default settings
MS Access Form, 489 PivotTable and Pivotchart Report, 399 Refresh Data, 417, 495, 550 Sort, 345 Text to Columns, 176 Validation, 382 data points on charts, 242 data series on charts, 242 adding, 253–254 deleting, 254 Data Sort dialog box, 347 Data Source component, 557 data sources, 492–493 creating, 496–498 for OLAP, 514–516 limiting access, 501 for Microsoft Query selecting existing, 499 setup for new, 500, 500–501 using existing, 494–495 data tables, 584, 584–587 displaying with chart, 291, 291–293, 292 with two variables, 586, 586–587 Data Validation dialog box, 382 Error Alert tab, 384 Input Message tab, 384 Settings tab, 382, 469 database functions, 149, 367–370, 368 databases application choices, 343–345 basic concepts, 340–345 conditional formatting, 370–379 consolidation to combine data into pivot table, 413–417 converting Excel worksheet to Access, 486–489 creating, 341–342 data forms, 365, 365–367 adding and deleting records, 366 to search for records, 366–367 in Excel, sorting, 345–348 filtering, 349–360, 350 with Advanced filters, 354–360 with AutoFilter, 349–354 pivot table analysis, 398 relationships between tables, 506, 507 subset, 353–354 advanced filters to extract, 354–360 subtotals, 360–364
templates linking worksheet cells to fields, 477–483 validation, 382–385 date data type (VBA), 798 DATE function, 186, 188–189, 189, 195 DATEDIF function, 190 dates and times basic math, 183–186 addition, 190 subtraction, 185–186 calculations, 181 conditional formatting, 378 converting text to, 179 Ctrl+; to enter current, 108 determining weekday for date, 194–195 filling, 59–62 formatting, 65–66 customizing, 71–72 forms recognized by Excel, 181, 181–182 functions, 149, 180–195 to create dates, 188–189, 189 to exclude weekends and holidays, 191–194 to retrieve current, 189 interpretation of, 67 storing, 182–183 Text to Speech and, 35 times decimal values, 184 entry, 182 DateSerial function (VBA), 800, 801 DATEVALUE function, 179 DateValue function (VBA), 741, 743, 800 DAVERAGE function, 369 DAY function, 187 day of year dates, 179–180 calculations, 195 DB function, 233 dBASE, templates linking worksheet cells to fields, 477 DCOUNT function, 369 DCOUNTA function, 369 DDB function, 233 Deactivate event (VBA), 830, 834–835 Debug menu (VBA), Compile VBA Project, 692 debugging in Visual Basic IDE, 707–712, 708 decimal data type (VBA), 798 default settings, 773 for chart type, 282–283 for charts, 269
40012ndex.qxd 7/27/01 11:01 AM Page 875
default template • drawings
for column width, 102 for formatting, 63 margins, 75 for text alignment, 89 default template, 428 Define Name dialog box, 126, 126–127 Delete method of Worksheet object, 825 deleting cell contents, 48–49 cells in worksheet, 106 chart objects, 254–255 clip from Clip Organizer, 326 conditional formatting, 373 custom formats, 70 data series on charts, 254 with Find and Replace, 52 items from menus or toolbars, 657 macros, 648–649 manual page breaks, 85 name for cell range, 126 records in data form, 366 rows and columns in worksheet, 103–104 styles, 100 text box, 303 UserForms, 683 watch, 165 worksheets, 123–124 delimited text files, parsing, 547 dependent cells, 165 dependent workbooks, for links, 134 depreciation functions, 232–233 descending sort order, 346 Design Gallery Live, finding new clips on, 327–329, 328 Design mode, 707 Dfunctions, 367–370, 368 DGET function, 369, 370 Diagram Gallery, 312, 312 Diagram toolbar, 316 diagrams, 312–316 .dic file extension, 779 dictating, 30 dictionary for Office XP applications, 115 for spell check, 779 digital dashboard, 569 digital photos, 335–336 digital signature, 784 for macros, 448
Dim statement, 801 dimensions in OLAP cube, 513, 518, 519 drilling down, 521–522 direction of text, 93 disabling AutoCorrect, 25 discussions about shared documents, 633–634 DisplayOutput subroutine, 756–762 Distributed alignment, 91 distribution list, for routing workbook, 615 Divide by Zero error, 159 handling, 214 DLLs (dynamic link libraries), 714 DMAX function, 369 DMIN function, 369 Do... loops, 810–813 Do... Loop Until loop, 813 Do... Loop While loops, 811–812 Do Until... Loop, 812–813 Do While... Loop, 810–811 docking custom command bars, 763 document element in XML, 570 Document Recovery task pane, 19, 19–20 documentation of protection information, 439 in VBA, 792–793 dollar sign ($) for absolute cell references, 155 donut charts, 264, 270–272, 271 dots per inch (dpi), 77 double-clicking, 839 double data type (VBA), 798 double declining balance depreciation, 233 downloading clips, 329 Template Wizard with Data Tracking add-in, 478 templates, 429 dpi (dots per inch), 77 DPRODUCT function, 369 draft quality, 82 drag and drop to copy and paste, 109 to fill cells, 59 DragOver event (VBA), 830, 838 DragPlot event (VBA), 830, 838 Drawing Pad, 35, 36 Drawing toolbar, 296, 296 Insert Clip Art button, 13, 317 Insert WordArt button, 303 Text Box button, 302 drawings. See graphics
875
40012ndex.qxd 7/27/01 11:01 AM Page 876
876
drilling down in pivot tables • Excel 2002
drilling down in pivot tables, 423–424 DSTDEV function, 369 DSTDEVP function, 369 DSUM function, 369 Duplicate method of ChartObject object, 828 DVAR function, 369 DVARP function, 369 dynamic link libraries (DLLs), 714
E e-mail, hyperlinks for, 141–142, 142, 663 e-mailing workbooks, 612–613, 613 Easter eggs, 22 Edit box form control, 458 Edit Links dialog box, 136, 136 Edit menu Clear, 49 Copy, 107 Cut, 107 Delete Sheet, 123 Fill, 60 Series, 61 Fill Across Worksheets, 121 Find, 50 Go To, 364 Links, 136 Move or Copy Sheet, 122 Office Clipboard, 107 Paste as Hyperlink, 530 Paste Special, 22, 529 Paste Link, 135 Replace, 50 Edit Ranges feature, 437–441 Edit Report dialog box, 610 Edit Watch dialog box, 711, 712 Edit WordArt Text dialog box, 304 editing, options for, 770–771 Elcomsoft, 436 elevation for 3-D chart, 261 ElseIf statement, 817 embedded objects, 525, 529–530, 530 working with, 532 in worksheets, 531–532 empty string, 224 End Function statement, 804 End Select statement, 818 End Sub statement, 653, 793, 804
engineering functions, 149 equal sign (=) to begin function, 148 Eqv operator in VBA, 807 Error Checking dialog box, 162 error codes, 159–161 error messages code for generating, 743–747 hiding when printing, 82 for invalid data input, 384, 384 from simultaneous edits of shared document, 632 Error Options button, 160 error report, sending to Microsoft, 39 errors checking worksheets for, 777–779 green triangle indicator for, 23 trapping with logical functions, 214–215 in typing, AutoCorrect, 116–117 Eurodata, 549 Evaluate Formula dialog box, 161, 596–598 EVEN function, 234 event-driven language, Visual Basic as, 675–676 events in VBA, 671, 828–832 Activate and Deactivate, 834–835 AddinInstall and AddinUninstall, 835–836 AfterRefresh and BeforeRefresh, 845 BeforeClose, 838 BeforeDoubleClick and BeforeRIghtClick, 839–841 BeforePrint, 845–846 BeforeSave, 846–847 Calculate, 836–837 Change, 837 DragOver and DragPlot, 838 FollowHyperlink, 841 MouseDown, MouseMove, and MouseUp, 842 NewSheet and NewWorkbook, 842–843 Open, 843 PivotTable, 843–845 SelectionChange and SeriesChange, 847–848 Windows, 848–849 Excel 5.0 form controls, 458 Excel 2002 and Access, 483–490 application window, 42–43, 43 moving cell pointer, 45–46 closing, 40 converting worksheet to Access database, 486–489
40012ndex.qxd 7/27/01 11:01 AM Page 877
Excel application • File menu
copying data to Access from, 484–485 for data conversion, 476 as database tool, 343–345 and external data Microsoft Query to retrieve, 498–512 Query results, 508–512 setting data range properties, 511–512 HTML support, 556 importing data, 491–498 from MapPoint, 856–857 from other applications, 545–550 from Outlook, 545 refreshable text importing, 549–550 integrating with other Office applications, 724–728 launching, 7 add-ins and, 483 display options, 769 MapPoint 2002 integration with, 857–858 new features, 4–6 for nonusers hiding title bar, 448 navigation buttons with hyperlinks, 446–447 turning off features, 445 programmability. See also Visual Basic for Applications (VBA) recovering from application error, 38–39 reliability features, 40 starting Web query in, 574 using Access forms and reports, 489–490 Visual Basic help file, 719–722 Web features, 552 Excel application, 716. See also Retirement Countdown application creating Application object, 726 Excel object model in VBA, 819–828, 820 Application object, 652, 821 creating, 726 special requirements, 832–833 Chart object, 825–828 displaying, 820 Sheets collection, 822–828 Workbook object, 821–822 Worksheet object, 823–825 Worksheets collection, 822–828 Exchange Server importing from, 491 and templates, 434
Exit Do statement, 813 Exit For statement, 809 exiting Excel 2002, 40 expanding menus, 15, 15 explicit declaration of VBA variables, 801–802 exploding pie charts, 259–260 exporting from Excel to Outlook, 541–544 holidays from Outlook, 192–194 from MapPoint 2002 to Excel, 856–857 from Outlook to Excel, 545 extended formulas and formats, 62 Extensible Markup Language (XML), 569–572 saving workbooks as, 571–572 for smart tag list file, 862–865 external data, importing, 545–550 External Data Range Properties dialog box, 511, 512 external data sources, pivot tables using, 412–413 External Data toolbar, 508, 508–509 external reference, 130 extracting data for file recovery, 786
F field buttons in PivotTable and PivotChart Wizard, 401, 402 fields changing for pivot table, 404–405 in database, 340 names, 342 Outlook vs. Excel, 544 File DSN, 501 File menu Add Clips to Organizer, 326 Close, 40 Exit, 40 New, 7 Open, 20, 434 for file recovery, 786 Page Setup, 76–82, 452 Print, 73 Print Area, Set Print Area, 81 Print Preview, 74 recently opened files, 434, 772 Save as Web Page, 555 Send To, 26 Exchange Folder, 627 Mail Recipient, 612
877
40012ndex.qxd 7/27/01 11:01 AM Page 878
878
“file not valid” error message • Format Cells dialog box
Mail Recipient for Review, 624 Next Routing Recipient, 616 Routing Recipient, 614 “file not valid” error message, 546 files. See also workbooks hyperlinks to, 140, 663 inserting, 532–534 manual recovery, 786–789 moving linked, 535 for program code, 681–682 removing user information from properties, 783 Fill alignment, 91 fill color, 94 for charts, 288–289 custom fills, 289–291, 290 for conditional formatting, 372 for drawing objects, 306 for templates, 433 Fill Effects dialog box, 289–291 Gradient tab, 290 Picture tab, 290 filling formulas, numbers and dates, 59–62 filtering databases, 340, 349–360, 350 with Advanced filters, 354–360 with AutoFilter, 349–354 criteria for text fields, 358 custom filters, 351–353 formula-based criteria, 359 for pivot tables, 405–406 financial functions, 149 amortization table, 222–227, 223 modified, 225, 225–227 depreciation functions, 232–233 future value calculation, 227–232 annuity future value, 230–232 compound interest, 228–230 simple interest, 228 interest rate calculation for loan, 222 loan payment calculation, 219–221 loan principal calculation, 222 loan term calculation, 221–222 for present and future value, 218–232 Find and Replace, 50–52 Find and Replace dialog box for formats, 51 Replace tab, 50, 50–51 Find Format dialog box, 51 Number tab, 51
FIND function, 174–175 finding. See also searching in Excel functions, 150 Fix function (VBA), 800 fixed declining balance depreciation, 233 fixed expenses in forecasting model, 589 fixed width files, parsing, 547 flat file database, Excel for, 343 FLOOR function, 234 flowcharts, AutoShapes for, 299–300, 300 focus, 834–835 folders, adding to Places bar for current projects, 18 FollowHyperlink event (VBA), 830, 841 Font property of Label control, 734 fonts color, 94 for drawing objects, 306 for command buttons, 462 shrinking size to fit cell, 93 for web pages, 775 footers, 78–80 For Each...Next loops, 809–810 For... Next loops, 808–809 forecasting and modeling, 587–591 accuracy in model, 588–591 assumptions, 588 form controls, 456, 456–457 adding to worksheets, 458–472 combo box controls, 467–468 Command buttons, 459–463 properties, 461–463 group boxes, option buttons, check boxes, 471–472 list controls, 464–468, 465 moving and sizing, 461 scroll bars and spinners, 469–470 Format AutoShape dialog box, Properties tab, 447, 447 Format Axis dialog box, 269 Scale tab, 269, 281 Format Cells dialog box, 64–73, 437 Alignment tab, 90, 92 Border tab, 94, 95 Font tab, 88, 89 Number tab, 64, 181 and ActiveX controls, 455 categories, 65 for custom formats, 69–70 Patterns tab, 96 Protection tab, 437
40012ndex.qxd 7/27/01 11:01 AM Page 879
Format Control dialog box • Formula bar
Format Control dialog box, 462–463, 667 Control tab, 466, 467 Font tab, 462 Properties tab, 667 Format Data Series dialog box, 257–258, 265 Axis tab, 283 Options tab, for bubble charts, 275 Patterns tab, 257, 289 Series Order tab, 266 Format menu AutoFormat, 98 Cells, 64, 88, 437 Column Hide, 105 Standard Width, 102 Width, 102 Conditional Formatting, 371, 374 Row AutoFit, 103 Hide, 105 Sheet Hide, 434 Tab Color, 120 Unhide, 435 Style, 98, 396 Format menu (VB) Align, Centers, 686 Make Same Size, Height, 686 Format Painter, 63, 97 to set column width, 102 Format Picture dialog box, 332–334 Size tab, 330, 333 Format Tab Color dialog box, 120 Format Text Box dialog box, 306 formatting AutoFormats, 98–101 charts, 254–260 with Chart toolbar, 255–256 individual objects, 256–258 resizing and deleting objects, 254–255 titles, 258–259 database cells, conditional, 370–379 drawing objects, 305–312 extended, 62 graphics, 332–334 including in paste, 108 with macros, 646 outlines, 395–396 pivot table options for, 410
styles applying, 100 copying between workbooks, 100–101 creating, 98–99 modifying and deleting, 100 worksheet layout, 101–113 column width and row height, 101–103 freezing, splitting and hiding, 104–105 grouping worksheets for, 121 hiding rows and columns, 105 inserting and deleting cells, 106 inserting and deleting rows and columns, 103–104 moving and copying cell contents, 106–109 zoom, 101 formatting numbers, 62–73 customizing, 68–73 dates and times, 65–66 fractions, 68 Special formats, 68 in strings, 178–179 Text formats, 68 formatting text, 88–97 alignment, 89–93 direction of text, 93 horizontal and vertical, 91 indent, 92 merge, shrink to fit, wrap, 92–93 rotating text, 91–92 borders and color, 94–96 fonts, 88 with Format Painter, 97 Formatting toolbar, 14, 43, 63–64 alignment buttons, 89 Fill Color button, 94 personalized, 659 forms from Access, in Excel, 489–490 creating printable, 450–453, 452 running macros from button, 667–668 types, 450 Forms toolbar, 458 Command Button button, 460 Formula Auditing toolbar, 161–165, 162, 385 to check validation, 385 Formula bar, 54 in application window, 42, 43 choosing function from, 151 Enter button, 46 fx button, 150
879
40012ndex.qxd 7/27/01 11:01 AM Page 880
880
formulas • geographic data
formulas, 46, 52 array, 379–382 automatic and manual calculation, 167–168 and cell formatting, 62 changing reference, 58 complex, 55–56 in conditional formatting, 374–378, 375 copying, 108 relative vs. absolute references in, 153–156 creating, 53–59 with data entry, 54 edit-free, 432 with point-and-click, 53–54 extended, 62 filling, 59–62 finding and fixing errors, 159–167 circular references, 166–167 error codes, 159–161 with Formula Auditing toolbar, 161–165, 162 logical errors, 159 tracing visually, 164, 164–165 with Watch window, 165, 165 hiding, 437 natural language, 55 order of operations in, 56 Paste Special to calculate without, 112 revising, 58–59 for totals, 56–57 viewing, 54 For...Next loops, 808–809 FoxPro, templates linking worksheet cells to fields, 477 fractions, formatting, 68 FreeForm objects, 298–299 freezing rows and columns in worksheet, 104 FTP site, download or upload, 552 full outer join, 506 Function Arguments dialog box, 152, 152–153, 173 for conditional formatting criteria, 377 for depreciation functions, 233 for PMT function, 220 for user-defined function, 704 Function keyword, 696 Function statement, 804 functions, 148–158. See also financial functions categories, 149 dates and times, 180–195 entering, 149, 150–153 entering arguments, 152–153
in formulas for conditional formatting, 377–378 IF functions, 198–204 with AND and OR, 202 summary IF, 202–204 to take action, 198–202, 199 information, 215 lookup functions, 204–214, 205 HLOOKUP, 207 LOOKUP, 208 Lookup Wizard, 210–214, 211, 212, 213 MATCH and INDEX, 209–210 vs. nested IF, 201 VLOOKUP, 206–207 MOD, 235–237 nesting, 172–173 QUOTIENT, 235–237 random number generation, 238 recently used, 151 for rounding, 234–235 selecting and finding, 150 statistical, 156–158 summarization, 56–57 syntax, 148 for text manipulation, 149, 170–179 to change case, 174 to convert to date, 179 copying results, 171–172 to determine length, 175 to find text position in cell, 174–175 parsing data, 172–174 putting strings together, 178–179 removing spaces, 170–171 user-defined, 696–702. See also user-defined functions volatile, 238 functions in VBA, 674, 804–805 data type conversion, 799–800 future value of money (Fv), 218, 219 calculation, 227–232 annuity future value, 230–232 compound interest, 228–230 simple interest, 228 FV function, 219, 228–230
G Gantt chart, 265 general protection fault (GPF), 714 geographic data, 852
40012ndex.qxd 7/27/01 11:01 AM Page 881
geometric numeric series, as fill option • hyperlinks
geometric numeric series, as fill option, 60 global macro workbook, 649 global macros, 646 Go To dialog box, 364 Go To Special dialog box, 364, 378 Go To statement (Visual Basic), 814 Goal Seek, 591, 592–593, 593 GPF (general protection fault), 714 graphics. See also Microsoft Clip Organizer; Microsoft Draw; objects AutoShapes, 297–298, 298 changing, 307 Curve objects, 298–299 for flowcharts, 299–300, 300 FreeForm objects, 298–299 Line art objects, 300–303 Scribble objects, 298–299 for chart fills, 291 diagrams and organizational charts, 312–316 Excel data in Word as, 527 flowcharts, 299–300, 300 formatting, 332–334 in header or footer, 80 for hyperlinks, 139 hyperlinks to insert, 663, 664 inserting into worksheets, 330–334 from other sources, 335–336 Line art objects, 300–303 new features, 5 rotating, 334, 334 shadow and 3D effects, 307–308 sizing, 330 WordArt, 303–304 graphics digitizing tablet, 37 green triangle indicator for errors, 23 greenbar, creating, 378 Gregorian calendar, 72 gridlines for charts, 251 printing or hiding, 82 in worksheets, 44, 44 group box controls, 458, 471–472 grouped worksheets, 121–122 grouping drawing objects, 311–312 items in pivot tables, 406–407, 407
H handles for chart object, 253 for graphics, 330 for text box, 303 Handwriting Options dialog box, 37, 37 handwriting recognition, 27, 35–37 HasAxis property of Chart object, 826 Header dialog box, 79 headers and footers, 78–80 Help, 20–21 for VBA and Excel 2002 objects, 713 for Visual Basic, 716–724, 717 in Excel, 719–722 Help menu, Show the Office Assistant, 20–21 Help menu (VB), Microsoft Visual Basic Help, 716 Hex function (VBA), 800, 801 hidden cells, plotting on chart, 287 hidden workbooks, unhiding, 649 hiding formulas, 437 rows and columns in worksheet, 105 title bar, 448 worksheets, 825 high-low charts, 277 high security, 785 Highlight Changes dialog box, 619 Hijri calendar, 72 History in Places bar, 17 History sheet, for tracked changes, 620 HLOOKUP function, 204, 205, 207 holidays exporting from Outlook, 192–194 functions to exclude, 191–194 horizontal alignment of text, 91 HOUR function, 187 hours of day, decimal values, 184 HTML (Hypertext Markup Language), 569 converting Excel worksheet to, 528 e-mailing worksheet as, 612 hyperlinks, 137–142 assigning to command, 662–663 blue underscore for, 23 to create new document, 141 to e-mail message form, 141–142 editing, 142 event triggered by clicking, 841
881
40012ndex.qxd 7/27/01 11:01 AM Page 882
882
IF functions • international settings
to existing file, 140 vs. macros, 645 navigation buttons with, 446–447 pasted object as, 530 stopping automatic creation, 25 to Web page, 139–140 to workbooks, 140
I IF functions, 198–204 with AND and OR, 202 nesting, 199–201, 200 summary IF, 202–204 to take action, 198–202, 199 If statements (VB), 816–818 Immediate window in Visual Basic IDE, 679, 709 Imp operator in VBA, 807 Import and Export Wizard (Outlook), 541–544, 542 for exporting data, 545 Import Data dialog box, 494 Import Data Wizard (MapPoint), 854, 854–855 Import File dialog box, 683 Import Spreadsheet Wizard (Access), 487, 488 Import to SharePoint List dialog box, 635 importing clips to Microsoft Clip Organizer, 326–327 importing data, 491–498 Excel options for, 476 from other applications, 545–550 parsing data, 547–549 refreshable text importing, 549–550 indentation of text, 92 in VBA, 792–793 INDEX function, 209–210, 466 Indexing Service, 12 infinite loops, avoiding, 814 information functions, 149, 215 input cell for data table, 585, 585 Insert Calculated Field dialog box, 421 Insert Calculated Item in X dialog box, 423 Insert Clip Art task pane, 317 search results, 318 Insert dialog box, 124 Insert Function dialog box, 150, 150, 151, 173, 206, 702 for user-defined function, 704
Insert Hyperlink dialog box, 138, 139, 446 Insert menu Columns, 103 Hyperlink, 138, 658 Name Define, 126, 130, 132 Paste, 128 Object, Create from File, 534 Picture AutoShapes, 297 Clip Art, 317 From File, 335 From Scanner or Camera, 336 WordArt, 303 Worksheet, 123 Insert menu (VB Editor) Procedure, 697 UserForm, 682 Insert Options button, 23 Insert Picture dialog box, 335 inserting AutoShapes, 297–298, 298 cells in worksheet, 106 files, 532–534 graphics into worksheets, 330–334 from other sources, 335–336 from scanners and cameras, 335–336 manual page breaks, 84 rows and columns in worksheet, 103–104 text box, 302–303 worksheets, 123–124 insignificant digits, 70 installing Analysis Toolpack, 187–188 Conditional Sum Wizard, 379 language support, 38 Template Wizard with Data Tracking add-in, 478 INT function, 234 Int function (VBA), 800 integer data type (VBA), 798 integrity of data, Excel vs. Access, 344 IntelliMouse, and zoom, 772 interactive web pages, 555, 557–566, 560 interest compound, 227, 228–230 in payment, calculating, 221 simple, 227, 228 Interior object, 828 international settings, 776
40012ndex.qxd 7/27/01 11:01 AM Page 883
interpolation • Lined Paper Writing Pad
interpolation, 287 intersections, 59 names to refer to, 129, 129 intranet site, from SharePoint Team Services, 26, 26 Invalid Reference error, 160 IPMT function, 221 ISBLANK function, 215 IsDate function, 741, 743 ISERR function, 215 ISERROR function, 215 ISLOGICAL function, 215 ISNA function, 215 ISNONTEXT function, 215 ISNUMBER function, 215 ISTEXT function, 215 iterations in Goal Seek, 592
J JavaScript, and ActiveX controls, 454 joins creating, 507 cross, 506 Joins dialog box, 508 Julian calendar, 72–73 Julian dates, 179–180 Justify alignment, 91
K keyboard cell pointer movement, 45 forced line breaks, 93 function keys F2 for cell editing, 48 F4 for absolute references, 156 setting command accelerator, 661 shortcut keystrokes, 116 for cut, copy and paste, 108 in Immediate window, 709 for macros, 646 keyboard alternatives handwriting recognition, 35–37 multilanguage support, 38 speech features, 27–35 dictating, 30 speech recognition setup, 28–30
tweaking, 32 voice commands, 30–32 text to speech feature, 33, 33–35 changing voices, 33–34 keywords assigning to clips, 323–324, 324 in VBA, 794 Keywords dialog box, All Clips at Once tab, 324, 325 Knowledge Base, 719
L Label controls, 454, 458 adding, 733–735 labels for charts, 251 for consolidating databases, 414 range names from, 127–128 landscape orientation, 77 language multilingual editing, 118 for spell check, 779–782 supporting multiple, 38 Language Bar, 28, 28 Draw button, 35 Microphone button, 30 Tools Options, 32 Write menu, Lined Paper, 36 Language Detection, Automatic, 116 LARGE function, 377 layers for drawing objects, 309 leading spaces, 170 leading zeros, text formats for numbers and, 68 LEFT function, 172–174 legend for charts, 251 Legend object, 826 LEN function, 175 Lernout & Hauspie, speech-recognition engine, 27 libraries for objects, 724, 725–726 licensing for Office Web components, 558 line break, invisible character for, 93 line charts, 244, 244 line color for drawing objects, 306 line continuation character, 793 line style for drawing objects, 306 linear numeric series, as fill option, 60, 61 linear programming, 599 Lined Paper Writing Pad, 36
883
40012ndex.qxd 7/27/01 11:01 AM Page 884
884
linked objects • measures in OLAP cube
linked objects, 525, 529, 530–532 links, 133–137 with hyperlinks, 137–142 list controls, 453, 458, 464–468, 465 vs. data validation, 468–469 properties, 465 list files for smart tags, 862–866 loans amortization table, 222–227, 223 modified, 225, 225–227 interest rate calculation, 222 nonstandard payments, 225–227 payment calculation, 219–221 principal calculation, 222 term calculation, 221–222 local macros, 646 local scope, defining names with, 131 Locals window in Visual Basic IDE, 679 Locked object, 828 Locked property of cells, 436 logical errors, troubleshooting, 159 logical functions, 149, 198 IF functions, 198–204 with AND and OR, 202 summary IF, 202–204 to take action, 198–202, 199 to trap errors, 214–215 logical operators, 52, 198 in VBA, 806, 807 long data type (VBA), 798 lookup functions, 149, 198, 204–214, 205 HLOOKUP, 207 LOOKUP, 208 Lookup Wizard, 210–214, 211, 212, 213 MATCH and INDEX, 209–210 VLOOKUP, 206–207 lookup tables, in Retirement Countdown application, 731, 731 looping Do... loops, 810–813 For Each...Next loops, 809–810 For...Next loops, 808–809 infinite loops, 814 nesting, 815 in user-defined function, 697–700 Lotus 1-2-3, converter for, 546 low security, 785 LOWER function, 174
M Macintosh 1904 date system, 65, 183 Macro dialog box, 647, 648, 703 running macros from, 656 Macro Options dialog box, 703 Macro Recorder, limitations, 653 macros, 644–651 absolute and relative cell references in, 647 Command button to run, 459 comments in, 652 creating, 644–645 deleting, 648–649 editing, 654–655 to hide title bar, 448 opening file containing, 649–651 running from form button, 667–668 from Macros dialog box, 647, 648 security and, 784–785 stopping recording, 647 storing, 646–647 as subprocedures, 804 terminating during execution, 648 virus risk from, 649–651 magnification (zoom), 101 mail merge with Word and Excel, 537–538 manual page breaks deleting, 85 inserting, 84 Map Custom Fields dialog box (Outlook), 543, 543 MapPoint 2002, 852–858 demo CDs, 858 exporting data to Excel, 856–857 importing and mapping Excel data, 854–855 integration with Excel, 857–858 results from, 853 maps, copying to Excel from MapPoint, 857 margin adjustment, when printing worksheets, 76 margins adjusting when printing worksheets, 75 of command buttons, 462–463 Page Setup dialog box to set, 77, 77–78 MATCH function, 209–210 mathematical functions, 149 mathematical operators, 52 MAX function, 56, 157 measures in OLAP cube, 513
40012ndex.qxd 7/27/01 11:01 AM Page 885
MEDIAN function • moving
MEDIAN function, 156 medium security, 785 meetings, virtual, 638–640 memory, for speech recognition, 28 Menu bar, 43 menus creating, 664–665 customizing, 657–667 for macros, 660–663 personalized, 14–16, 15 for smart tags, 21 merge, 92–93 Merge and Center alignment, 89, 90 merging workbook changes, 622 Message Options dialog box, 625, 625 methods in VBA, 653, 795 MHTML (MIME HTML), 572 microphone for speech recognition, 27 setup, 28–29 turning off and on, 30 Microsoft Clip Organizer, 13–14, 316–330 assigning keywords, 323–324, 324 database maintenance for, 330 Explorer interface, 319–322, 320 collections, 320–321 finding similar clips, 319 importing clips, 326–327 organizing clips, 322 searching for clip, 317–319 shared catalogs, 327 Microsoft Design Gallery Live, finding new clips on, 327–329, 328 Microsoft Draw, 296–316 Curve, Freeform and Scribble objects, 298–299 diagrams and organizational charts, 312–316 flowcharts, 299–300 formatting objects, 305–312 inserting AutoShapes, 297–298 Line art objects, 300–303 WordArt, 303–304 Microsoft Excel Visual Basic Reference, 718 Microsoft Exchange Conferencing, 638 Microsoft Forms Reference, 718 Microsoft Graph Object Model, 719 Microsoft Office dictionary for, 115 and Excel, 536–545 Outlook, 541–544 PowerPoint, 539–541 Word, 537–538
integrating Excel with other applications, 724–728, 724–728 referencing Excel from another application, 727–728 Web site for templates, 429 Updates, 428 for Visual Keyboard, 38 Microsoft Office Document Imaging, 12 Microsoft Office Object Model, 719 Microsoft Office Visual Basic Reference, 719 Microsoft Org Chart, 312 Microsoft Platform SDK, 714 Microsoft Project 2000, 265 Microsoft Query defining relationships, 505–508 launching, 498 parameter queries, 509–510 for pivot table report, 413 to retrieve external data, 498–512 new data source setup, 500, 500–501 selecting data source, 499 Microsoft SQL Server, 344 views, 608 Microsoft Visual Keyboard, 38 MID function, 172–174 MIME HTML (MHTML), 572 MIN function, 57, 157 MINUTE function, 187 Miscellaneous options section, of New Workbook task pane, 9 mixed cell references, 156 MOD function, 235–237, 378 MODE function, 157 modeling. See also forecasting and modeling modular division, 235 module-level scope, 797 modules, 652, 681 MOFL.DLL for smart tags, 860 MONTH function, 187, 190 mouse pointer, 44, 49, 50 MouseDown event (VBA), 830, 842 MouseMove event (VBA), 830, 842 MouseUp event (VBA), 831, 842 Move method of Worksheet object, 825 Move or Copy dialog box, 122, 123 movie files, 321 moving cell contents, 106–109 cell pointer, 45–46
885
40012ndex.qxd 7/27/01 11:01 AM Page 886
886
MROUND function • objects
charts, 252–253 form controls, 461 worksheets, 122–123 MROUND function, 234 Multidimensional Connection dialog box, 515 multilanguage support, 38 multivariate analysis, radar charts for, 275
N #N/A error, 159, 206 handling, 214 Name box, 43 in application window, 42 #NAME error, 159 names for controls, 687 for macros, 645 to store constants, 132–133 to store user-defined functions, 133 for VBA variables, 794 for worksheets, 120 names for range of cells, 124–128 as absolute cell reference, 155 creating creating from row or column, 127–128 with Define Name dialog box, 126, 126–127 with Name box, 125 names to span worksheets, 130–131 for other workbooks, 129–130 same name in multiple worksheets, 131–132 using, 128–133 in functions, 203 as reference to other workbooks, 129–130 namespace, XML, 863 naming rules, in VBA, 797 natural language formulas, 55 navigation buttons in application window, 43, 43 with hyperlinks, 446–447 navigation using names, 128 negative numbers, Text to Speech and, 34 nesting functions, 172–173 IF functions, 199–201, 200 nesting loops, 815 NetMeeting, 638, 639 Network Places. See Web folders NETWORKDAYS function, 187, 191–194, 432
new document, hyperlink for, 141 New Web Query dialog box, 573, 574 New Workbook task pane, 7, 8, 9, 429 NewSheet event (VBA), 831, 842–843 NewWorkbook event (VBA), 831, 842–843 Next keyword, 809 noncontiguous cells, selecting, 49 noninteractive web pages, 555, 558 and web queries, 578, 578–579 nonprinting characters, removing, 171 Not Available error, 159 Not operator in VBA, 807 Notepad for smart tag creation, 861 list file creation, 862–866 NOW function, 186, 189 NPER function, 219, 222 nudging drawing objects, 310–311 #NULL error, 160 #NUM error, 160 NUM in status bar, 42 numbers, 52–59 entry, 46–49 filling, 59–62 formatting, 62–73 with Format Cells dialog box, 64, 64–73 with Formatting toolbar, 63–64 in strings, 178–179 formulas, 53–59 rounding, 234–235
O Object Browser, 679, 723, 723–724 for constants, 796, 796 object data type (VBA), 798 Object dialog box Create from File tab, 534 Create New tab, 536 object libraries for Office applications, 724 adding references, 725–726 object-oriented language, 675 objects. See also embedded objects; linked objects alignment, 310 arranging, 309–310 creating, 535–536 formatting, 305–312 grouping and ungrouping, 311–312 help for, 713 placeholders, 769
40012ndex.qxd 7/27/01 11:01 AM Page 887
objects in VBA • OR
objects in VBA, 794 assigning to variable, 803 OCR (Optical Character Recognition), 12 Oct function (VBA), 800 ODBC data sources, 492–493 drivers, 493 importing from, 491 OLEDB data sources vs., 494 ODBC Manager, 500 ODD function, 234 Office Assistant, 20–21 Office Clipboard, 9–10, 10, 107–108 to copy formatting, 179 Office Collections folder, 321 Office Data Connection, for pivot table data, 412 Office shortcut bar, Excel icon, 7 Office Web Components, 555, 557, 558 Chart component, 565–566, 566 PivotTable component, 563, 563–565 Spreadsheet component, 560–562, 562 Office XP dictionary for, 115 and Excel, 536–545 Outlook, 541–544 PowerPoint, 539–541 Word, 537–538 integrating Excel with other applications, 724–728 Web site for templates, 429 Updates, 428 for Visual Keyboard, 38 OK command button code, 739–748 generating error messages, 743–747 testing validation code, 747–748 validating user data, 739–743 OLAP (Online Analytical Processing) 3D pivot analysis with, 512–522 creating data source, 514–516 OLAP Cube Wizard, 516, 518 OLAP cubes, 513–514 creating, 516–520 cube definition file, 520 opening existing, 514 OLE (Object linking and embedding), 524–536 OLE client, 524 OLE objects, creating from files, 534 OLE server, 524
OLEDB data sources importing from, 491 vs. ODBC data source, 494 Online Analytical Processing (OLAP), 3D pivot analysis with, 512–522 Open dialog box, 16–18, 17 Open event (VBA), 831, 843 Open Workbook section of New Workbook task pane, 9 opening OLAP cubes, 514 workbooks existing, 7 password, 782–783 those containing macros, 649–651 in Word, 538 XML files in Excel, 571 operators mathematical and logical, 52 in VBA, 806–807 Optical Character Recognition (OCR), 12 optimal solution, Solver to find, 594, 599–602 option button controls, 454, 458, 471–472, 737 in Retirement Countdown application, 736–737 Option Explicit statement, 802 Options dialog box, 768–785 Calculation tab, 168 Accept Labels in Formulas, 55 automatic or manual, 167 for date system, 65, 183 Chart tab, 285, 285–288 Color tab, 288, 289, 372 Custom Lists tab, 775, 775–776 Edit tab, 770, 770–771 for AutoComplete, 46 Extend List Formats and Formulas, 62, 342 Error Checking tab, 777–779, 778 General tab, 772, 772–775 default number of worksheets, 43 Recently used files, 434 International tab, 776, 776 Save tab, 776–777, 777 AutoRecover, 39 Security tab, 782–785, 783 Spelling tab, 779, 779–782 View tab, 445, 768–769, 769 .oqy file extension, 520 OR in filter criteria, 353, 356
887
40012ndex.qxd 7/27/01 11:01 AM Page 888
888
order of operations in formulas • pivot tables
IF functions with, 202 for parameter query, 510 in VBA, 807 order of operations in formulas, 56 organizational charts, 312–316 creating, 313, 314 layout, 314 selecting sections, 314–315 styles, 315, 315 orientation of page, 76, 77 outlines, 388–397, 389 creating, 390–391 with AutoOutline, 391 manually, 393–395 worksheet structure review for, 392–393 displaying and hiding symbols, 391 formatting, 395–396 Outlook, 141 Calendar for meeting scheduling, 639 and Excel, 541–544 exporting data to Excel, 545 exporting holiday list from, 192–194 message settings for Send for Review, 624 oval, 301
P P-Code, 677 Page Break Preview, 73, 84 and chart placement, 253 page breaks when printing worksheets, 84–85 page ranges, printing, 74 Page Setup dialog box Header/Footer tab, 78, 78–80 Margins tab, 77, 77–78 Page tab, 76, 76–77 Sheet tab, 80–82, 81 PageSetup object of Worksheet object, 824 paragraphs, AutoCorrect to insert, 117 parameter queries, 509–510 parentheses ( ) for functions, 690 parsing data, 172–174, 544 with Text Import Wizard, 547, 547–549, 549 password, 782–783 for protected workbook, 436 for merging, 622–623 and Web publishing, 558 for worksheets, 441
Paste Errors table in Access, 485 Paste Link, 135 Paste Name dialog box, 128 Paste Options button, 23, 23–25 menu, 24 Paste Special dialog box, 110 to calculate without formulas, 112 to embed objects, 529 for non-Excel data, 111 options, 111–112 Skip Blanks option, 113 to transpose data, 112, 112 Paste Special dialog box (Word), 528 pasting. See also Copy and paste and conditional formatting, 379 patterns for fills, 96, 96 PDAs (personal digital assistants), handwriting recognition, 35 percentage entry, 771 formatting, 65 period (.) to designate control properties, 690 Permissions dialog box, 439 Personal Macro Workbook, 646 storing global macros in, 657 personalized menus and toolbars, 14–16, 15 PERSONAL.XLS workbook, 649 perspective for 3-D chart, 261 phone numbers, formatting, 68 Pick From List, 48 Picture toolbar, 331–332 pictures. See graphics pie charts, 243, 243 exploding, 259, 259–260 Pivot charts, 397 creating, 424–426, 426 pivot tables 3D with OLAP, 512–522 AutoFormats, 411 changing summary and format for data fields, 408 creating from consolidation ranges, 413–417 separate, 424 using external data sources, 412–413 custom calculations, 418–423 calculated fields and items, 420–421, 422 calculated item formulas, 422–423 summarization function and basis, 418, 418–420
40012ndex.qxd 7/27/01 11:01 AM Page 889
PivotLayout object • protecting
date area, 404 drilling down, 423–424 filtering items, 405–406 grouping items, 406–407, 407 layout changes, 402–408 page area, 403 removing and adding fields, 404–405 row and column areas, 403 setting options, 409–411 subtotals vs., 399 updating, 417 PivotLayout object, 828 PivotTable and PivotChart Wizard, 399–402, 400 for consolidating databases, 414–415 data range verification, 400, 401 data source and report type, 400 layout and destination, 401, 401–402, 402 PivotTable component, 557, 563, 563–565 PivotTable event (VBA), 843–845 PivotTable Field dialog box, 408, 419 PivotTable Field List dialog box, 564 PivotTable object of Worksheet object, 824 PivotTable Options dialog box, 409, 409–411 data options, 411 format options, 410 PivotTable reports, 397–426, 398 AutoFormats, 98 PivotTable toolbar, displaying, 404 PivotTableCloseConnection event (VBA), 831 PivotTableUpdate event (VBA), 831 placeholders for custom formats, 69 Placement property, 828 Places bar, 16–17, 17 customizing, 18–19 plot area, 254, 255 plotting on chart hidden cells, 287 missing values, 286, 286–287 PMT function, 219, 220 PNG (Portable Network Graphics), 773–774 point-and-click to create formulas, 53–54 pointer (mouse), 44, 49, 50 portrait orientation, 77 PowerPoint and Excel, 539–541 including PivotChart in presentation, 425 referencing Excel from, 727–728 PPMT function, 221 precedents of formula, 164, 165
present value of money (Pv), 218 primary key for Access database, 487 primary sort, 346 principal in payment, calculating, 221 print area, 81 Print dialog box, 73, 74 printable forms, 450–453, 452 printing charts, 252–253 event triggered prior to, 845–846 filtered database, 353 printing worksheets, 73–74 blank pages when, 83 margin adjustment, 75, 76 options, 84–85 page breaks, 84–85 page setup, 76–82 Print Preview, 74, 75 tips and tricks, 83 Private keyword (VB), 689, 696, 698, 802 procedure-level scope, 797 variable declaration with, 801 procedures in VBA, 673, 681, 795, 804–805 programming, development process, 676–678 programming structures in VBA, 808–819 conditional branching, 815–819 Do... loops, 810–813 For Each...Next loops, 809–810 For...Next loops, 808–809 If statements, 816–818 infinite loops, 814 nesting loops, 815 Select Case structure, 818–819 sequential structures, 808 While... Wend structures, 813 Project Explorer in VB IDE, 651, 652 PROPER function, 174 properties of controls, 686–688 period (.) to designate, 690 of files, removing user information from, 783 recording in macros, 654–655 in VBA, 795 Properties window in VB IDE, 651, 652, 686 proportional sizing of graphics, 330 protecting cells in templates, 433 graphics, 332
889
40012ndex.qxd 7/27/01 11:01 AM Page 890
890
Protection property of Worksheet object • Retirement Countdown application
workbooks, 435–436 worksheets and ranges, 436–441 Protection property of Worksheet object, 824 Public keyword (VB), 689, 696, 698 public scope, 797 Publish as Web Page dialog box, 558–559, 559, 568 purple triangle indicator for smart tags, 23 PV function, 219, 222 pyramid diagram, 313
Q quality assurance, radar charts for, 277 quality of print, 77 Quattro Pro, converter for, 546 queries new features, 5 parameter, 509–510 Query. See Microsoft Query Query Wizard, 502, 502–505 for editing query, 505 filter criteria, 503, 503 sort order, 503, 504 QueryTable objects, special requirements, 832–833 question mark (?) as Find and Replace wildcard, 51 Quick Watch dialog box (VB), 710 Quit method, 726 quotation marks (‘) for comments, 652, 792 QUOTIENT function, 235–237
R R1C1 reference style, 772 radar charts, 264, 275, 275–277, 276 radial diagram, 313 radio buttons. See option button controls RAM, for speech recognition, 28 RAND function, 238 Range collection, of Worksheet object, 824 Range Finder, 58 Range object of Worksheet object, 824 range of cells as function argument, 152 naming, 124–128 creating from row or column, 127–128 with Define Name dialog box, 126, 126–127 with Name box, 125
painting formats from, 97 protecting, 436–441 selecting, 49–50 user editing of, 437–441 Rate as financial function argument, 219 RATE function, 219, 222 Recognition Profile Settings dialog box, 32 Record Macro dialog box, 645, 646 records in database, 340 adding and deleting in data form, 366 Advanced filter to eliminate, 359–360 recovering files manually, 786–789 recovering passwords, utilities for, 436 recovery of data, new features, 5 rectangle, 301 #REF error, 160 reference functions, 149 References dialog box, 725 refreshable web query, 573, 573 refreshing Query data, 511 Regional Options dialog box, Date tab, 67 relational database, 344 relationships, defining in Query, 505–508, 507 relative cell reference, 153–156 in macros, 647 relative URL, 140 remark lines in VBA, 792 repairing damaged workbooks, 19–20 replace. See Find and Replace Report Manager dialog box, 609 reports from Access in Excel, 489–490 as analysis tool, 609–610 Resize event (VBA), 831 Resolve Conflict dialog box, 621 Retirement Countdown application, 729–763 basics, 729–731 calculating retirement values basCalcHolidays function, 755–756 basCalcVacation function, 752–754 basCountWeekends function, 756 basYrsService function, 756 CalcRetirement subroutine, 749–750 constants worksheet, 751 DisplayOutput subroutine, 756–762 code for Cancel command button, 738 code for OK Command button, 739–748 generating error messages, 743–747
40012ndex.qxd 7/27/01 11:01 AM Page 891
reversing AutoCorrect • searching in Excel
testing validation code, 747–748 validating user data, 739–743 custom command bars, 762–763 form display for user, 738 lookup tables, 731, 731 UserForm controls, 733–737 creating, 731–732, 732 design mode, 730 display for user, 738 properties, 732–733 reversing AutoCorrect, 25 Reviewing toolbar, 26, 626 ribbon charts, 244 right-clicking, 839 RIGHT function, 172–174 ROMAN function, 195 root element in XML, 570 rotating graphics, 331, 334, 334 text, 91–92 ROUND function, 64 ROUNDDOWN function, 234 RoundedCorners object, 828 rounding, errors from, 598 rounding numbers, 234–235 ROUNDUP function, 234 Routing Slip dialog box, 482, 614 routing workbooks, 613–616 ROW function, 378 Rows and Columns property of Worksheet object, 824 rows in worksheets, 44, 44 arranging for outlining, 392–393 blank to designate database end, 341 freezing, 104 height, 103 hiding, 105 inserting and deleting, 103–104 printing numbers for, 82 repeating on printout pages, 81 selecting, 49 summarizing, 57 testing for empty, 103 transposing to columns, 112, 112 vertical title crossing multiple, 92–93 RTF, converting Excel worksheet to, 528 Rule of 72, 228 runtime, 454
S Safe mode, 39 Save As dialog box, 16–18, 555, 556 saving chart types, 282–283 event triggered by prior to, 846–847 files in Web folders, 554–555 smart tags list file, 865–866 Solver models, 602–603 static web page, 555–556 templates, 430, 432 workbooks to Exchange folder, 626–627 before formatting changes, 396 as HTML, 528 as XML, 571–572 Scaliger, Joseph P., 180 scaling print page, 77 scanner importing clips from, 326 inserting graphics from, 335–336 scatter charts, 265, 272, 273 Scenario Manager dialog box, 604–605, 605 Scenarios, 603–607 merging, 604–606 reports to combine with worksheets and views, 609–610 summarizing, 606–607 scientific notation, 65 scope for names in workbooks, 131 for procedure, 698 of VBA variables, 797 screen tips for hyperlinks, 139, 447 for tracked changes, 619 Scribble objects, 298–299 script-level scope, creating variable with, 802 scroll bar controls, 459, 469–470, 470 scroll bars, 43, 45 SEARCH function, 174, 175 searching in Excel, 11–14 Advanced Search, 12–13, 13 Basic Search, 11, 11–12 for clip art, 13–14, 317–319 with data forms, 366–367 results, 12
891
40012ndex.qxd 7/27/01 11:01 AM Page 892
892
secondary sort • SMALL function
secondary sort, 346 security. See also password of data, Excel vs. Access, 345 macros and, 784–785 new features, 6 settings, 782–785 Security dialog box, Security Level tab, 650, 785 Select Case structure, 818–819 Select Data Source dialog box, 491 for mail merge, 538 Select event (VBA), 831 Select method of ChartObject object, 828 Select Table dialog box for mail merge, 538 Select Users, Computers, or Groups dialog box, 440 selecting charts, 253 event triggered by change, 847–848 functions, 150 linked or embedded objects, 532 merged cells and, 90 multiple cells, 49–50 organizational chart sections, 314–315 worksheets, 121 SelectionChange event (VBA), 831, 847–848 Send for Review, 623–626 sequential structures in VBA, 808 serial value for dates and times, 180 series charts, 243–246 Series dialog box, 62 series, filling, 60–62 SeriesChange event (VBA), 831, 847–848 Set Hyperlink ScreenTip dialog box, 447 Set statement, 803 Sgn function (VBA), 800 shadow effect for drawing objects, 307–308 shadowing a keyword, 794 Shapes collection, 826 Share Workbook dialog box Advanced tab, 618 Editing tab, 617 for merging, 622–623 shared Clip Organizer catalogs, 327 SharePoint Portal Server, 26, 638 SharePoint Team Services, 26, 627–638, 628 creating team site, 629–630 discussions about documents, 633–634 hardware and software requirements, 628 importing list from spreadsheet, 634–637 making changes, 636–637
making new workbooks available, 630, 630–632 sending documents for review, 632–633 sharing workbooks, 617–623 conflict resolution, 621 highlighting changes, 619 limitations, 623 merging changes, 622 protecting for merging, 622–623 saving workbooks to Exchange folder, 626–627 Send for Review, 623–626 viewing change history, 620 sheet tabs in application window, 43, 43 SheetActivate event (VBA), 829, 834–835 SheetBeforeDoubleClick event (VBA), 829 SheetBeforeRightClick event (VBA), 829 SheetCalculate event (VBA), 822, 830 SheetChange event (VBA), 830 SheetDeactivate event (VBA), 830, 834–835 SheetFollowHyperlink event (VBA), 830 SheetPivotTableUpdate event (VBA), 831 Sheets collection in Excel object model, 822–828 SheetSelectionChange event (VBA), 831 shortcut keystrokes for hyperlinks, 658 for macros, 646 shortcut menu for cell, 45 shortcuts for Web folders creating in Windows 98/NT 4.0, 554 creating in Windows 2000/Me, 552–554 Shrink to Fit, 93 significant digits, 70 simple interest, 227, 228 single data type (VBA), 798 size of database, Excel vs. Access, 344 SizeWithWindow property of Chart object, 826 sizing AutoShapes, 298 charts, 252–253, 288 controls, 684, 686, 735 dialog boxes, 16 form controls, 461 graphics, 330 organizational charts, 314 slash (/), 117 Slide Show menu (PowerPoint), Custom Animation, 539 SLN function, 233 SLYK (Symbolic Link) file for data recovery, 787–788 SMALL function, 377
40012ndex.qxd 7/27/01 11:01 AM Page 893
Smart Tag SDK • styles
Smart Tag SDK, 860 smart tags, 21–23, 142–144 creating, 860–867 tools for, 860–861 enabling support, 144 options, 143 paste options, 527 purple triangle indicator for, 23 schema, 861 settings, 781–782 SmartTagMOSTLGenerator, 860 to create list file, 866, 866–867 Snap to Grid, 310 Snap to Shape, 310 snippets of code, 673 social security numbers, formatting, 68 Solver, 591, 594–603 Evaluate Formula feature, 596–598 with multiple variables, 598–602 saving models, 602–603 Solver Parameters dialog box, 594, 595, 600, 601 Sort dialog box, 345, 346–347 Sort Options dialog box, 347 sorting databases, 340, 345–348 multilevel, 346–348 with Sort buttons, 348 sound card for speech recognition, 27 sound files, inserting or importing, 534 source workbook for links, 134 spaces, trailing and leading, 170 spacing in custom format, 73 Special formats for numbers, 68 speech features, 27–35 dictating, 30 Speech recognition setup, 28–30 tweaking, 32 voice commands, 30–32 Speech object, 727 Speech Properties dialog box, 29 Text to Speech tab, 34 spelling check, 113–115 options, 779–782 Spelling dialog box, 114 spider charts, 264 spinner controls, 459, 469–470, 470 splitting worksheet window, 104–105 Spreadsheet component, 557, 560–562, 562 features and formatting not supported, 561–562 toolbar, 560, 560–561
SQL databases, importing from, 491 SQL Server (Microsoft), 344 views, 608 square, 301 stacked area chart, 265 stacked bar chart, 245 stacked column chart, 245, 246 Standard toolbar, 14, 43 AutoSum button, 56 Chart Wizard button, 248 Drawing button, 296 Insert Hyperlink button, 138 MapPoint button, 857 New button, 429 personalized, 659 Print Preview button, 74 Spelling button, 114 Start menu Programs, Microsoft Excel 2002, 7 Programs, Microsoft Office Tools, Microsoft Office Application Recovery, 39 Startup Prompt dialog box, 137, 137 statements in VBA, 690, 793 Static keyword, 696 static web page, worksheets as, 555–556 static web query, 573 statistical functions, 149, 156–158 status bar, 42, 43 CIRCULAR, 166 Recording message, 646 step value for series fill, 61 stock charts, 265, 277–278, 278 stop value for series fill, 61 storing charts, 293 macros, 646–647 straight-line depreciation, 233 string data type (VBA), 798 strings, 170. See also text empty, as text, 224 formatting numbers in, 178–179 stub of code, 673 Style dialog box, 99 styles applying, 100 copying between workbooks, 100–101 creating, 98–99 modifying and deleting, 100 for outlines, 396
893
40012ndex.qxd 7/27/01 11:01 AM Page 894
894
Sub statement • 3D area chart
Sub statement, 653, 793, 804 subprocedures in VBA, 804 subroutines, 674, 690 subset of database, 353–354 advanced filters to extract, 354–360 substrings, functions to locate, 174–175 Subtotal dialog box, 360 SUBTOTAL function, 362–363 subtotals for database field, 360–364 copying, 363–364 Excel creation of, 362–363 vs. pivot tables, 399 subtracting dates and times, 185–186 SUM function, 56 sum of the years’ digits depreciation, 233 SUMIF function, 202, 203 summarization functions, 56–57 surface charts, 265, 270, 270 SYD function, 233 System DSN, 501 system resources, for MapPoint, 853
T tags in XML, 570 target cell for Solver, 595 target diagram, 313 task panes, 7–14, 43 Advanced Search, 12–13, 13 Basic Search, 11, 11–14 Document Recovery, 19, 19–20 Insert Clip Art, 317 New Workbook, 8, 9, 429 Office Clipboard, 9–10, 10 telephone numbers, Text to Speech and, 35 Template Wizard with Data Tracking add-in, 477–483, 479, 480, 481 installing, 478 templates, 428–435, 430 creating for other users, 433–435 for personal use, 430–432 data entry, 429–430 editing, 434 existing, 428–430 hiding worksheets, 434–435 macros stored in, 646
saving, 430, 432 vs. workbook, 431 Templates dialog box, Spreadsheet Solutions tab, 429 terminating macro during execution, 648 tertiary sort, 346 testing Visual Basic code, 747–748 text. See validation of data AutoCorrect to replace, 781 in closed objects, 301 converting to columns, 176–177 including in custom number format, 73 Text Box tool, 302, 302–303 text formats for numbers, 68 text formatting, 88–97 alignment, 89–93 direction of text, 93 horizontal and vertical, 91 indent, 92 merge, shrink to fit, wrap, 92–93 rotating text, 91–92 borders and color, 94–96 fonts, 88 with Format Painter, 97 TEXT function, 178–179 to convert date to text, 189 Text Import Wizard, parsing data with, 547, 547–549, 549 text manipulation, 170–179 entering, 46 functions, 149 to change case, 174 to convert to date, 179 copying results, 171–172 to determine length, 175 to find text position in cell, 174–175 parsing data, 172–174 putting strings together, 178–179 removing spaces, 170–171 text to speech feature, 33, 33–35 changing voices, 33–34 Visual Basic for, 727–728 TextBox controls, 453 adding, 733–735 adding to UserForm, 684, 685 code for, 690 TextLength property, 740 ThisWorkbook property of Workbook object, 822 3D area chart, 267, 268
40012ndex.qxd 7/27/01 11:01 AM Page 895
3D effect for drawing objects • typing errors, AutoCorrect
3D effect for drawing objects, 307–309 3D name, 130 3D pivot analysis with OLAP, 512–522 3D views in charts, 260–261 time. See dates and times TIME function, 186, 188–189 for addition, 191 time-scale axes, 278 time value of money, 218 arguments for functions, 219 Timed Recovery Save, 39 TimeSerial function (VBA), 800 TimeValue function (VBA), 800 Title bar, 43 title bar, hiding, 448 titles for charts, 258–259 TODAY function, 186, 189, 378 Toolbar Options button, 15, 43 Toolbar Options menu, Add or Remove Buttons, Customize, 16 toolbars adding buttons, 16 attaching and resetting, 666–667 buttons missing from, 659 creating, 452–453, 665–667 creating buttons for, 661 customizing, 14–16, 15, 657–667 for macros, 656, 660–663 Toolbox (Visual Basic), 684 Tools menu Add-Ins, 188, 211, 706 AutoCorrect Options, 116 Smart Tags, 144 Compare and Merge Workbooks, 622 Error Checking, 164 Formula Auditing, Show Formula Auditing Toolbar, 385 Macro Macros, 647, 703 Record New Macro, 644 Security, 650 Visual Basic Editor, 651, 679 Options. See Options dialog box Protection Allow Users to Edit Ranges, 438 Protect and Share Workbook, 623 Protect Workbook, 435 Unprotect Worksheet, 441 Scenarios, 603
Share Workbook, 617 Solver, 594 Speech Show Text to Speech Toolbar, 33 Speech Recognition, 28 Spelling, 114 Track Changes Accept or Reject Changes, 621 Highlight Changes, 619 Tools menu (Open dialog box), Clear History, 17, 19 Tools menu (Save As dialog box), 18, 18 Tools menu (VB), References, 725 Tools menu (Word), Letters and Mailings, Mail Merge Wizard, 537 tooltips to display variable value, 712 for functions, 772 Top 10 filter, 349, 351 totals, creating, 56–57 touchpad for handwriting input, 37 tracing formulas visually, 164, 164–165 tracking routing of document, 616 trailing spaces, 170 trailing zeros, 70 formatting display of, 63 transparent color for graphics, 332 transposing data, Paste Special for, 112, 112 triangle indicator green for errors, 23 purple for smart tags, 23 TRIM function, 170–171 troubleshooting blank pages when printing, 83 formula errors, 159–167 circular references, 166–167 error codes, 159–161 with Formula Auditing toolbar, 161–165, 162 logical errors, 159 tracing visually, 164, 164–165 with Watch window, 165, 165 TRUNC function, 234 TWAIN standard, 336 Type, as financial function argument, 219 typeover for cell editing, 48 typing errors, AutoCorrect, 116–117
895
40012ndex.qxd 7/27/01 11:01 AM Page 896
896
ungrouping • video files, inserting or importing
U ungrouping drawing objects, 311–312 in outlines, 394–395 Unicode text, converting Excel worksheet to, 528 unions, 59 unprotecting worksheets, 441 unstacked 3D area chart, 267, 268 updating linked objects, 135, 532 UPPER function, 174 URLs for hyperlinks, 140 U.S. Census Bureau, 265 user data source, 501 user-defined functions, 696–702 as add-in, 705–706 basCalcHolidays function, 755–756 basCalcVacation function, 752–754 basCountWeekends function, 756 basYrsService function, 756 calling, 702 Count Weekends function, 700–702 including in worksheets, 702–706 Insert Function dialog box for, 704 names to store, 133 Years of Service function, 697–700 user information, removing from file properties, 783 user input, validating. See validation of data user interface AutoCorrect, reversing or disabling, 25 creating, 680–686 design, 677 Help, 20–21 macro design and, 656–657 new features, 4–5, 7–21 Open dialog box, 16–18, 17 personalized menus and toolbars, 14–16, 15 Places bar, customizing, 18–19 Save As dialog box, 16–18 smart tags, 21–23 task panes, 7–14 Advanced Search, 12–13, 13 Basic Search, 11, 11–14 Document Recovery, 19, 19–20 Insert Clip Art, 317 New Workbook, 8, 9, 429 Office Clipboard, 9–10, 10
UserForm, 680–682 adding controls, 683–686 default, 682 focus and loss of focus, 834–835 properties, 687 removing and restoring, 683 in Retirement Countdown application controls, 733–737 creating, 731–732, 732 design mode, 730 display for user, 738 properties, 732–733
V valid XML, 570 validation of data, 382–385 code for, 739–743 in templates, 433 testing code, 747–748 validation, using list, 468-469 #VALUE error, 160, 179 variable expenses in forecasting model, 589 variables in subroutines, 690 tooltips to display value, 712 variables in VBA, 796–803 assigning value, 803 converting data type, 799–800 creating, 801–803 declaration placement, 803 explicit declaration, 801–802 implicit declaration, 802 data subtypes, 798–800 names for, 794 naming conventions, 800–801 scope, 797 variant data type (VBA), 798 VBA. See also Visual Basic for Applications (VBA) VBAXL10.CHM file, 716 VBScript, 670 and ActiveX controls, 454 VDB function, 233 vector lookup, 208 Vector Markup Language (VML), 773–774 Venn diagrams, 312 vertical alignment of text, 91 video files, inserting or importing, 534
40012ndex.qxd 7/27/01 11:01 AM Page 897
View menu • Visual Basic How-To Topics
View menu Custom Views, 608 to hide and display task pane, 7 Page Break Preview, 84, 253 Report Manager, 609 Toolbars, 296 Customize, 657 Forms, 458 View menu (VB), Toolbars, Debug, 707 views as analysis tool, 608–609 reports to combine with worksheets and scenarios, 609–610 virtual meetings, 638–640 viruses, 649 macros and, 785 Visible property of application object, 726 of command bars, 762 of Worksheet object, 825 Visual Basic, 670 and ActiveX controls, 454 as event-driven language, 675–676 Hello World program, 678–692 application interface, 680–686 changing properties, 686–688 code, 688–691 Help for, 716–724, 717 information resources, 692–693 program development process, 676–678 sample application. See Retirement Countdown application troubleshooting, 691–692 what it is, 671–674 and XML, 572 Visual Basic Add-In Model, 718 Visual Basic Conceptual Topics, 717 Visual Basic Developers Guide, 714 Visual Basic for Applications (VBA), 644. See also macros comments, blank lines and indentation, 792–793 events, 828–832 Activate and Deactivate, 834–835 AddinInstall and AddinUninstall, 835–836 AfterRefresh and BeforeRefresh, 845 BeforeClose, 838 BeforeDoubleClick and BeforeRightClick, 839–841
BeforePrint, 845–846 BeforeSave, 846–847 Calculate, 836–837 Change, 837 DragOver and DragPlot, 838 FollowHyperlink, 841 MouseDown, MouseMove, and MouseUp, 842 NewSheet and NewWorkbook, 842–843 Open, 843 PivotTable, 843–845 SelectionChange and SeriesChange, 847–848 Windows, 848–849 Excel object model, 819–828, 820 Application object, 652, 726, 821, 832–833 Chart object, 825–828 Sheets collection, 822–828 Workbook object, 821–822 Worksheet object, 823–825 Worksheets collection, 822–828 naming rules, 797 operators, 806–807 programming structures, 808–819 conditional branching, 815–819 Do... loops, 810–813 For Each...Next loops, 809–810 For...Next loops, 808–809 If statements, 816–818 infinite loops, 814 nesting loops, 815 Select Case structure, 818–819 sequential structures, 808 While... Wend structures, 813 syntax, 793–805 collections, 794 constants, 795–796 events, 805 keywords, 794 methods, 795 objects, 794 procedures, 804–805 properties, 795 variables, 796–803 Visual Basic Help hyperlinks for additional information, 722 Index tab, 721 Object Browser, 723, 723–774 Visual Basic How-To Topics, 718
897
40012ndex.qxd 7/27/01 11:01 AM Page 898
898
Visual Basic Integrated Development Environment (IDE) • WordArt Gallery dialog box
Visual Basic Integrated Development Environment (IDE), 651, 651–656, 670, 672, 678–680, 679, 801 Code Editor window, 689, 689 code with errors, 692 Debugging toolbar and menu, 707–712 Visual Basic Language Reference, 718 Visual Basic Package Manager, 728 Visual Basic User Interface Help, 717 visual trace of errors, 164–165 VLOOKUP function, 204, 205, 206–207 VML (Vector Markup Language), 773–774 voice commands, 30–32 voice, for Text to Speech, 33–34 volatile function, 238
W Wacom, 37 Watch window, 165, 165 adding expressions, 711 in Visual Basic IDE, 679, 709–710 Web browser, Excel configuration to appear like, 442–448 Web Collections folder, 321 Web folders, 552–555 creating shortcut in Windows 98/NT 4.0, 554 creating shortcut in Windows 2000/Me, 552–554 saving files in, 554–555 Web Options dialog box, 773–775 Web pages. See also Office Web Components appending component to, 567 automatically republishing, 567–568 hyperlinks to, 139–140 worksheets as, 555–569 interactive, 557–566, 560 static, 555–556, 557 web parts, 569 Web queries, 573–575 importing from, 491 Web Query Options dialog box, 574, 574–575 websites. See also SharePoint Team Services about Exchange Conferencing Server, 639 about NetMeeting, 639 about SharePoint, 638 about Visual Basic, 693 for Clip Organizer, 327, 328 Gantt chart creation method, 265
Knowledge Base, 719 Office Developers site, 860 U.S. Census Bureau, 265 weekday, determining for date, 194–195 WEEKDAY function, 187, 194–195 weekends, functions to exclude, 191–194 well-formed XML, 570 What If tools. See analysis tools wheel mouse, 46 While... Wend structures, 813 white space, in programming code, 689 WIA (Windows Image Acquisition), 336 width of columns, 97, 101–102 wildcards in filter criteria, 352, 358 in Find and Replace, 51 for SEARCH function, 175 Window menu Arrange, 134 Freeze Panes, 104 New Window, 134 Remove Split, 105 Split, 105 Unhide, 649 WindowActivate event (VBA), 822, 832 WindowDeactivate event (VBA), 832 WindowResize event (VBA), 832 windows command button to close, 674 display options, 769 Windows 98/NT 4.0, creating Web folder shortcut, 554 Windows 1900 date system, 65 Windows 2000/Me, creating Web folder shortcut, 552–554 Windows API functions, 714 Windows event (VBA), 848–849 Windows Image Acquisition (WIA), 336 Windows Media Player, 534 Windows Media Services, for virtual meetings, 638 Windows system tray, Clipboard icon, 9, 10 Word and Excel, 537–538 inserting files in, 533 to open corrupt Excel file, 789 word wrap in text boxes, 303 WordArt, 303–304 toolbar, 305 WordArt Gallery dialog box, 304
40012ndex.qxd 7/27/01 11:01 AM Page 899
WordPerfect, moving tables to Excel from • worksheets
WordPerfect, moving tables to Excel from, 546 Workbook object in Excel object model, 821–822 WorkbookActivate event (VBA), 829 WorkbookAddInInstall event (VBA), 829 WorkbookAddInUninstall event (VBA), 829 WorkbookBeforeClose event (VBA), 829 WorkbookBeforePrint event (VBA), 829 WorkbookBeforeSave event (VBA), 830 WorkbookDeactivate event (VBA), 830 WorkbookNewSheet event (VBA), 831 WorkbookOpen event (VBA), 831 WorkbookPivotTableOpenConnection event (VBA), 831 workbooks, 42. See also templates AutoRecover, 776–777 closing, 40 collaboration. See also workgroups copying data between, 108 copying styles between, 100–101 data recovery from corrupted, 787–789 hyperlinks to, 140 macros stored in, 646 opening existing, 7 those containing macros, 649–651 in Word, 538 protecting, 435–436 repairing damaged, 19–20 republishing to Web when saving, 567–568 saving on Web folders, 554–555 as XML, 571–572 templates vs., 431 unhiding, 649 views for, 608–609 Workbooks(index) property of Workbook object, 821 WORKDAY function, 187, 191–194 workgroups, 612–627 e-mailing workbooks, 612–613, 613 new features, 6 routing workbooks, 613–616 sharing workbooks, 617–623 conflict resolution, 621 highlighting changes, 619 merging changes, 622 protecting for merging, 622–623 saving workbooks to Exchange folder, 626–627
Send for Review, 623–626 viewing change history, 620 Worksheet object in Excel object model, 823–825 worksheets, 42, 120–123. See also cell entries; columns in worksheets; outlines; rows in worksheets automatic and manual calculation, 167–168 for charts, 251–252, 293 color of tab, 120 components, 44, 44 configuration like Web page, 442–448, 444 consolidating, 416–419 converting to Access database, 486–489 copying and moving, 122–123 copying data between, 108 creating for nonusers, 442–448 as database, 341–342 entering common data in multiple, 121–122 form controls on, 458–472 formatting for Text to Speech use, 34–35 formatting layout, 101–113 column width and row height, 101–103 freezing, splitting and hiding, 104–105 hiding rows and columns, 105 inserting and deleting cells, 106 inserting and deleting rows and columns, 103–104 moving and copying cell contents, 106–109 zoom, 101 hiding, 825 hiding in templates, 434–435 inserting and deleting, 123–124 inserting graphics, 330–334 from other sources, 335–336 inserting in Word document, 533 layers, 155 linking and embedding in, 531–532 maximum size, 44 names to span, 130–131 printing, 73–74 margin adjustment, 75, 76 options, 84–85 page breaks, 84–85 page setup, 76–82 Print Preview, 74, 75 tips and tricks, 83 protecting, 436–441 publishing on the Web, 555–569
899
40012ndex.qxd 7/27/01 11:01 AM Page 900
900
Worksheets collection in Excel object model • zoom
reports to combine with views and scenarios, 609–610 reviewing structure for outlining, 392–393 selecting, 121 selecting entire, 49 selecting for printing, 83 spelling check, 113–115 splitting window, 104–105 ungrouping, 122 unprotecting, 441 Worksheets collection in Excel object model, 822–828 Worksheets(index) property of Worksheets collection, 823 World Wide Web Consortium, 569 wrapping text, 93
X x-axis in chart, 245 XLM macro sheets, 455 .xls file extension, 431 .xlt file extension, 431 XML (Extensible Markup Language), 569–572 opening files in Excel 2002, 571 saving workbooks as, 571–572 for smart tag list file, 862–865 XOr operator in VBA, 807 XY charts, 272, 273
Y y-axis in chart, 245 YEAR function, 187, 189, 195 Years of Service user-defined function, 697–700
Z zip codes database, 852 formatting, 68 zoom, 101 IntelliMouse and, 772