SECOND EDITION EXCEL HACKS TM David and Raina Hawley Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo Excel Hacks™ by David and Raina Hawley Copyright © 2007 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 [email protected]. Editors: Brian Sawyer and Brian Jepson Indexer: Tolman Creek Design Technical Editor Tom Sgouros Cover Designer: Hanna Dyer Production Editor: Adam Witwer Interior Designer: David Futato Copyeditor: Derek Di Matteo Illustrators: Robert Romano Proofreader: Tolman Creek Design and Jessamyn Read Printing History: March 2004: First Edition. June 2007: Second Edition. NutshellHandbook,theNutshellHandbooklogo,andtheO’Reillylogoareregisteredtrademarks of O’Reilly Media, Inc. TheHacks series designations,Excel Hacks, the image of a trowel, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimedastrademarks.Wherethosedesignationsappearinthisbook,andO’ReillyMedia,Inc.was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. Small print:The technologies discussed in this publication, the limitations on these technologies thattechnologyandcontentownersseektoimpose,andthelawsactuallylimitingtheuseofthese technologies are constantly changing. Thus, some of the hacks described in this publication may notwork,maycauseunintendedharmtosystemsonwhichtheyareused,ormaynotbeconsistent withapplicableuseragreements.Youruseofthesehacksisatyourownrisk,andO’ReillyMedia, Inc.disclaimsresponsibilityforanydamageorexpenseresultingfromtheiruse.Inanyevent,you should take care that your use of these hacks does not violate any applicable laws, including copyright laws. This book uses RepKover™, a durable and flexible lay-flat binding. ISBN-10: 0-596-52834-5 ISBN-13: 978-0-596-52834-8 [M] Contents Credits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv Chapter1. Reducing Workbook and Worksheet Frustration . . . . . . . . . . . . . 1 1.Create a Personal View of Your Workbooks 5 2.Enter Data into Multiple Worksheets Simultaneously 8 3.Prevent Users from Performing Certain Actions 11 4.Prevent Seemingly Unnecessary Prompts 15 5.Hide Worksheets So That They Cannot Be Unhidden 19 6.Customize the Templates Dialog and Default Workbook 21 7.Create an Index of Sheets in Your Workbook 23 8.Limit the Scrolling Range of Your Worksheet 26 9.Lock and Protect Cells Containing Formulas 30 10.Find Duplicate Data Using Conditional Formatting 34 11.Find Data That Appears Two or More Times Using Conditional Formatting 35 12.Tie Custom Toolbars to a Particular Workbook 36 13.Outsmart Excel’s Relative Reference Handler 38 14.Remove Phantom Workbook Links 39 15.Reduce Workbook Bloat 42 16.Extract Data from a Corrupt Workbook 45 Chapter2. Hacking Excel’s Built-in Features. . . . . . . . . . . . . . . . . . . . . . . . . 48 17.Validate Data Based on a List on Another Worksheet 48 18.Control Conditional Formatting with Checkboxes 50 vii 19.Identify Formulas with Conditional Formatting 54 20.Count or Sum Cells That Meet Conditional Formatting Criteria 56 21.Highlight Every Other Row or Column 58 22.Create 3-D Effects in Tables or Cells 60 23.Turn Conditional Formatting and Data Validation On and Off withaCheckbox 62 24.Support Multiple Lists in a ComboBox 64 25.Create Validation Lists That Change Based on a Selection from Another List 66 26.Use Replace... to Remove Unwanted Characters 68 27.Convert Text Numbers to Real Numbers 68 28.Extract the Numeric Portion of a Cell Entry 70 29.Customize Cell Comments 71 30.Sort by More Than Three Columns 73 31.Random Sorting 74 32.Manipulate Data with the Advanced Filter 75 33.Create Custom Number Formats 79 34.Add More Levels of Undo to Excel for Windows 84 35.Create Custom Lists 84 36.Boldface Excel Subtotals 85 37.Convert Excel Formulas and Functions to Values 89 38.Automatically Add Data to a Validation List 91 39.Hack Excel’s Date and Time Features 94 40.Enable Grouping and Outlining on a Protected Worksheet 98 41.Prevent Blanks/Missing Fields in a Table 100 42.Provide Decreasing Data Validation Lists 101 43.Add a Custom List to the Fill Handle 102 Chapter3. Naming Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 44.Address Data by Name 105 45.Use the Same Name for Ranges on Different Worksheets 106 46.Create Custom Functions Using Names 108 47.Create Ranges That Expand and Contract 112 48.Nest Dynamic Ranges for Maximum Flexibility 118 49.Identify Named Ranges on a Worksheet 121 viii | Contents Chapter4. Hacking PivotTables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 50.PivotTables: A Hack in Themselves 124 51.Share PivotTables but Not Their Data 129 52.Automate PivotTable Creation 131 53.Move PivotTable Grand Totals 135 54.Efficiently Pivot Another Workbook’s Data 137 Chapter5. Charting Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 55.Explode a Single Slice from a Pie Chart 140 56.Create Two Sets of Slices in One Pie Chart 142 57.Create Charts That Adjust to Data 144 58.Interact with Your Charts Using Custom Controls 148 59.Four Quick Ways to Update Your Charts 152 60.Hack Together a Simple Thermometer Chart 157 61.Create a Column Chart with Variable Widths and Heights 160 62.Create a Speedometer Chart 164 63.Link Chart Text Elements to a Cell 171 64.Hack Chart Data So That Empty or FALSE Formula Cells Are NotPlotted 173 65.Add a Directional Arrow to the End of a Line Series 175 66.Place an Arrow on the End of a Horizontal (X) Axis 177 67.Correct Narrow Columns When Using Dates 180 68.Position Axis Labels 181 69.Tornado Chart 184 70.Gauge Chart 186 71.Conditional Highlighting Axis Labels 188 72.Create Totals on a Stacked Column Chart 190 Chapter6. Hacking Formulas and Functions . . . . . . . . . . . . . . . . . . . . . . . . 193 73.Add Descriptive Text to Your Formulas 193 74.Move Relative Formulas Without Changing References 194 75.Compare Two Excel Ranges 195 76.Fill All Blank Cells in a List 197 77.Make Your Formulas Increment by Rows When You Copy AcrossColumns 199 78.Convert Dates to Excel Formatted Dates 202 Contents | ix 79.Sum or Count Cells While Avoiding Error Values 203 80.Reduce the Impact of Volatile Functions on Recalculation 205 81.Count Only One Instance of Each Entry in a List 206 82.Sum Every Second, Third, or Nth Row or Cell 208 83.Find the Nth Occurrence of a Value 210 84.Make the Excel Subtotal Function Dynamic 212 85.Add Date Extensions 214 86.Convert Numbers with the Negative Sign on the Right toExcelNumbers 215 87.Display Negative Time Values 217 88.Use the VLOOKUP Function Across Multiple Tables 219 89.Show Total Time As Days, Hours, and Minutes 221 90.Determine the Number of Specified Days in Any Month 222 91.Construct Mega-Formulas 224 92.Hack Mega-Formulas that Reference Other Workbooks 226 93.Hack One of Excel’s Database Functions to Take the Place ofManyFunctions 227 94.Extract Specified Words from a Text String 233 95.Count Words in a Cell or Range of Cells 234 96.Return a Worksheet Name to a Cell 236 97.Sum Cells with Multiple Criteria 239 98.Count Cells with Multiple Criteria 243 99.Calculate a Sliding Tax Scale 246 100.Add/Subtract Months from a Date 251 101.Find the Last Day of Any Given Month 253 102.Calculate a Person’s Age 255 103.Return the Weekday of a Date 256 104.Evaluate a Text Equation 258 105.Lookup from Within a Cell 259 Chapter7. Macro Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 106.Speed Up Code While Halting Screen Flicker 263 107.Run a Macro at a Set Time 264 108.Use CodeNames to Reference Sheets in Excel Workbooks 266 109.Connect Buttons to Macros Easily 267 110.Create a Workbook Splash Screen 268 x | Contents 111.Display a “Please Wait” Message 270 112.Have a Cell Ticked or Unticked upon Selection 271 113.Count or Sum Cells That Have a Specified Fill Color 273 114.Add the Microsoft Excel Calendar Control to Any Excel Workbook 274 115.Password-Protect and Unprotect All Excel Worksheets inOneFellSwoop 276 116.Retrieve a Workbook’s Name and Path 279 117.Get Around Excel’s Three-Criteria Limit for Conditional Formatting 280 118.Run Procedures on Protected Worksheets 282 119.Distribute Macros 283 120.Delete Rows Based on a Condition 289 121.Track and Report Changes in Excel 293 122.Automatically Add Date/Time to a Cell upon Entry 297 123.Create a List of Workbook Hyperlinks 298 124.Advanced Find 300 125.Find a Number Between Two Numbers 306 126.Convert Formula References from Relative to Absolute 310 127.Name a Workbook with the Text in a Cell 315 128.Hide and Restore Toolbars in Excel 316 129.Sort Worksheets 319 130.Password-Protect a Worksheet from Viewing 320 131.Change Text to Upper- or Proper Case 322 132.Force Text to Upper- or Proper Case 324 133.Prevent Case Sensitivity in VBA Code 328 134.Display AutoFilter Criteria 329 Chapter8. Cross-Application Hacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 135.Import Data from Access 2007 into Excel 2007 331 136.Retrieve Data from Closed Workbooks 336 137.Automate Word from Excel 344 138.Automate Outlook from Excel 349 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Contents | xi 0 Credits About the Authors David and Raina Hawley provide business applications, software, develop- ment,consultancy,training,andtutoringinallaspectsofExcelandVBAfor Excel through OzGrid Business Applications in Western Australia. David Hawley has spent the last 15 years creating business applications using Excel and VBA for Excel on a day-to-day basis. He produces a monthlynewslettercontaininginformationontheuseofExcelandVBAfor Excel. He runs and maintains one of the largest Excel forums in the world on the OzGrid web site. Raina Hawley lectures in industry and in the college education system, and isaregisteredworkplaceassessor.RainarunstheOzGridoffice,administra- tion,consultancy,development,andtrainingsideofthebusiness,andworks in Excel solutions alongside her husband. David and Raina offer hundreds of Excel Add-Ins and business software designed for data analysis in all industry areas through their web site at http://www.ozgrid.com. The web site contains over 50,000 pages of free Excelinformation.TheyliveinBunbury,WesternAustralia,withtheirtwo children. Contributors The following people contributed their hacks, writing, and inspiration to this book: • Andy Pope is a programmer working in London. He has been using computerssincethemid’80s.Hiscurrentroleinvolveswritingcustom- izedsolutionsforreportingprojectsutilizingtheMSOfficeproductsvia VBA. Andy also runs his own web site (http://www.andypope.info). His xiii contributions to the Excel community have been recognized by Microsoft, which has awarded Andy with MVP status for the past four years. • DennisWallentinhasbeenworkingasanindependentExcelconsultant sincethelate’80s.HeutilizesMSExcelandothertoolstodeveloppro- fessionalsolutionsforallsizesofcompanies,includingthepublicsector both in Sweden and internationally. He is currently focused on Visual Studio Tools for Office System (VSTO). Dennis has a Masters in Busi- ness and Management Accounting. He runs an English web site (http:// www.excelkb.com) and a blog (http://xldennis.wordpress.com). Acknowledgments First and foremost, we would like to thank our parents, Walter and Beryl Fenlon and Mike and Marlene Hawley, for without their love and support, we never would have made it through. Thanks must also go to the team at O’Reilly, first and foremost Brian Saw- yer, for all the hard work that he has put into this book. Andy Pope and DennisWallentinmustbethankedalsoforthehacks theycontributed,and wehavetomentionallthevisitorstoourwebsiteandforum,whohelpedus to identify some of the most common issues that people face. We would also like to say a special thanks to all moderators and Oz MVPs on our free Q/A forum who share their time and knowledge in such an unselfishway.Finally,wemustthankAleishaandKate,asalways,ourinspi- ration.Theirunderstandingandextraeffortstobegoodwhilethebookwas in progress will be remembered!! xiv | Credits 0 Preface Millions of Microsoft Excel users are busy creating and sharing spread- sheetseveryday.Indeed,thespreadsheethasgrownfromapowerfulconve- niencetoatransformativefoundationformanybusinesses,drivingdecision- making around the planet. AlthoughExcelisacriticaltool,manyExcelusersknowonlyaboutasubset of its functionality. They utilize the pieces they need, often reusing more complex pieces from existing templates, and don’t dive too deeply into everything Excel has to offer. Odds are good that no single user actually needs every feature in Excel, so this approach is pretty reasonable. At the same time, though, it means a lot of people never get far enough along the learning curve to see the techniques they can use to make their work much easier. WiththereleaseofMSOffice2007comesanewversionofExcel.Thereare many changes with Excel 2007, the most obvious being the new user inter- face.Theintroductionoftheribbonprovidesaresults-orientedinterfacethat presents tools when you need them, in a clear and organized fashion. The sizeofaspreadsheethasalsobeengreatlyincreased,withthenumberofcol- umns now well over 16,000 and the number of rows over 1,000,000. The total amount of memory that Excel can use has also been increased and is limited only by the maximum available memory Windows will allow on your PC. Other improvements include easier use of PivotTables, conditional format- ting and named ranges, live visual previews, predefined style galleries, table formats, and SmartArt graphics allowing you to use more complicated graphics in your spreadsheets. As most of us are usually required to work acrossarangeofapplications,shareworkbooks,andconnectwiththeWeb, Excel 2007 makes this much more user-friendly and easy to manage. xv