excel tips 2008

514
ExcelTips 2008 Compiled from the pages of ExcelTips, your free weekly productivity newsletter

Upload: civilgoa

Post on 14-Aug-2015

35 views

Category:

Data & Analytics


1 download

TRANSCRIPT

Page 1: Excel tips 2008

ExcelTips 2008

Compiled from the pages of ExcelTips, your free weekly productivity newsletter

Page 2: Excel tips 2008

ExcelTips 2008

Published by:

Sharon Parq Associates, Inc. PO Box 794 Orem, UT 84059

All contents copyright © 1999–2009 by Sharon Parq Associates, Inc., All rights reserved. No part of this document or the related files may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher.

Produced and published in the United States of America

Revision history:

7 January 2009: First published

Limit of Liability and Disclaimer of Warranty: The publisher has used its best efforts in preparing this book, and the information provided herein is provided “as is.” Sharon Parq Associates, Inc., makes no representation or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaims any implied warranties of merchantability or fitness for any particular purpose and shall in no event be liable for any loss of profit or any other commercial damage, including but not limited to special, incidental, consequential, or other damages.

Trademarks: This book identifies product names and services known to be trademarks, registered trademarks, or service marks of their respective holders. They are used throughout this book in an editorial fashion only. In addition, terms suspected of being trademarks, registered trademarks, or service marks have been appropriately capitalized, although Sharon Parq Associates, Inc., cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark, registered trademark, or service mark. Sharon Parq Associates, Inc., is not associated with any product or vendor mentioned in this book.

Page 3: Excel tips 2008

Table of Contents

Introduction 1 WHAT’S IN THIS E-BOOK? 1 WHAT ABOUT VIRUSES? 1 NEED MORE TIPS? 2 A SPECIAL NOTE OF THANKS 2 SHARING THIS DOCUMENT 2

General Tips 4 I HATE THE EXCEL 2007 USER INTERFACE 4 CANCELING A COMMAND 5 ARRANGING WORKBOOK WINDOWS 5 STARTING IN SAFE MODE 6 EXCLUDING A SPECIFIC ADD-IN AT STARTUP 7 DISABLING EXCEL'S HELP SYSTEM 8 WHERE IS THAT NAME? 10 TURNING OFF NAMES 10 REFUSING ONLINE HELP 10 TURNING OFF DYNAMIC MENUS 12 ANIMATED MENUS 13 TURNING OFF ERROR CHECKING 13 A SHORTCUT FOR SWITCHING FOCUS 15 ACTIVATING THE FORMULA BAR WITH THE KEYBOARD 16 LIMITING WHAT IS SHOWN IN THE FORMULA BAR 18 ENLARGING THE FORMULA BAR 19 TURNING OFF SCREENTIPS 21 SIMULTANEOUS SCROLLING 23 REMOVING PERSONAL INFORMATION 24 CLEARING LARGE CLIPBOARD ENTRIES 25 CHANGING ERROR CHECKING RULES 26 FORCING MANUAL CALCULATION FOR A WORKBOOK 27 MAKING AUTOCOMPLETE WORK FOR AN ENTIRE COLUMN 28 EXCEL PROFICIENCY TESTING 29 SELECTED CELLS NOT SHADED 29 PROBLEM WITH MISSING CONTEXT MENU OPTION 30 CHANGING THE SHORTCUT MENU 31 ALWAYS OPEN AT 100% ZOOM 32 COUNTERING COMPRESSED COLUMNS 33 CHANGING HORIZONTAL ORIENTATION 34 TAB KEY WON'T MOVE FROM CELL TO CELL IN LOCKED WORKSHEET 35 TURNING HEADERS ON AND OFF 36

ExcelTips 2008 Page iii

Page 4: Excel tips 2008

MAKING COLUMN HEADERS VERTICALLY WIDER 37 FORCING STUBBORN RECALCULATION 39 VIEWING SAME CELLS ON DIFFERENT WORKSHEETS 39 BACKING UP CUSTOM DICTIONARIES 41 DISABLING A FUNCTION KEY 43 SIMPLIFYING THE FONT LIST 43 SHORTCUT FOR VIEWING FORMULAS 44

Editing Tips 45 CREATING NEW WINDOWS 45 CANCELING AN EDIT 45 QUICKLY SELECTING CELLS 46 SELECTING NONCONTIGUOUS RANGES WITH THE KEYBOARD 46 DISPLAYING A HIDDEN FIRST ROW 47 COPYING BETWEEN INSTANCES OF EXCEL 48 PASTING WITHOUT UPDATING REFERENCES 50 CONVERTING FROM RELATIVE TO ABSOLUTE 51 INSERTING AND COPYING ROWS 52 MOVING AND SELECTING ROWS 52 ENTERING NUMBERS IN EXCEL 54 ENTERING INFO INTO MULTIPLE CELLS 55 LIMITING ENTRIES TO NUMERIC VALUES 55 LIMITING INPUT TO A FORMAT 57 DEALING WITH LONG FORMULAS 59 TRANSPOSING YOUR DATA 60 DRAGGING TO CLEAR CELLS 61 DELETING BLANK COLUMNS 61 CONDITIONALLY DELETING ROWS 63 ADDING POP-UP DOCUMENTATION TO A CELL 64 CORRECTING A CAPITAL MISTAKE 66 MODIFYING PROPER CAPITALIZATION 67 SELECTING FORMULAS 69 DELETING EVERYTHING EXCEPT FORMULAS 70 GETTING RID OF EVERYTHING EXCEPT NUMBERS 72 RANGES ON MULTIPLE WORKSHEETS 74 EDITING THE SAME CELL IN MULTIPLE SHEETS 75 UNDERSTANDING AUTOCOMPLETE 75 QUICKLY FILLING A COLUMN 77 FAST AUTOFILL 77 AUTOFILL WON'T WORK AS EXPECTED 78 TURNING OFF AUTOFILL FOR A WORKBOOK 79 FINDING UNUSED NAMES 79 ADJUSTING FORMULAS WHEN PASTING 81 UNWANTED DATA CHANGES 82

ExcelTips 2008 Page iv

Page 5: Excel tips 2008

TURNING OFF AUTOMATIC CAPITALIZATION 83 ENSURING UNIQUE VALUES IN A COLUMN 84 PUTTING ADDRESSES ON STATE-SPECIFIC WORKSHEETS 85 DELETING OLD DATA FROM A WORKSHEET 88 WORKING IN FEET AND INCHES 89 SHORTENING ZIP CODES 90 FORMATTING CANADIAN POSTAL CODES 92 DIVIDING VALUES 92 AUTOMATICALLY PROTECTING AFTER INPUT 94 SCROLL WHEEL DOESN'T WORK WHEN EDITING IN EXCEL 2007 94 TYPING CHECK MARKS INTO EXCEL 96 RETAINING FORMATTING AFTER A PASTE MULTIPLY 97 INSERTING A RADICAL SYMBOL 99 EASILY CHANGING LINKS 99 UPDATING LINKS IN COPIED FILES 100 COPYING A HYPERLINK TO LOTS OF WORKSHEETS 102 REMOVING SPACES 103 CONTINGENT VALIDATION LISTS 103 REFERENCING THE LAST CELL IN A COLUMN 105 COUNTING WORDS 106 GETTING HELP WHEN ENTERING FUNCTIONS 107 AUTOMATICALLY BREAKING TEXT 108 CHECKING FOR AN ENTRY IN A CELL 108 CONCATENATING RANGES OF CELLS 109 CONVERTING TEXT TO VALUES 111 USING SLASHED ZEROES 113 COMBINING MULTIPLE ROWS IN A COLUMN 113 ERRORS WHEN COPYING REFERENCES TO EXTERNAL CELLS 114 DELETING ALL NAMES BUT A FEW 115 TURNING OFF INSERT OPTIONS 116 TURNING OFF PASTE OPTIONS 117 SYMBOLS CONVERT TO NUMBERS IN EXCEL 119 USING SUBTOTALS AND TOTALS 120 COPYING SUBTOTALS 121 WILDCARDS IN 'REPLACE WITH' TEXT 123

Formatting Tips 126 NUMBER FORMATTING SHORTCUTS 126 UNABLE TO FORMAT CELLS 126 CHANGING FONT SIZE USING A SHORTCUT KEY 127 NOTATION FOR THOUSANDS AND MILLIONS 128 ALTERING THE DISPLAYED FORMAT OF NUMBERS TO THE NEAREST 100 129 USING AN EXACT NUMBER OF DIGITS 129 FORMATTING CURRENCY 130

ExcelTips 2008 Page v

Page 6: Excel tips 2008

FILLING A CELL 131 FILL COLOR DOESN'T DISPLAY 133 REFERENCING EXTERNAL CELL COLORS 134 SETTING VERTICAL ALIGNMENT 135 USING STRIKETHROUGH FORMATTING 136 DRAWING BORDERS 137 ADDING DIAGONAL BORDERS 138 PARTIALLY BLOCKING SOCIAL SECURITY NUMBERS 140 ADDING DROP SHADOWS TO CELLS 141 UNHIDING A SINGLE COLUMN 142 CONVERTING FROM NUMBERS TO TEXT 143 CONVERTING FORCED TEXT TO NUMBERS 145 HIGHLIGHTING CELLS CONTAINING SPECIFIC TEXT 147 SETTING CELL WIDTH AND HEIGHT USING THE KEYBOARD 150 USING FRACTIONAL NUMBER FORMATS 152 SELECTING A PAPER SIZE 153 HIDING ROWS BASED ON TWO VALUES 154 ADJUSTING CELL MARGINS FOR MORE WHITE SPACE 156 USING AUTOFORMAT 157 MAKING ALL OCCURRENCES BOLD 159

Conditional Formatting Tips 163 COPYING CONDITIONAL FORMATTING 163 PROTECTING CONDITIONAL FORMATTING 164 SORTING OR FILTERING BY CONDITIONAL FORMAT RESULTS 165 APPLYING CONDITIONAL FORMATTING TO MULTIPLE WORKSHEETS 165 CHANGING FONT FACE AND SIZE CONDITIONALLY 166 SHADING BASED ON ODDS AND EVENS 168

Header and Footer Tips 171 DYNAMIC HEADERS AND FOOTERS 171 USING A DIFFERENT FOOTER ON SECONDARY PAGES 172 PUTTING A DIFFERENT DATE IN A HEADER 173 PRINTING A MULTI-LINE FOOTER 174 USING COLOR IN HEADERS AND FOOTERS 174 ADDING AMPERSANDS IN HEADERS AND FOOTERS 175 LEADING ZEROS IN PAGE NUMBERS 175 HEADER AND FOOTER BACKGROUND COLOR 176

Online Tips 179 TURNING OFF HYPERLINK ACTIVATION 179 TYING A HYPERLINK TO A SPECIFIC CELL 181 DROP-DOWN LIST OF HYPERLINKS 182

ExcelTips 2008 Page vi

Page 7: Excel tips 2008

CHANGING PORTIONS OF MANY HYPERLINKS 183 REMOVING HYPERLINKS WITHOUT A MACRO 184 REMOVING HYPERLINKS WITHOUT A MACRO 185 GETTING RID OF MANY HYPERLINKS 186 GETTING RID OF ALL HYPERLINKS 186 AUTOMATIC TEXT IN AN E-MAIL 187 LINKING TO A SPECIFIC PAGE IN A PDF FILE 188 SETTING WEB FONTS 189 SPECIFYING YOUR TARGET MONITOR 192

Worksheet Tips 195 VIEWING TWO WORKSHEETS AT ONCE 195 REFERENCING WORKSHEET TABS 196 QUICKLY COPYING WORKSHEETS 197 DISABLING MOVING BETWEEN WORKSHEETS 197 PREVENTING SOMEONE FROM RECREATING A PROTECTED WORKSHEET 198 CHANGING THE COLOR OF WORKSHEET GRIDLINES 200 LOCKING WORKSHEET NAMES 201 SWITCHING HEADERS IN A FROZEN ROW 202 PROTECTING WORKSHEETS FROM DELETION 205 PROTECTING A WORKSHEET'S FORMAT 205 IDENTIFYING THE LAST CELL CHANGED IN A WORKSHEET 207

Worksheet Function Tips 209 RETURNING A WORKSHEET NAME 209 GETTING THE NAME OF THE PARENT WORKBOOK 209 LARGE NUMBERS IN THE MOD FUNCTION 210 RETURNING A WEIGHT AND A DATE 212 COUNTING DISPLAYED CELLS 213 FINDING THE LOWEST NUMBERS 214 ROUNDING TO POWERS OF 10 215 CHECKING FOR TEXT 216 ROUNDING NUMBERS 216 USING THE MROUND WORKSHEET FUNCTION 217 SUMIF DOESN'T RECALC AUTOMATICALLY 217 CELL AND NAME REFERENCES IN COUNTIF 220 USING THE INT WORKSHEET FUNCTION 221 USING THE TRUNC WORKSHEET FUNCTION 221 RETURNING BLANKS WITH VLOOKUP 222 RETURNING BLANKS OR ASTERISKS FROM A LOOKUP 223

Formula Tips 225 EVALUATING FORMULAS 225

ExcelTips 2008 Page vii

Page 8: Excel tips 2008

EXACT FORMULA COPIES 226 IGNORING CASE IN A COMPARISON 227 SUMMING BASED ON FORMATTING IN ADJACENT CELLS 227 FINDING THE NTH OCCURRENCE OF A CHARACTER 230 DETERMINING BUSINESS QUARTERS FROM DATES 231 SUMMING ONLY POSITIVE VALUES 232 ERRORS WHEN SUBTRACTING 233 FINDING THE FIRST NON-DIGIT IN A TEXT VALUE 235 REFERENCING THE LAST SIX ITEMS IN A FORMULA 237 COUNTING CELLS ACCORDING TO CASE 237 STOPPING A FORMULA FROM UPDATING REFERENCES 240 CALCULATING THE MEDIAN AGE OF A GROUP OF PEOPLE 241 GENERATING DOUBLE-DIGIT RANDOM NUMBERS 241 EXCLUDING VALUES FROM AVERAGING 242 RETURNING LEAST-SIGNIFICANT DIGITS 244 ROUNDING TO THE NEAREST EVEN INTEGER 244 PULLING FORMULAS FROM A WORKSHEET 245 FIGURING OUT THE LOW-SCORE WINNER 250 DETERMINING WINNERS, BY CATEGORY 251 REPLACING DASHES WITH PERIODS 252 INCREMENTING NUMERIC PORTIONS OF SERIAL NUMBERS 253 COUNTING NON-BLANK CELLS 254 COUNTING UNIQUE VALUES 254 COUNTING CONSECUTIVE NEGATIVE NUMBERS 255 COUNTING WINS AND LOSSES 257 COUNTING ONLY MONEY WINNERS 258 LAST NON-ZERO VALUE IN A ROW 259 GETTING THE NAME OF THE WORKSHEET INTO A CELL 260 DETERMINING IF A VALUE IS OUT OF LIMITS 262 SEARCHING FOR A VALUE USING A FUNCTION 263 CALCULATING FUTURE WORKDAYS 265 REVERSING NAMES IN PLACE 266 CELL ADDRESS OF A MAXIMUM VALUE 267 FINDING COLUMNS OF A CERTAIN WIDTH 268 DETERMINING COMBINATIONS TO MAKE A TOTAL 269 CONDENSING SEQUENTIAL VALUES TO A SINGLE ROW 272 SUMMING DIGITS IN A VALUE 273 GENERATING RANDOM STRINGS OF CHARACTERS 275 DEALING WITH CIRCULAR REFERENCES 277

PivotTable Tips 278 TEXT TRUNCATED IN PIVOTTABLE 278 SUPPRESSING ZERO VALUES IN PIVOTTABLES 278 BOGGING DOWN WITH CALCULATED ITEMS 279

ExcelTips 2008 Page viii

Page 9: Excel tips 2008

Sorting and Filtering Tips 280 SORTING A RANGE OF CELLS 280 SORTING DECIMAL VALUES 281 SORTING BY FILL COLOR 282 FIXING ODD SORTING BEHAVIOR 284 DETERMINING SORTING CRITERIA 285 FILTERING TO A DATE RANGE IN THE PAST 287 FILTERING FOR COMMENTS 288 COUNTING FILTERED ROWS 289 PERFORMING CALCULATIONS WHILE FILTERING 290

Comment Tips 291 EDITING COMMENTS 291 ADDING A COMMENT TO MULTIPLE CELLS 291 PASTING A COMMENT INTO YOUR WORKSHEET 292 COPYING COMMENTS TO CELLS 293 PLACING FORMULA ANSWERS IN A COMMENT 294 LINKING COMMENTS TO MULTIPLE CELLS 296 FINDING AND REPLACING TEXT IN COMMENTS 297

Date and Time Tips 299 HOW EXCEL STORES DATES AND TIMES 299 CONVERTING TIME NOTATION TO DECIMAL NOTATION 299 CHANGING EXCEL’S STARTING DATE 300 INSERTING THE CURRENT TIME WITH SECONDS 302 ENTERING LARGE TIME VALUES 303 USING EARLY DATES 304 ROUNDING TIME 305 DATES WITH PERIODS 305 USING EXCEL FOR TIMING 307 WORKING WITH ELAPSED TIME 308 DISPLAYING NEGATIVE TIMES 310 ENTERING DATES WITHOUT SEPARATORS 312 ENTERING OR IMPORTING TIMES WITHOUT COLONS 315 MODIFYING DEFAULT YEAR FOR DATES 316 COUNTING DATES IN A RANGE 318 DAYS LEFT IN THE YEAR 319 FORCING DATES FORWARD 320 AUTOMATICALLY ADVANCING BY A MONTH 320 EVERY SECOND TUESDAY 322 IS DAYLIGHT SAVINGS TIME IN EFFECT? 323 CONVERTING EUROPEAN DATES TO US DATES 325 CONVERTING UNIX DATE/TIME STAMPS 328

ExcelTips 2008 Page ix

Page 10: Excel tips 2008

CONVERTING UTC TIMES TO LOCAL TIMES 329

Graphics Tips 330 RESIZE GRAPHICS OUTSIDE OF EXCEL 330 PUTTING A GRAPHIC IN A HEADER OR FOOTER 331 SPECIFYING AN ORDER FOR DRAWING OBJECTS 332 INSERTING A WATERMARK BEHIND MERGED CELLS 333 SETTING DEFAULT ATTRIBUTES FOR LINES AND ARROWS 334 USING WORDART IN EXCEL 335 PICTURES IN AUTOSHAPES 337 ADDING TEXT TO AN AUTOSHAPE 340 PLACING TEXTBOX TEXT INTO A WORKSHEET 341 TAKING A PICTURE 342 GETTING RID OF FIXED OBJECTS 343 PIXELS IN A TEXT STRING 344 HIDING GRAPHICS WHEN FILTERING 345

Charting Tips 347 FORMATTING AXIS PATTERNS 347 FORMATTING THE BORDER OF A LEGEND 349 SELECTING FONTS FOR A CHART 351 USING GRAPHICS TO REPRESENT DATA SERIES 353 USING THE MOUSE TO ADJUST YOUR VIEW OF 3-D GRAPHS 356 CHANGING AXIS TICK MARKS 356 READING VALUES FROM GRAPHS 359 REORDERING THE DISPLAY OF A DATA SERIES 360 ADDING TEXT BOXES TO CHARTS 362 MOVING GROUPS OF DATA LABELS AT ONE TIME 363 LABELING X-Y SCATTER PLOTS 363

Printing Tips 365 SETTING PAGE MARGINS 365 SELECTING A PAPER SOURCE 367 SCALING YOUR PRINTING 369 AUTOMATICALLY PRINTING A RANGE 370 CHANGING ORIENTATIONS WITHIN A SINGLE PRINTOUT 371 PRINTING WORKBOOKS IN A FOLDER 373 PREVENTING PRINTING 373 PRINTING ALL OR NOTHING 374 PRINTING MULTIPLE PAGES ON A PIECE OF PAPER 375 REPEATING ROWS ON A PRINTOUT EXCEPT ON THE LAST PAGE 377 SHOWING FILTER CRITERIA ON A PRINTOUT 377 PRINTING A NUMBER OF DIFFERENT PAGES 379

ExcelTips 2008 Page x

Page 11: Excel tips 2008

PRINTING AN ENTIRE WORKBOOK BY DEFAULT 380 PRINTING JUST THE VISIBLE DATA 381 HIDING ERRORS ON PRINTOUTS 383 PRINTING ONLY NON-BLANK WORKSHEETS 385 LOCKING THE PRINT AREA 385 PROTECTING PRINT SETTINGS 386 CONDITIONAL PRINTING 387 PRINTING BASED ON CELL CONTENTS 390

Workbook and File Tips 392 INCREASING THE NUMBER OF MRU FILES 392 SAVING ALL OPEN WORKBOOKS 393 SAVING A WORKBOOK WITH A PREVIEW 394 CORRECTLY SAVING DELIMITED FILES 395 SETTING THE AUTORECOVER DIRECTORY 396 DATE LAST EDITED 398 HANGING WHEN OPENING A WORKBOOK 399 FILE FORMATS THAT INCLUDE FIELD FORMATS 400 FIXING "CAN'T FIND FILES" ERRORS 401 LOADING UNWANTED FILES AT STARTUP 401 ACCESSING OLD EXCEL DATA 403 LOCKED FILE PUZZLE 404 DUPLICATE WORKBOOKS OPENING 405 SAVING IN TWO LOCATIONS 406 SHORT-LIVED BOOK1 406 FINDING THE PARENT FOLDER 407 MERGING MANY WORKBOOKS 407 USING YOUR OWN FILE EXTENSIONS 408 GETTING RID OF "COPY OF" 409 AVOIDING SCIENTIFIC NOTATION ON FILE IMPORTS 410 OPENING A WORKBOOK TO A SPECIFIC WORKSHEET 411 AUTOMATICALLY HIDING PERSONAL.XLS 412 LOSING DATA IN A SHARED WORKBOOK 413 PROBLEMS WITH DEFAULT WORKBOOK AND WORKSHEET TEMPLATES 414 IMPORTING HUGE DATA FILES 415 CSV FILE OPENS WITH DATA IN A SINGLE COLUMN 416 IMPORTING MANY FILES INTO EXCEL 418 GETTING INPUT FROM A TEXT FILE 418

Tools Tips 420 SETTING SPELL-CHECKING OPTIONS 420 SPELL-CHECKING UPPERCASE WORDS 422 ADJUSTING SPELL CHECK FOR INTERNET ADDRESSES 424

ExcelTips 2008 Page xi

Page 12: Excel tips 2008

ALLOWING FOR WORDS THAT CONTAIN NUMBERS 426 WATCHING CELL VALUES 428 IMPORTING CUSTOM LISTS 429 AUTOFILLING FROM A CUSTOM LIST 431 VIEWING COMMENTS 432 USING DATA VALIDATION 434 SETTING DATA VALIDATION INPUT MESSAGES 436 CHANGING AUTOFILTER DROP-DOWN ARROW COLORS 437 USING AUTOCORRECT 438 ADDING AND USING A COMBO BOX 439 INDEPENDENT RADIO BUTTONS 441 FORMATTING COMBO BOX TEXT 442 COMPARING WORKBOOKS 442

Macro Tips 444 UNDERSTANDING VARIABLES IN VBA MACROS 444 UNDERSTANDING SUBROUTINES 445 UNDERSTANDING FUNCTIONS 446 EXITING A FOR ... NEXT LOOP EARLY 447 UNDERSTANDING THE SELECT CASE STRUCTURE 448 DOCUMENTING CHANGES IN VBA CODE 449 STEPPING THROUGH A MACRO WITH A WORKSHEET VISIBLE 449 SELECTING A RANGE OF CELLS RELATIVE TO THE CURRENT CELL 450 SELECTING A CELL IN THE CURRENT ROW 451 JUMPING TO THE START OF THE NEXT DATA ENTRY ROW 452 COMPARING STRINGS 452 DETERMINING IF A NUMBER IS ODD OR EVEN 453 CREATING WORKSHEETS WITH A MACRO 453 REMOVING ALL MACROS 454 WORKING WHILE A MACRO IS RUNNING 456 FORCING A MACRO TO RUN WHEN A WORKSHEET IS RECALCULATED 456 AUTOMATING COPYING MACROS 458 MACRO FAILS AFTER AUTOFILTER 458 DISABLED MACROS 459 SELF-AWARE MACROS 461 COUNTING COLORS OF CELLS 462 COUNTING SHADED CELLS 463 OUT OF MEMORY ERRORS WHEN ACCESSING THE VBA EDITOR 464 DETERMINING HOW MANY WINDOWS ARE OPEN 465 SAVING CHANGES WHEN CLOSING 465 UPGRADING A PERSONAL.XLS WORKBOOK 466 SEARCHING FOR LEADING APOSTROPHES 467 WAITING FOR UPDATE COMPLETION 468 GENERATING UNIQUE NUMBERS FOR WORKSHEETS 469

ExcelTips 2008 Page xii

Page 13: Excel tips 2008

ExcelTips 2008 Page xiii

SAVING A WORKBOOK IN A MACRO 471 PUTTING AN X IN A CLICKED CELL 471 HIDING EXCEL IN VBA 472 DETERMINING A WORKSHEET'S NUMBER 473 RETRIEVING DRIVE STATISTICS 474 DEFAULT WORKSHEET WHEN OPENING 476 SELECTING CELLS OF A SPECIFIC COLOR 477 DETERMINING MOUSE CURSOR COORDINATES ON A GRAPHIC 480 LIMITING SCROLL AREA 481 COUNTING PRECEDENTS AND DEPENDENTS 482 PREPARING DATA FOR IMPORT INTO ACCESS 483 COUNTING COMMAS IN A SELECTION 485 EXTRACTING PROPER WORDS 486 AUTOMATICALLY LOADING ADD-INS 487 SHEETS FOR DAYS 488 SHEETS FOR MONTHS 490 USING BIN2DEC IN A MACRO 491 SELECTING ALL VISIBLE WORKSHEETS IN A MACRO 492 GETTING USER INPUT IN A DIALOG BOX 493 MOUSE CLICK EVENT IN VBA 494 CONVERTING PHONE NUMBERS 494 RETRIEVING WORKSHEET NAMES 496 GETTING A FILE NAME 496 FINDING THE LAST-USED CELL IN A MACRO 497 USING MACROS IN PROTECTED WORKBOOKS 498 ITEM NOT AVAILABLE IN LIBRARY 499 AUTOMATICALLY CHANGING REFERENCES TO VBA LIBRARIES 499

Page 14: Excel tips 2008

Introduction elcome to ExcelTips 2008. This document and the related files represent a compilation of tips that appeared in the pages of ExcelTips during the year 2008. In this e-book you will find how to make your use of Excel as productive as possible. Best of all, each

idea is presented in a bite-sized “tip” that you can apply right away. No more wading through tortuous pages of a computer book or through message after message in some newsgroup—all the information you need is right here, at your fingertips, 24 hours per day.

W As any long-time subscriber to ExcelTips knows, some tips are geared for beginners while others can teach veteran Excel users a thing or two. Regardless of your expertise, there is a very good chance that ExcelTips can teach you something you didn’t know before.

There are hundreds of tips in this e-book. Each is categorized (see the Table of Contents) and each includes an indicator of the version of Excel to which it applies. For instance, you will see indicators like the following on each tip in this document:

Applies to Excel 97, 2000, 2002, 2003, and 2007

This means that the related tip applies to all the popular versions of Excel in use today.

What’s In This E-Book? This document (the one you are reading) is the primary portion of ExcelTips 2008. There is another part to it, as well. When you extracted this document, you should have noticed that there was another directory (folder) created on your disk. This folder, named Original, contains the original ExcelTips newsletters, from January 5, 2008 through December 27, 2008. These are in the format originally sent in the newsletter, without any changes. The files are in text format, and can be easily opened with any text editor (such as Notepad).

In addition, if you purchased the CD-ROM version of the archives, you’ll find another folder on the CD: Premium. This includes all 52 of the ExcelTips Premium issues published during 2008. These issues are in PDF format, and can be opened with Acrobat Reader.

What about Viruses? Let’s face it—we live in a world where there are some sick people. I include in that judgment anyone that releases a program that will harm the data on others’ computers or impair their ability to use their computer in the way they want. Excel includes an amazingly rich macro capability that makes it vulnerable to macro viruses.

ExcelTips 2008 Page 1

Page 15: Excel tips 2008

Introduction

For this reason, this document has been distributed as a PDF document. This allows you to read and print the document as desired, using Adobe Reader, but hinders anyone from adding viruses that could harm your computer. (If you purchased the CD-ROM version of ExcelTips 2008, then it contains versions of the archives that will work with Adobe Reader 4, 5, and 7.)

As for the contents of the Original folder (as described above), they are nothing but text files—they cannot contain viruses.

You’ll notice that the archive also contains a Microsoft Word document. This is nothing but a Word version of the PDF e-book. It contains the same content, and has been examined to make sure that it contains no viruses. (If you get some sort of a message about the file containing macros when you open it, then the file is not the original. The original Word document has no macros attached to it at all.)

Need More Tips? Remember that this document contains the tips presented in past issues of ExcelTips. If you want to stay at the top of your Excel form, you should consider subscribing to ExcelTips. All you need is an e-mail account, and you can receive a free weekly dose of tips related to Excel. To subscribe to ExcelTips directly, visit the following Web site:

http://excel.tips.net

This site includes tips for all the current versions of Excel (97 through 2007). If you are solely interested in tips for Excel 2007, then this site may be of more interest to you:

http://excel2007.tips.net

ExcelTips is a part of the Tip.Net network. This family of sites is related by a common goal: to make useful information available in bite-sized chunks that are easy to understand. You can find more information at the main Tips.Net site:

http://www.tips.net

A Special Note of Thanks I would like to thank the many thousands of current ExcelTips subscribers. Without their assistance, many of these tips would not have been possible. Week in and week out I receive e-mail from people needing help, as well as from people willing to offer help. These people selflessly provide assistance to others, submitting solutions to problems that others face.

Sharing this Document There was a lot of work that went into putting this document together. I can’t tell you how many countless hours are spent putting together the weekly ExcelTips newsletter from which this information was compiled. That means that this information has value, and your friends, neighbors, and co-workers may recognize that value and want to share it.

ExcelTips 2008 Page 2

Page 16: Excel tips 2008

Introduction

ExcelTips 2008 Page 3

The information in this document is copyrighted. Please do not share this information with others—you purchased ExcelTips 2008, and you have a right to use it on your system. Another person who has not purchased this document does not have that right. It is the sales of this valuable information that makes the continued publishing of ExcelTips possible. If enough people disregard that simple economic fact, the newsletter will no longer be viable or available.

If your friends think this information is valuable enough to ask you for it, they should think it is valuable enough to purchase on their own. After all, the price is low enough that just about anyone should be able to afford ExcelTips.

It should go without saying that you cannot post this document or the information it contains on any electronic bulletin board, Web site, FTP site, newsgroup, or … well, you get the idea. The only place from which this document should be available is the ExcelTips Web site. If you want an original copy, visit the Tips.Net store:

http://store.tips.net

In addition, it is a violation of copyright to share this e-book with others in your office. Even if you purchased it with company funds, that does not provide the company with the unlimited right to share the e-book with others in the company. If you would like to share the content with others, contact me directly (mailto:[email protected]) regarding site licenses for ExcelTips.

Page 17: Excel tips 2008

General Tips

I HATE THE EXCEL 2007 USER INTERFACE

Applies to Excel 2007

Excel 2007 was released in early 2007, and it presented a drastically new interface to users. Karen wrote about this interface, expressing the feelings of many that while she likes the new features in the version, she absolutely hates the user interface. She wonders if there is any way she can configure Excel 2007 so that it uses the old menu interface, as was used in Excel 2003.

The bottom line is that there is no “easy” way. In fact, the easiest way to not have to put up with the Excel 2007 interface is not stick with Excel 2003. This, of course, becomes less and less of an option as time goes on and more and more people learn the new interface. (Microsoft is showing no signs of backing down on the interface change.)

The user interface for Excel 2007 is written in the XML language. Although Microsoft allows users to customize that XML (and thereby modify the interface), they don’t include tools or information on how to make the changes. There are, however, several different add-on tools you can get that allow you to make changes. A good (and free) one is located here:

http://pschmid.net/office2007/customize/

If you prefer, you can spring for a commercial one, such as Classic Menu, available here:

http://www.addintools.com

By the way, if you want to get the complete scoop as to why Microsoft made such a drastic change in the user interface, you’ll want to check out the resources on this Web page:

http://pschmid.net/blog/2006/10/09/58

It will take some time to read through all the information at this site, but it is well worth it if you want to understand, exactly, why Microsoft did what they did. (It may not help mitigate the dislike, but you can certainly better understand why the change was made.)

ExcelTips 2008 Page 4

Page 18: Excel tips 2008

General Tips

(Thanks to Ron Solecki and José Lôbo for contributing to this tip.)

CANCELING A COMMAND Applies to Excel 97, 2000, 2002, 2003, and 2007

If you start to perform a command or action within Excel, you may want to cancel it before it finishes. To do this, the general rule is to simply press the ESC key. This should cancel any command or action that Excel is processing. It is also interesting to note that you can press ESC to close most every dialog box that may pop up in Excel.

ARRANGING WORKBOOK WINDOWS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have more than one workbook open at a time, Excel allows you to view all the workbooks at the same time, and to arrange each workbook window as you desire. The easiest method of arranging workbook windows is as follows, if you are using a version of Excel prior to Excel 2007:

1. Choose Arrange from the Window menu. This displays the Arrange dialog box.

The Arrange dialog box.

2. The Tiled option should be selected. Click on OK. This divides the screen space evenly between all your workbooks. The main benefit is that each workbook gets at least a piece of the screen.

3. Click on the window whose size you wish to adjust. It becomes active.

ExcelTips 2008 Page 5

Page 19: Excel tips 2008

General Tips

4. Move the mouse cursor near the border of the active window. When the cursor turns into a set of arrows, click the mouse button and drag the window edge to the desired size. Release the mouse button.

5. Repeat steps 3 and 4 for each window you want to adjust.

If you are using Excel 2007, follow these steps instead:

1. Display the View tab of the ribbon. 2. In the Window group click the Arrange All tool. Excel displays the Arrange Windows

dialog box. 3. The Tiled option should be selected. Click on OK. This divides the screen space evenly

between all your workbooks. The main benefit is that each workbook gets at least a piece of the screen.

4. Click on the window whose size you wish to adjust. It becomes active. 5. Move the mouse cursor near the border of the active window. When the cursor turns

into a set of arrows, click the mouse button and drag the window edge to the desired size. Release the mouse button.

6. Repeat steps 4 and 5 for each window you want to adjust.

STARTING IN SAFE MODE Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are having problems with Excel, it could be because of the files and add-ins that are loaded whenever you start Excel. To test this theory, you can start Excel in “safe mode.” Follow these steps:

1. Choose the Run option from the Start menu. Windows displays the Run dialog box.

The Run dialog box.

ExcelTips 2008 Page 6

Page 20: Excel tips 2008

General Tips

2. In the Open box, type the path to the Excel program, and add the /s switch at the end. For instance, the command line you enter might look like this:

"c:\program files\microsoft office\office\excel.exe" /s

3. Click OK.

Excel starts, but in doing so, it bypasses all the files in the various startup folders (such as XLStart), and depending on your version of Excel it skips loading the toolbar file (Excel.xlb). You know you are in safe mode because the words “Safe Mode” appears in the title bar. You can use Excel as you normally would, and then exit the program. The next time you start the program—without the safe mode switch—it runs as it normally does.

EXCLUDING A SPECIFIC ADD-IN AT STARTUP

Applies to Excel 97, 2000, 2002, 2003, and 2007

Peter asked if there is a way to specify, at Excel startup, that a particular add-in should not be loaded. The add-in he has in mind takes a lot of time to load, and he doesn’t need it all the time. Disabling the add-in would help start Excel quicker for those instances when it wasn’t needed.

Unfortunately, there is little that can be done to disable add-ins at start-up because no particular workbook is already open. (The add-ins are loaded before any workbooks.) There are a couple of things you could try, however.

The first thing is that you could create your own add-in that does nothing more than ask if the large add-in should be loaded or not. Depending on the user’s response, the add-in could then be loaded by using the following line of code:

AddIns("Big Add-in").Installed = True

Of course, you’ll need to replace “Big Add-in” with the name of the actual add-in to be loaded. If the user doesn’t want the add-in loaded, just skip the line of code. In the Close event for your little add-in you could then add a line like the following that unloads the big add-in:

AddIns("Big Add-in").Installed = False

In this way, the add-in is added only if the user says it is OK to add, and then always unloaded at the end of your Excel session.

Another approach is to never load the large add-in, but put a routine in your Personal.xls file that gives the user a chance to load the add-in. The following could be added to the Workbook_Open event in Personal.xls:

ExcelTips 2008 Page 7

Page 21: Excel tips 2008

General Tips

Private Sub Workbook_Open() With Application .OnKey "{TAB}", "InstallMyAddIn" .OnTime (Now + TimeValue("0:00:05")), "DisableTABProc" End With End Sub

The purpose of this macro is to give the user a period of time—in this case five seconds—to press the Tab key so that the large add-in is loaded. The .OnKey method runs the installation routine, if Tab is pressed, and the .OnTime routine starts a timer that runs the disable routine once the five seconds is elapsed. Notice that this macro calls two routines; these can go in a regular module for Personal.xls.

Sub InstallMyAddIn() AddIns("Big Add-in").Installed = True DisableTABProc End Sub

Sub DisableTABProc() Application.OnKey "{TAB}", "" End Sub

Of course, you’ll need to add some code for the Workbook_Close event of Personal.xls, in this case to unload the add-in:

Private Sub Workbook_Close() AddIns("Big Add-in").Installed = False End Sub

If you prefer to not use macros, then you can always just move the big add-in from it’s directory location or rename the add-in prior to starting Excel. If Excel cannot locate the add-in, it continues to load without loading it.

DISABLING EXCEL'S HELP SYSTEM

Applies to Excel 97, 2000, 2002, 2003, and 2007

Mark is a high school teacher and he wants to disable Excel's Help system during student tests. He wonders if there is an easy way to do this.

The answer is yes, there is a relatively easy way. You could set up a couple of macros that disable and restore the most common ways of opening the Help system. The following macros, DisableHelp and EnableHelp, do that.

ExcelTips 2008 Page 8

Page 22: Excel tips 2008

General Tips

Sub DisableHelp() EnableControl 984, False ' help EnableControl 1004, False ' Office Assistant Application.OnKey "{F1}", "" End Sub

Sub EnableHelp() EnableControl 984, True ' help EnableControl 1004, True ' Office Assistant Application.OnKey "{F1}" End Sub

Sub EnableControl(Id As Integer, Enabled As Boolean) Dim CB As CommandBar Dim C As CommandBarControl For Each CB In Application.CommandBars Set C = CB.FindControl(Id:=Id, recursive:=True) If Not C Is Nothing Then C.Enabled = Enabled Next End Sub

Both of the main macros call the EnableControl macro. This macro does the actual work of removing the Help options from the menus and toolbars. Note that the main macros also use the OnKey method to disable (or restore) the functioning of the F1 function key. To use these macros, you can call them from a suitable event procedure, such as those that automatically run when a workbook is opened and closed.

The macros will run just fine in all the modern versions of Excel, but they are particularly useful in versions prior to Excel 2007. In those versions the menus and toolbars are modified by the macros, but not so in Excel 2007. The Help button (small question mark within a circle) remains at the upper-right corner of the worksheet window and can still be clicked. Regardless of your version, the F1 key is disabled and enabled by the macros.

Even with a macro such as this at work, you need to realize that the Help system is not totally disabled. The Help files still reside on disk, and could be located via Windows and opened. (You don’t even need Excel to open and view them.)

Typically the Excel Help files are stored in files that use the CHM file extension. Disabling the file can be as simple as locating the proper CHM help file on the disk and renaming it to something different.

For example, Excel may be installed on a certain machine in the directory “c:\program files\microsoft office\office11”. The Help file for this installation of Excel can be found in “c:\program files\microsoft office\office11\1033”. The main Excel file is XLMAIN11.CHM, but there may be other Help files (CHM extension) in the directory as well. All you need to do is to rename these files something such as XLMAIN11.XXX. Since the Help program cannot locate the file, it cannot display any help in Excel.

(Thanks to Kirk Mays, Steve Aprahamian, Mark Rotchell, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 9

Page 23: Excel tips 2008

General Tips

WHERE IS THAT NAME? Applies to Excel 97, 2000, 2002, 2003, and 2007

Defining names in an Excel worksheet is a common task, and many worksheets can end up with many, many named ranges. You can, of course, jump to a range name by using the Go To dialog box (press F5).

One little-known tip allows you to see all your named ranges at once, rather than jumping to them individually. Simply change the Zoom factor for your workbook to 39%, and the named ranges are shown on-screen as “blocked” areas. This works only when the Zoom factor is 39% or less; at 40% or greater, the named ranges are not marked. It also only shows named ranged occupying two cells or more; single-celled named ranges are not shown.

TURNING OFF NAMES Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel includes the capability to convert cell references (such as B2 or C7) to names you have defined within a document; exactly how you do this has been covered in other issues of ExcelTips. There is no inherent command that will convert from named references back to cell references.

Unfortunately, if you try to delete names already defined in a workbook, Excel simply replaces the results of formulas referencing the name with the #NAME? error. The only way to switch back to cell references is to edit each of the formulas that reference a name and replace the reference with a cell reference.

REFUSING ONLINE HELP Applies to Excel 2003 and 2007

One of the changes introduced in Excel 2003 was a greater reliance by the program on online help systems. When you choose to display Excel’s Help system and then search for information on a topic, by default Excel also returns help topics from the Web, specifically from Microsoft’s Web sites.

You can, if desired, configure Excel 2003 so that it won’t access any online information. To make this change, follow these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box.

ExcelTips 2008 Page 10

Page 24: Excel tips 2008

General Tips

2. Make sure the General tab is displayed. 3. Click Service Options. Excel displays the Service Options dialog box. 4. In the Category list, choose Online Content.

The Service Options dialog box.

5. Using the controls at the right side of the dialog box, specify how you want Excel to access (or not access) online content.

6. Click OK to close the Service Options dialog box. 7. Click OK to close the Options dialog box.

You can make the same configuration change in Excel 2007 by following these steps:

1. Display the Excel Help dialog box. (Click the small Help icon in the upper-right corner of the screen.)

2. At the bottom-right of the dialog box you should see text that says Connected to Office Online. Click this text to display a drop-down list.

3. Select the choice that reflects how you want Excel to access (or not access) online content.

4. Dismiss the Excel Help dialog box.

ExcelTips 2008 Page 11

Page 25: Excel tips 2008

General Tips

TURNING OFF DYNAMIC MENUS Applies to Excel 2000, 2002, 2003, and 2007

Excel, starting with Excel 2000, employs a feature I refer to as "dynamic menus." This means that Excel keeps track of which menu options you use the most, and these are the options it presents you. If you want to see all the menu options, you need to hover the mouse pointer over a menu for a few seconds, or click on the down-pointing arrows at the bottom of any menu.

Dynamic menus can make it a bit easier to get to the choices you make most often, but there is a drawback: It is more difficult to see all the menu-based capabilities of Excel. If you want to turn off this feature (thereby making Excel's menus behave as they did in previous program versions), follow these steps:

1. Choose Customize from the Tools menu. Excel displays the Customize dialog box. 2. Make sure the Options tab is selected.

The Options tab of the Customize dialog box.

3. Clear the check box to the left of the Menus Show Recently Used Commands First option. (In Excel 2003, select the Always Show Full Menus check box.)

4. Click on OK.

These steps won’t work in Excel 2007, and there is no comparable configuration option. Why? Because Excel 2007 doesn’t use menus; it uses the ribbon interface, instead.

ExcelTips 2008 Page 12

Page 26: Excel tips 2008

General Tips

ANIMATED MENUS Applies to Excel 97, 2000, 2002, 2003, and 2007

One of the ways that Excel attempts to add spice to life is through menu animation. Normally menu animation is turned off, but if you have some CPU cycles to spare, you may want to give it a try.

If you are using a version of Excel prior to Excel 2007, simply choose Customize from the Tools menu, and then click on the Options tab. The Menu Animations drop-down list has these possible settings:

• System Default. This is (oddly enough) the default; there is no menu animation. • Random. Results in a menu using the Unfold or Slide method, at random. • Unfold. The menu opens up from top to bottom and left to right. • Slide. The menu “slides” onto the screen, progressing from top to bottom. • Fade. The menu “fades” in, from light to dark.

Make your selection, then click on the Close button.

None of these settings are available in Excel 2007. Why? Because the Excel 2007 interface doesn’t rely on menus, it relies on the ribbon. Thus, settings as to how menus should behave would be extraneous in Excel 2007.

TURNING OFF ERROR CHECKING Applies to Excel 2002, 2003, and 2007

While you have Excel 2002, Excel 2003, or Excel 2007 open, it is constantly checking in the background for potential errors in your worksheets. If an error is located (or, at the least, what Excel thinks is an error), then the cell is “flagged” with a small green triangle in the upper-left corner of the cell.

If you don’t want Excel to check for errors, you can turn the feature off by following these steps in Excel 2002 or Excel 2003:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Error Checking tab is displayed.

ExcelTips 2008 Page 13

Page 27: Excel tips 2008

General Tips

The Error Checking tab of the Options dialog box.

3. Clear the Enable Background Error Checking check box. 4. Click OK.

You turn off the feature in Excel 2007 by following these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Formulas at the left side of the dialog box.

ExcelTips 2008 Page 14

Page 28: Excel tips 2008

General Tips

The Formulas area of the Excel Options dialog box.

3. Clear the Enable Background Error Checking check box. 4. Click OK.

Any existing green triangles should disappear, and Excel stops checking for errors.

A SHORTCUT FOR SWITCHING FOCUS

Applies to Excel 97, 2000, 2002, 2003, and 2007

You probably already know that you can use the ALT+TAB shortcut to switch from one open application in Windows to another, right? What if you don’t want to switch between applications, but simply want to switch to the desktop, then back to your application again? If you are using the mouse, you can click on the Show Desktop icon available in the Quick Launch toolbar, just to the right of the Start menu. (This depends on your version of Windows, obviously.)

Using the keyboard to switch focus in this manner is a bit different, however. Assuming you have an enhanced Windows keyboard—the one with the Windows key next to the ALT keys—then the answer is easy. In fact, there are two shortcuts you can use.

• Press WINDOWS+M to minimize all the open windows and change focus to the desktop. To return focus to where you were last working, using SHIFT+WINDOWS+M.

ExcelTips 2008 Page 15

Page 29: Excel tips 2008

General Tips

• Press WINDOWS+D to minimize all the open windows and change focus to the desktop. Press WINDOWS+D again, and focus is returned to the window in which you were previously working.

While this is not technically an Excel tip (it is a Windows tip), it is a tip that can come in handy for those Excel users who only want (or need) to use the keyboard.

ACTIVATING THE FORMULA BAR WITH THE KEYBOARD

Applies to Excel 97, 2000, 2002, 2003, and 2007

The Formula bar, just above the work area in Excel, shows the formula or value in the currently selected cell. You can click on the formula bar to edit information within a cell, if desired. What if you want to activate the Formula bar by using the keyboard, however?

The quickest way to do this is simply to press F2. This tells Excel that you want to edit the contents of a cell. When you press F2, it is highly possible that Excel will simply expand the information in the cell and allow you to edit the information directly in the cell itself. If you don’t like this behavior, but instead want F2 to activate the Formula bar, follow these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Edit tab is selected.

ExcelTips 2008 Page 16

Page 30: Excel tips 2008

General Tips

The Edit tab of the Options dialog box.

3. Clear the Edit Directly In Cell check box. 4. Click on OK.

These steps won’t work in Excel 2007. Follow these steps, instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click the Advanced option at the left of the dialog box.

ExcelTips 2008 Page 17

Page 31: Excel tips 2008

General Tips

The advanced options in the Excel Options dialog box.

3. Make sure the Allow Editing Directly In Cell check box is cleared. 4. Click on OK.

Now, whenever you press F2, the Formula bar is selected and you can edit the formula there.

LIMITING WHAT IS SHOWN IN THE FORMULA BAR

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel 2007 offers the ability to prevent the Formula bar from displaying more than one line of text so the worksheet isn't obscured by the Formula bar when a cell with a large amount of content is selected. Jennifer wonders if there is a way to accomplish this in Excel 2003 and earlier versions of Excel.

The short answer is that no, there isn’t. This capability is new in Excel 2007 with no equivalent in earlier versions of the program. What most people did was to either turn off the display of the Formula bar entirely (View | Formula Bar) or to insert a blank “dummy row” at the top of your worksheet that you didn’t mind being overwritten with the expanding Formula bar.

(Thanks to Steve Aprahamian and Dave Pettit for contributing to this tip.)

ExcelTips 2008 Page 18

Page 32: Excel tips 2008

General Tips

ENLARGING THE FORMULA BAR Applies to Excel 97, 2000, 2002, 2003, and 2007

When you select a cell in a worksheet, the contents of that cell are shown in the Formula bar. If the contents are longer than what can be displayed in a single line on the Formula bar, the depth of the Formula bar increases so that the entire formula can be displayed. When you move to another cell, the Formula bar again decreases in depth to a single line.

The problem with an automatically adjusting Formula bar is that it can obscure other elements on the screen. If the Formula bar takes up two or three lines of depth, it overlays the column headers and other cells in the worksheet. This can be distracting, at times.

Unfortunately, there is no way to instruct Excel to a) limit the Formula bar to a set depth, or b) decreasing the size of the type in the Formula bar so more can fit within a single line. (At least this is true for versions of Excel prior to Excel 2007—more on that in a moment.) The best you can do is to simply remove the Formula bar completely, so it is not visible. (If you have no Formula bar displayed, then it cannot expand and obscure information in the worksheet.) You can turn off the Formula bar in this manner if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the View tab is selected.

ExcelTips 2008 Page 19

Page 33: Excel tips 2008

General Tips

The View tab of the Options dialog box.

3. Clear the Formula Bar check box. 4. Click on OK.

Excel 2007 gives you more flexibility. It allows you to modify the number of lines used by the Formula bar. That way it will always take a specific amount of space and you won’t be bothered by it jumping around as much. To expand the Formula bar (so you can see everything it contains), click the tool at the very right edge of the Formula bar. When you hover the mouse pointer over the tool, the ToolTip says “Expand Formula Bar.”

If you want to turn off the Formula bar completely in Excel 2007, follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left of the dialog box click Advanced. 3. Scroll through the options until you see the Display section.

ExcelTips 2008 Page 20

Page 34: Excel tips 2008

General Tips

The Display section of the Advanced options in the Excel Options dialog box.

4. Clear the Show Formula Bar check box. 5. Click on OK.

TURNING OFF SCREENTIPS Applies to Excel 97, 2000, 2002, 2003, and 2007

ScreenTips are the small yellow boxes that appear as you position the mouse pointer over a toolbar button or over another control on the Excel program window. Some people find these ScreenTips distracting, so Microsoft provided a way for you to control whether they are displayed or not. To turn off ScreenTips, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose the Customize option from the Tools menu. Excel displays the Customize dialog box.

2. Click on the Options tab.

ExcelTips 2008 Page 21

Page 35: Excel tips 2008

General Tips

The Options tab of the Customize dialog box.

3. Make sure the Show ScreenTips on Toolbars option is not selected. 4. Click on Close.

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Make sure the Popular option is selected at the left of the dialog box.

ExcelTips 2008 Page 22

Page 36: Excel tips 2008

General Tips

The Popular area of the Excel Options dialog box.

3. Using the ScreenTip Style drop-down list, choose Don’t Show ScreenTips. 4. Click OK.

SIMULTANEOUS SCROLLING Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have worksheets that are very similar in nature, you may like to work with them side-by-side on the screen at the same time. This makes it easy to examine both worksheets for differences or for other reasons. It can be a bother, however, to scroll down at the same rate in both worksheets. First you have to scroll in one window, then in the other.

As with most tedious tasks, you can automate the process a bit. Consider the following macros:

Sub myScrollDown() ActiveWindow.SmallScroll Down:=1 ActiveWindow.ActivateNext ActiveWindow.SmallScroll Down:=1 ActiveWindow.ActivatePrevious End Sub

Sub myScrollUp() ActiveWindow.SmallScroll Up:=1 ActiveWindow.ActivateNext ActiveWindow.SmallScroll Up:=1

ExcelTips 2008 Page 23

Page 37: Excel tips 2008

General Tips

ActiveWindow.ActivatePrevious End Sub

If you add these to a workbook, and then assign them to a toolbar button, a shortcut key, or the Quick Access toolbar you can scroll through both workbooks at the same rate. The SmallScroll method is used to move down one row at a time through a window. If you want to scroll a page at a time, simply replace all instances of SmallScroll with the LargeScroll method.

REMOVING PERSONAL INFORMATION

Applies to Excel 2002, 2003, and 2007

As you create a workbook in Excel, there is a lot of information that is stored with the workbook that can identify you as the author. Most of this information is stored in the workbook’s file properties. If you are using Excel 2002 or Excel 2003, there is an option you can use that can help eliminate some of the identifying information saved with a workbook. Choose Tools | Options to display the Options dialog box, then make sure the Security tab is displayed.

The Security tab of the Options dialog box.

ExcelTips 2008 Page 24

Page 38: Excel tips 2008

General Tips

Notice the Remove Personal Information from File Properties on Save check box. If this option is selected, Word will strip out personal information from the file properties.

Excel 2007 takes a much more detailed approach to removing personal information from a workbook. This version includes a feature known as the Document Inspector, which can check the document for a wide range of items. Just click the Office button | Prepare | Inspect Document. In the resulting Document Inspector dialog box, specify the items you want the inspector to look for and then click on Inspect. Excel displays what it found in the workbook and gives you the option to remove the personal information you want removed.

CLEARING LARGE CLIPBOARD ENTRIES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Have you ever noticed that after you’ve copied a large amount of data to the Clipboard, and then you close Excel, you see a dialog box stating that “A large amount of data is present in the Clipboard. Do you want to save it before quitting?” You may get tired of seeing this message. If so, then there are a couple of things you can do.

First, you can replace the “large amount” with a “small amount.” (Excel never asks if you want to discard a small amount.) To do this, just select a single cell in your worksheet and copy it to the Clipboard. The contents of the single cell replace the large amount of data on the Clipboard, and you can exit Excel without seeing the message.

If you’d rather have a macro approach, you can do the exact same thing in a macro—just select cell A1 and have your macro copy it to the Clipboard:

Sub GoAway1() ActiveSheet.Range("A1").Copy End Sub

Another approach is to use a single-line macro that basically “disables” the Clipboard by canceling any current copy operation:

Sub GoAway2() Application.CutCopyMode = False End Sub

ExcelTips 2008 Page 25

Page 39: Excel tips 2008

General Tips

CHANGING ERROR CHECKING RULES

Applies to Excel 2002, 2003, and 2007

When Excel 2002 or Excel 2003 does background checking of your worksheet for errors, it follows a set number of rules. You can modify the rules that Excel follows through these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Error Checking tab is displayed.

The Error Checking tab of the Options dialog box.

3. Make sure the Enable Background Error Checking check box is selected. 4. Clear or set the checkboxes at the bottom of the dialog box, each of which specifies a

different error-checking rule that Excel can follow. 5. Click OK.

The error-checking rules can be modified in Excel 2007 by following these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Formulas at the left side of the dialog box.

ExcelTips 2008 Page 26

Page 40: Excel tips 2008

General Tips

The Formulas options of the Excel Options dialog box.

3. Make sure the Enable Background Error Checking check box is selected. 4. Clear or set the checkboxes in the Error Checking Rules area of the dialog box, each of

which specifies a different error-checking rule that Excel can follow. 5. Click OK.

FORCING MANUAL CALCULATION FOR A WORKBOOK

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel workbooks can become quite complex. In fact, it is possible to create workbooks that can take hours to calculate. The only problem with this, of course, is that when you open a workbook, it automatically recalculates if you have Excel configured to do that. This means that just opening a workbook can, in some instances, take hours.

One solution, of course, is to turn off automatic recalculation before you open the workbook. If you are like me, this solution isn't that great because my memory isn't always that great.

A better solution is to turn off automatic recalculation for certain workbooks. Since Excel doesn't allow you to specify manual or automatic recalculation on a workbook-by-workbook basis, you will need to add this feature through the use of a macro that automatically runs when the workbook is opened. This macro can turn off automatic recalculation, as shown here:

Private Sub Workbook_Open()

ExcelTips 2008 Page 27

Page 41: Excel tips 2008

General Tips

Application.Calculation = xlManual Application.CalculateBeforeSave = False End Sub

This macro must be placed in the ThisWorkbook project window. This means that you should open the workbook, press ALT+F11 to display the VBA Editor, and then double-click on the ThisWorkbook object in the Object Browser (upper-left corner of the VBA Editor window).

If you want, you can also place another macro right after the previous one. This macro is run automatically when the workbook is closed and, in this case, turns automatic recalculation back on:

Private Sub Workbook_BeforeClose(Cancel As Boolean) Application.Calculation = xlAutomatic Application.CalculateBeforeSave = True End Sub

There is an important caveat to remember in relation to using this macro. You can only set the calculation mode for the application as a whole. Thus, with automatic recalculation turned off, no other worksheets will be automatically recalculated, either.

MAKING AUTOCOMPLETE WORK FOR AN ENTIRE COLUMN

Applies to Excel 97, 2000, 2002, 2003, and 2007

The AutoComplete feature in Excel can be a great boon for data entry, making it very easy to enter multiple instances of the same text in a column. One of the constraints on the AutoComplete feature is that it only works on contiguous ranges of cells in a column. For instance, if you have data in cells B7 through B25, then AutoComplete will work just fine if you are entering data in cell B6 or B26. It will not, however, work in cells B5 or B27 if cells B6 or B26 are left empty.

The only way to get around this limitation is to make sure that you have something in every single cell in the range. Some people put characters, such as periods, in the cells they otherwise would have left blank. The problem with this, of course, is that the periods show up on a printout, and need to be removed as a final step of creating your worksheet.

A better approach is to use a non-printing character in the otherwise blank cells. Instead of a period, use a space. Better yet, you can use a 0 (zero) value. You can then instruct Excel to suppress the display of zeros in the display.

ExcelTips 2008 Page 28

Page 42: Excel tips 2008

General Tips

EXCEL PROFICIENCY TESTING Applies to Excel 97, 2000, 2002, 2003, and 2007

Mark needs to determine someone's proficiency with Excel and is wondering if there are any tests available that can run without the installation of any special software, macros, flash, or the like.

The short answer is that it depends—on lots of things. Proficiency tests are designed to measure how well someone does at a certain task. Excel is a tool you can use to accomplish some tasks, but it isn’t a task itself. For example, a proficiency test may indicate how well someone does at creating pie charts, but may not do well on PivotTables, lookup formulas, or conditional formatting.

Because the number of things you can do with Excel is so large, many people develop their own in-house tests that, again, are geared toward specific tasks. An example would be to create a worksheet that has assorted raw data and then ask the user to do something with that data to reach a desired goal. You might even provide a question or two that direct the user to create a worksheet to solve the question.

If you prefer to not develop your own proficiency test, you should try doing a search on Google for what you need. For instance, you might search for “Excel proficiency tests” (without the quote marks). If you want to limit the results further, add additional search terms that reflect the specific skills you want to test. For example, you could search for “Excel proficiency tests charts” or “Excel proficiency tests PivotTables.”

Finally, here are some specific resources pointed out by some ExcelTips subscribers:

http://www.proveituk.com/ http://Office.Microsoft.com/en-us/excel/Q2 http://www.snowcrest.net/dsp/Excel_Q.htm

(Thanks to Shirley Simcock, Steve Aprahamian, and Richard Raciborski for contributing to this tip.)

SELECTED CELLS NOT SHADED Applies to Excel 2007

Ted just switched to Excel 2007. Whenever he select multiple cells, all the cells are white, not shaded blue as in previous versions of Excel. This means he cannot tell which cell is the active cell. When Ted uses the CTRL key to select multiple cells in different parts of the worksheet, he cannot even tell which cells have been selected. Ted wonders how he can get Excel 2007 to shade selected cells as was done in previous versions of the program.

ExcelTips 2008 Page 29

Page 43: Excel tips 2008

General Tips

The short answer is that you can’t. In fact, it appears that the coloring of many parts of Excel (including selections) are hard-coded. In previous versions of Excel you could change the colors in Windows itself; this won’t really affect Excel 2007 that much.

The problem, has been known since the earliest betas of Excel 2007, and still Microsoft has done nothing to fix it. There is an interesting blog post over on the MSDN (Microsoft Developer Network) site that talks about this issue and provides a few workarounds:

http://blogs.msdn.com/excel/archive/2008/04/22/improving-sheet-selection.aspx

(Thanks to Steve Aprahamian for contributing to this tip.)

PROBLEM WITH MISSING CONTEXT MENU OPTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Rita has encountered a situation at her workplace that has her scratching her head. They have an employee who can right-click on any cell and the Format Cells option is not available on the resulting Context menu. Rita is wondering what is necessary to get the Context menu option back.

It is possible that the Context menu that is displayed when you right-click on a cell has, over time, become modified in some way. You can reset this particular Context menu by using a very simple macro:

Sub ResetContextMenu() CommandBars("Cell").Reset End Sub

If this does not do the trick, or if the menu inexplicably changes at some future point, the culprit could very well be some sort of add-in or a particular macro in a workbook. Determining which of the macros is doing the modification can take some serious detective work. If you can access the macros in the add-in or workbook, you might want to just search through the VBA code to see if you can find the text “CommandBars” to see what is being changed.

If you cannot access the macro code (perhaps the add-in or workbook is protected), then you will need to go through a trial-and-error process where you stop the loading of the add-ins, one by one, until you determine which one causes a change in the Context menu.

(Thanks to Steve Aprahamian, Andrija Vrcan, and John Cross for contributing to this tip.)

ExcelTips 2008 Page 30

Page 44: Excel tips 2008

General Tips

CHANGING THE SHORTCUT MENU Applies to Excel 97, 2000, 2002, 2003, and 2007

The shortcut menus that you see when you right-click on different objects can be very helpful. In Word, it is relatively easy to change the shortcut menus. In Excel, however, changing the menus—while possible—is nowhere near as easy.

In Excel, you can only change the options on a shortcut menu by using VBA. The exact code you use depends on whether you are removing items from a shortcut menu or adding them in. The following code illustrates how to delete an item from a shortcut menu:

Sub Del_Item() CommandBars("Cell").Controls("Cut").Delete End Sub

Each shortcut menu is really a member of the CommandBars collection, and can thus be manipulated in VBA. In this case, a CommandBar by the name of “Cell” is being manipulated. This just happens to be the command bar for the shortcut menu that appears when you right-click on a cell in a worksheet. Excel has 47 named shortcut menu CommandBars.

If you want to add a command to a shortcut menu, all you do is use code similar to the following:

Sub Add_Item() CommandBars("Cell").Controls.Add _ Type:=msoControlButton, Id:=21, _ Before:=1 End Sub

In this instance you are again manipulating the shortcut menu that appears when you right-click on a cell. You are adding a command that is defined by the Id value setting. In this case, the Id value is 21, which represents the Cut command. There are scores, if not hundreds, of different command IDs within Excel.

To aid you in determining both the Id to use for a command, as well as the names of the various shortcut menu CommandBars, you should refer to the Knowledge Base article 213552. This article is quite long, and can be found at the following address:

http://support.microsoft.com/?kbid=213552

The article is written for Excel 2000, but is also applicable to later versions of Excel, through Excel 2003. In Excel2007 there are still CommandBars, but it can be hit-and-miss trying to see what will work with them. In my testing it appears that the CommandBars for the Context menus (or, if you prefer, shortcut menus) are all available in Excel 2007. What can be bothersome is trying to figure out what the proper command IDs are for the various commands available in Excel 2007.

ExcelTips 2008 Page 31

Page 45: Excel tips 2008

General Tips

ALWAYS OPEN AT 100% ZOOM Applies to Excel 97, 2000, 2002, 2003, and 2007

If you work with workbooks first worked on by your colleagues, you may be frustrated by the zoom factor applied to those workbooks by those others. For instance, if your colleague (Wanda) has a huge monitor, it wouldn’t be uncommon for her to reduce the zoom factor on Excel to 75% or even 60%. The purpose, of course, is so she isn’t overpowered by things that look very large at the full zoom factor.

The problem is that the zoom factor is saved with the workbook. Thus, when Wanda saves the workbook and hands it off to you, when you open it, the workbook is still displayed at whatever zoom factor Wanda last used. If you don’t have the same size monitor as Wanda, then the workbook may be almost illegible on your system.

There are only two possible solutions to this problem. First, you can simply adjust the zoom factor once you open the workbook. There are a multitude of ways to do this, but the easiest involve the Zoom setting on the Formatting toolbar, or using the scroll wheel on your mouse. (On some systems you may need to hold down the CTRL key in order for the scroll wheel to adjust the zoom factor.)

The second workaround is to create a macro that gets saved with the workbook. The macro can run every time the workbook is opened, and thereby set the zoom factor. (This macro should be added to the This Workbook code window in the VBA editor.)

Private Sub Workbook_Open() ActiveWindow.Zoom = 100 End Sub

The only problem with a macro such as this, of course, is that whenever Wanda (your colleague) opens the workbook on her system, the zoom factor is also set and she’ll get just as frustrated with you as you were with her.

Perhaps a solution is to create a more involved macro—one that checks the current screen resolution and then sets the zoom factor accordingly. For instance, the following macro could be used to make the adjustments based on resolution:

Declare Function GetSystemMetrics32 Lib "user32" _ Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long Public Sub ScreenRes() Dim lResWidth As Long Dim lResHeight As Long Dim sRes As String lResWidth = GetSystemMetrics32(0) lResHeight = GetSystemMetrics32(1) sRes = lResWidth & "x" & lResHeight

ExcelTips 2008 Page 32

Page 46: Excel tips 2008

General Tips

Select Case sRes Case Is = "800x600" ActiveWindow.Zoom = 75 Case Is = "1024x768" ActiveWindow.Zoom = 125 Case Else ActiveWindow.Zoom = 100 End Select End Sub

This routine checks the screen resolution and adjusts the window accordingly. Other resolutions and zooms may be added easily. To make the routine run automatically, just use a Workbook_Open event handler in the This Workbook code window to trigger the macro:

Private Sub Workbook_Open() ScreenRes End Sub

COUNTERING COMPRESSED COLUMNS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Mark is experiencing a problem where, when he opens a workbook, many of the column widths have been compressed (narrowed) and need to be reset. This could be caused by a number of different things, so you’ll need to do some checking.

The first thing to check is if someone else is opening the workbook. For instance, if the workbook is accessible across a network, and another person opens it, they could be changing the column widths. The user could even be doing this inadvertently. For instance, if the user has a different screen resolution than yours, then Excel will adapt the workbook to that resolution, and that may change the column widths. The solution is to either make sure that nobody else opens the workbook or make sure that everyone uses the same screen resolution.

You should also check your Zoom setting for the workbook. It could be that the column widths aren’t changing at all, but that the Zoom setting is. This would make the columns appear to be a compressed width, even though they aren’t.

Finally, it could also be that there are elements in the workbook that are forcing Excel to change column widths when they are automatically calculated. There have been reports of elements such as PivotTables and graphics causing column widths to change automatically.

ExcelTips 2008 Page 33

Page 47: Excel tips 2008

General Tips

CHANGING HORIZONTAL ORIENTATION

Applies to Excel 2002 and 2003

For those who use Excel 2002 or Excel 2003 in an international environment, you may be interested in knowing that you can change the horizontal orientation of a worksheet. Normally cell A1 is in the upper-left corner of the worksheet, but you can configure Excel so that cell A1 is in the upper-right corner of any worksheets you create. Follow these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the International tab is displayed.

The International tab of the Options dialog box.

3. Near the bottom of the dialog box, choose the Right-to-Left radio button. 4. Click on OK.

The change doesn’t affect the workbook you have open, but it does affect any new workbooks you create.

ExcelTips 2008 Page 34

Page 48: Excel tips 2008

General Tips

TAB KEY WON'T MOVE FROM CELL TO CELL IN LOCKED WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Craig created a form that has unlocked cells. When this form is protected and he is using Excel 2003 (or earlier) he can use the TAB key to move from one unlocked cell to another. However, Craig noticed that when he is using Excel 2007 the TAB key will not move from one cell to another. He wonders why this is happening; why Excel doesn’t behave as he came to expect in earlier versions of the program.

More than likely the reason is rooted in how Excel 2007 is configured. Here’s what you need to check:

1. Click the Office button and choose Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left of the dialog box. 3. Scroll through the options until you see the Lotus Compatibility category.

The advanced options of the Excel Options dialog box.

4. Make sure the Transition Navigation Keys check box is unchecked. 5. Click OK.

(Thanks to Steve Aprahamian for contributing to this tip.)

ExcelTips 2008 Page 35

Page 49: Excel tips 2008

General Tips

TURNING HEADERS ON AND OFF Applies to Excel 97, 2000, 2002, 2003, and 2007

You already know that the headers in a worksheet come in handy. This is the gray area, at the left and top of a worksheet, which indicates the row and column label used by Excel. You click in the header area if you want to select either a row or header. You also know that you can adjust the height or width or rows or columns by using the row and column header area.

Even though this area is very useful, there may be times when you do not want it displayed. For instance, if you are using Excel to create an on-screen form, then the header areas may be distracting to the intended users of the form.

To control whether headers are turned on or off, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. 2. Make sure the View tab is selected.

The View tab of the Options dialog box.

3. Make sure the Row & Column Headers check box is selected. If cleared, then the header area is not displayed.

4. Click on OK.

ExcelTips 2008 Page 36

Page 50: Excel tips 2008

General Tips

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left of the dialog box click Advanced. 3. Scroll through the available options until you see the Display Options for this

Worksheet section.

The advanced options of the Excel Options dialog box.

4. Make sure the Show Row and Column Headers check box is selected. If cleared, then the header area is not displayed.

5. Click on OK.

Notice that Excel does not allow you to control the display of row and column headers individually—they are either both on or both off.

MAKING COLUMN HEADERS VERTICALLY WIDER

Applies to Excel 2007

Robert notes that his version of Excel (2007) has a very narrow column header line (A, B, C, etc.). It is very difficult for him to even click within the column header. He can expand the height of regular rows, but wonders how he can expand the height of the header row.

ExcelTips 2008 Page 37

Page 51: Excel tips 2008

General Tips

There are a number of things to check. The height of the header row is determined automatically by Excel, based on the size of the font used in the program. Thus, you may be able to increase the header size by changing the default font used in Excel. Try these steps in Excel 2007:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box; the Popular option should be selected at the left of the dialog box.

The Excel Options dialog box.

2. Using the Font Size drop-down list, choose a different size font for the program to use. 3. Click OK. Excel informs you that for your change to take effect you need to restart the

program. 4. Restart Excel.

If Excel is not the only program in which you have problems seeing small information, you might check out your settings in Windows itself. Check to see if display configuration for your system has been changed so that small fonts are used in dialog boxes and for screen fonts. It may take some experimentation, but you might find that all your programs are easier to use after some changes.

(Thanks to Steve Aprahamian and Trevor Bundy for contributing to this tip.)

ExcelTips 2008 Page 38

Page 52: Excel tips 2008

General Tips

FORCING STUBBORN RECALCULATION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Kirk wrote that he was having a problem with the recalculation of his worksheet. He mentions that the worksheet is complicated, and that pressing F9 does not get the spreadsheet to “recalculate correctly.”

The first thing to try is to press ALT+F9 instead of just F9. When you press F9, Excel basically recalculates just the cells that have changed since the last time there was a recalculation. The ALT+F9 shortcut forces a recalculation of all cells in the worksheet.

If that doesn’t do the trick, then you may have a problem that is sometimes evident with complex worksheets: The order of the calculations done by Excel. When you calculate a worksheet, Excel basically calculates the cells from left to right and top to bottom. If you have a very large worksheet, with lots of dependent calculations, and the calculations on which everything else is dependent are at the bottom or right side of the worksheet, then you may get incorrect results. (Remember, this happens only with the most complex of worksheets.) The answer is to reorganize your worksheets so that the primary calculations are placed near the top of the worksheet and as far left as possible, and the calculations that are based on those primary calculations are placed later in the worksheet.

If you still have problems with the worksheet, try saving it as an HTML file and then reloading it into Excel. This may sound odd, but the process may help clear out any corruption that may exist in the internal pointers used by Excel.

VIEWING SAME CELLS ON DIFFERENT WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When using multiple worksheets, Chris wonders if there is a way to 'lock' the scrolling through all worksheets. For instance, if he scrolls down and across on Sheet1 until rows 100 to 140 and columns G to P are in view, then when he switches to Sheet2 (or any other worksheet) he would like the same rows and columns to be shown on those worksheets.

The only way to accomplish this task is through the use of macros. What has to happen is that the macro needs to determine which rows and columns are visible when a sheet is deactivated (being left) and then set the display of the activated sheet (the one you are going to) to the same rows and columns. The following macros, added to the ThisWorkbook module, perform exactly this task.

ExcelTips 2008 Page 39

Page 53: Excel tips 2008

General Tips

Dim grngSelection As Range Dim gintScrollColumn As Integer Dim glngScrollRow As Long Private Sub Workbook_SheetActivate(ByVal Sh As Object) If TypeName(ActiveSheet) = "Worksheet" Then On Error Resume Next With ActiveWindow Sh.Range(grngSelection.Address).Select .ScrollColumn = gintScrollColumn .ScrollRow = glngScrollRow End With End If End Sub

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object) Dim oSheet As Object If TypeName(Sh) = "Worksheet" Then Set oSheet = ActiveSheet Application.EnableEvents = False Sh.Activate With ActiveWindow gintScrollColumn = .ScrollColumn glngScrollRow = .ScrollRow Set grngSelection = .RangeSelection End With oSheet.Activate Application.EnableEvents = True End If End Sub

Note the use of the variables outside of the event handlers. These variables are used to pass the values of the column, row, and selected area from the SheetDeactivate handler to the SheetActivate handler.

Of course, you may not want an automatic solution. Instead, you may want the user to take a specific step to trigger whether the worksheets are synchronized. This can be done by adding the following macro to a regular module in your workbook:

Global WindowScrollRow Global WindowScrollCol Global WindowSyncOn As Boolean Public Sub WindowLock() If Not WindowSyncOn Then WindowScrollRow = ActiveWindow.VisibleRange.Row WindowScrollCol = ActiveWindow.VisibleRange.Column Application.StatusBar = "WindowSync: ON" Else Application.StatusBar = "" End If WindowSyncOn = Not WindowSyncOn

ExcelTips 2008 Page 40

Page 54: Excel tips 2008

General Tips

End Sub

All that this macro does is to check the status of the global variable WindowSyncOn. If the value is False, then the current settings for the top visible row and leftmost visible column are stored into global variables. The setting of these variables are then used by the following event handler, added to the ThisWorkbook module:

Private Sub Workbook_SheetActivate(ByVal Sh As Object) If WindowSyncOn Then If Not ActiveWindow Is Nothing Then ActiveWindow.ScrollRow = WindowScrollRow ActiveWindow.ScrollColumn = WindowScrollCol End If End If End Sub

The macro simply checks the setting of the WindowSyncOn variable, and if it is True (it has been set), then the macro sets which row and column are at the top and left of the active window.

(Thanks to Andrija Vrcan, Steve Aprahamian, Richard Raciborski, Dave Latham, Attila Molnar, and Peter Atherton for contributing to this tip.)

BACKING UP CUSTOM DICTIONARIES

Applies to Excel 97, 2000, 2002, 2003, and 2007

The Excel spell-check program allows you to create a number of custom dictionaries for your use. At some time you may want to copy the custom dictionaries, either for a personal backup or to transfer to a different computer.

The default custom dictionary used by Excel is Custom.dic. However, custom dictionaries can be saved under any number of different names. You can see the name of the custom dictionary you are using by choosing Options from the Tools menu, then displaying the Spelling tab. The Add Words To drop-down list shows the name of the custom dictionary.

ExcelTips 2008 Page 41

Page 55: Excel tips 2008

General Tips

The Spelling tab of the Options dialog box.

In Excel 2007 you can see the name of the custom dictionary by clicking the Office button, choosing Excel Options, clicking Proofing, and then clicking the Custom Dictionaries button.

The Custom Dictionaries dialog box.

The safest course to backing up custom dictionaries is to look for any file that has the DIC file name extension. Use the Windows Search tool to locate the files. You can then copy these files to some sort of backup media, such as an external hard drive, CD-ROM, or flash drive.

ExcelTips 2008 Page 42

Page 56: Excel tips 2008

General Tips

DISABLING A FUNCTION KEY Applies to Excel 97, 2000, 2002, 2003, and 2007

Jean recently asked if there is a way to disable the F1 key in Excel. It seems that she frequently presses F1 when she means to press F2, and doing so is bothersome.

The only way to disable a key such as this is to create a macro. The following macro will do the trick quite nicely:

Private Sub Workbook_Open() Application.OnKey "{F1}", "" End Sub

Private Sub Workbook_BeforeClose(CANCEL As Boolean) Application.OnKey "{F1}" End Sub

Actually, there are two macros here. The first one executes whenever the workbook is opened, and the second is executed when the workbook is closed. In the case of the first macro, the OnKey method traps every keypress of F1 and cancels it. The macro that runs when the workbook closes restores the normal operation of the F1 key.

These macros can be placed in a given workbook, in which case they will only apply while that workbook is open. If you want them to apply at all times when using Excel, store the macros in the Personal.xls workbook. (The use of this workbook has been covered in other issues of ExcelTips. You can also find information on it in the Excel Help system.)

SIMPLIFYING THE FONT LIST Applies to Excel 2000, 2002, 2003, and 2007

When you click the Font drop-down list on the Formatting toolbar, Excel shows you the names of all the fonts you can use to format whatever you have selected on the screen. Normally, Excel shows the font names using the actual font. You may find the differing font faces to be distracting, or your slower computer may be really slow when listing all the fonts.

Whether you can turn this capability off or not depends on the version of Excel you are using. If you are using a version of Excel prior to Excel 2007, the program provides a control that turns the feature on or off. If you are using Excel 2007 the control has been removed; you cannot simplify the font list and it must be displayed using the actual fonts.

To turn this feature off in Excel 2000, Excel 2002, or Excel 2003, follow these steps:

1. Select Customize from the Tools menu. Excel displays the Customize dialog box.

ExcelTips 2008 Page 43

Page 57: Excel tips 2008

General Tips

2. Make sure the Options tab is displayed.

The Options tab of the Customize dialog box.

3. Clear the List Font Names In Their Font check box. 4. Click Close.

SHORTCUT FOR VIEWING FORMULAS

Applies to Excel 97, 2000, 2002, 2003, and 2007

You probably already know how to display the formulas in cells rather than the results of those formulas, right? If you’re like most people, you choose Tools | Options, then on the View tab make sure the Formulas check box is selected. The process is even longer in Excel 2007—click the Office button | Excel Options | Advanced | Display Options for this Worksheet group | Show Formulas in Cells Instead of their Calculated Result check box.

A much faster way to get the same result is to press CTRL+`. (That’s hold down the Ctrl key while you press the accent grave, which is the backwards apostrophe just to the left of the 1 key and above the Tab key.) The shortcut is a toggle, which means that you can press it repeatedly to switch between the display of formulas and results.

ExcelTips 2008 Page 44

Page 58: Excel tips 2008

Editing Tips

CREATING NEW WINDOWS Applies to Excel 97, 2000, 2002, 2003, and 2007

If you want to work on two different parts of the same workbook at the same time, there are a couple of different ways you can do so. One way is to open a second window. You do this by simply choosing New Window from the Window menu or, in Excel 2007, displaying the View tab of the ribbon and clicking New Window in the Window group. Excel opens a new window. You can then use each window to display and edit different parts of the same workbook.

Notice that each new window you create has not only the workbook name in the title bar, but also a number that indicates the actual window number. Thus, you could have Book1:1 and Book1:2. These are the same way that the window names appear at the bottom of the Window menu (or on the Switch Windows drop-down list of the ribbon’s View tab in Excel 2007) and on the Task bar.

Each window created in this way just provides a different way to look at the exact same workbook. This means that any change you make in one window is automatically and immediately made in the other window as well.

CANCELING AN EDIT Applies to Excel 97, 2000, 2002, 2003, and 2007

As you are entering information in a cell, you may want to cancel what you are entering. For instance, you may have selected the wrong cell before you started typing, and you want to “back out” of the edit you are making.

There are two ways you can do this. The first is to simply press the ESC key, and the other is to click on the red X just to the left of the Formula bar. (The red X only appears after you start typing.) Regardless of the method you choose, Excel undoes your changes and returns the cell to its state just before you started typing.

ExcelTips 2008 Page 45

Page 59: Excel tips 2008

Editing Tips

If you make a mistake and press ENTER, Excel replaces the contents of the cell with whatever you were typing. To undo this, you should use the Undo feature of Excel: simply press CTRL+Z or click on the Undo tool on the toolbar.

QUICKLY SELECTING CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

You already know that you can use the mouse to select a range of cells by holding down the left mouse button and dragging the mouse to make a selection. There is an even quicker way to select cells using the mouse, however. This is done in the following manner:

1. Select the cell that marks one corner of the range of cells you want to select. 2. Move the mouse pointer so it points to the cell at the opposite diagonal corner of the

range you want selected. 3. Hold down the SHIFT key as you click once on the left mouse button.

SELECTING NONCONTIGUOUS RANGES WITH THE KEYBOARD

Applies to Excel 97, 2000, 2002, 2003, and 2007

Most people know that you can select a noncontiguous range of cells by using the mouse. All you need to do is click the first cell in the range, and then hold down the CTRL key as you click other cells in the range. (This is often referred to as creating a selection set of cells.)

Some folks don’t like using the mouse that much. If you are in that camp, you may wonder if there is a way to select a noncontiguous range simply by using the keyboard. Fortunately there is, but very few folks know about it. Provided that you know the addresses of the cells you want in the range, follow these steps:

1. Press F5. Excel displays the Go To dialog box.

ExcelTips 2008 Page 46

Page 60: Excel tips 2008

Editing Tips

The Go To dialog box.

2. In the Reference box at the bottom of the dialog box, type the address of the first cell or range you want selected.

3. Type a comma, followed by an additional range. 4. Repeat step 3 for each additional cell or range you want in the selection set. 5. Click OK (or press ENTER). Excel selects all the cells and ranges you entered in the

Reference box.

As an example, if you wanted your noncontiguous range to include cells A7, B2, F14 through G22, and T18, you would enter the following into the Reference box:

A7,B2,F14:G22,T18

Clicking OK then selects all these cells. In addition, the last cell that you entered is the “active cell” in the selected range.

DISPLAYING A HIDDEN FIRST ROW

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel makes it easy to hide and unhide rows using the menus. What isn’t so easy is displaying a hidden row if that row is above the first visible row in the worksheet. For instance, if you hide rows 1 through 5, Excel will dutifully follow out your instructions. If you later want to unhide any of these rows, the solution isn’t so obvious.

To unhide the top rows of a worksheet when they are hidden, follow these steps:

ExcelTips 2008 Page 47

Page 61: Excel tips 2008

Editing Tips

1. Press F5. Excel displays the Go To dialog box.

The Go To dialog box.

2. In the Reference field at the bottom of the dialog box, enter the number of the row range that you want to unhide. For instance, if you want to unhide rows 2 through 3, enter 2:3. Likewise, if you want to unhide row 1, enter 1:1.

3. Click on OK. The rows you specified are now selected, even though you cannot see it on the screen.

4. Choose Row from the Format menu, then choose Unhide.

COPYING BETWEEN INSTANCES OF EXCEL

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you’ve ever worked with a system that is configured for two monitors, it is really quite amazing; it can change the way you work. For example, you might open two instances of Excel and put one of them on one monitor and the other on the other monitor. You can then work with both workbooks onscreen at the same time.

One thing you’ll notice, however, is that copying information from one instance of Excel to another works differently than when you copy within the same instance. If you copy a cell that contains a formula and then paste it in the other instance, what gets pasted is the result of the formula, not the formula itself. You can’t even use Paste Special from the Edit menu to paste formulas; that isn’t an option when working with two instances.

ExcelTips 2008 Page 48

Page 62: Excel tips 2008

Editing Tips

Unfortunately, there is no easy way to get formulas from one instance of Excel to another. The best you can do is the following:

1. In the source workbook, select a single cell that you want to copy. 2. Press F2. Excel switches to Edit mode. 3. While still in Edit mode, select everything in the cell (the entire formula). 4. Press CTRL+C. Excel copies the formula to the Clipboard. 5. Press ESC to exit Edit mode. 6. In the target workbook, select the cell where you want the formula pasted. 7. Press F2. Excel again switches to Edit mode. 8. Press CTRL+V. The formula is pasted into the cell. 9. Press ENTER. Edit mode is exited, and the formula is now safely in the target cell.

This tedious procedure must be used for each formula you want to copy between instances. For this reason, many people choose not to use separate instances of Excel, even if they have the luxury of multiple monitors. Instead, the work with different windows within the same instance of Excel. Follow these steps:

1. Open the two workbooks you want to work with. 2. Choose Arrange from the Window menu. Excel displays the Arrange Windows dialog

box. (To see this dialog box in Excel 2007 display the View tab of the ribbon and click the Arrange All tool in the Window group.)

The Arrange Windows dialog box.

3. Choose Tiled. (You can choose other options, if you prefer, but I find that Tiled works best for me.)

4. Click OK. The two workbooks are now side-by-side in the program window. 5. Make sure the Excel window is not maximized. (Click the Restore button at the upper-

right corner of the program window.) 6. Position the non-maximized window in the left-most of your monitors. 7. Drag the right border of the Excel program window onto the second monitor. A single

instance of Excel now covers both monitors.

ExcelTips 2008 Page 49

Page 63: Excel tips 2008

Editing Tips

8. Within the Excel window, use the mouse to arrange the two workbooks so one is on each monitor.

Since you are using a single instance of Excel—even though it extends across two monitors—you can now cut, copy, and paste as you normally would.

PASTING WITHOUT UPDATING REFERENCES

Applies to Excel 97, 2000, 2002, 2003, and 2007

As you are working on a worksheet, copying and moving information from one place to another, you may wonder if there is a way to copy or move a selection without Excel changing all the references within the selection. The answer, of course, is that it depends. (Don’t you just love that about Excel?) Let’s take a look at how you can both copy and move selections in Excel.

If you are copying a selection, then Excel will update all relative references within the selection when you paste it. The solution, of course, is to make sure that all the references within the selection are absolute before doing the copy and paste. Making the changes to the formulas by hand is tedious. You can use the following macro to convert all the formulas in the selection to their absolute equivalent:

Sub ConvertToAbsolute() Dim c As Variant Application.ScreenUpdating = False For Each c In Selection c.Value = Application.ConvertFormula(c.Formula, _ xlA1, , xlAbsolute) Next c Application.ScreenUpdating = True End Sub

Once this macro is run, you can copy and paste the selection without Excel doing any updating to references. Once the pasting is done, you can change the references in the selection (and in the original range, if it still exists) by selecting the range and applying this macro:

Sub ConvertToRelative() Dim c As Variant Application.ScreenUpdating = False For Each c In Selection c.Value = Application.ConvertFormula(c.Formula, _ xlA1, , xlRelative, c) Next c Application.ScreenUpdating = True End Sub

ExcelTips 2008 Page 50

Page 64: Excel tips 2008

Editing Tips

This macro will change all formulas in the selected range to their relative equivalent. Remember that this will affect all formulas—which means that if the formulas in the range contained both relative and absolute references, when this macro is done, they will all be relative.

If you are moving a selection, then Excel does not update cell references in the move. You can move either by selecting the range and using the keyboard (pressing CTRL+X to cut and then CTRL+V to paste the selection) or the mouse (dragging the selection to a new location). In either case, Excel leaves the references in the selection exactly the same—relative or not—without updating.

So far I have discussed what Excel does with the references in the selection being copied or moved. What about references to the information in the selection? If you are copying, then Excel leaves references pointing to the original range. If you are moving a selection, then Excel updates references to that selection, regardless of whether they are relative or absolute. If you don’t want the information updated during a move, then the solution is to make a copy of the range and then delete the original.

CONVERTING FROM RELATIVE TO ABSOLUTE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to easily edit formulas. In doing so, you can quickly change a cell reference or a range reference from relative to absolute. What if you have a large number of cells in which you need to change from relative to absolute referencing? In this instance, the nature of the problem is well-suited to being solved through a macro.

By using the ConvertFormula method available in VBA, you can easily convert a formula from relative to absolute addressing. The following short macro uses this method to change the addressing method used in a range of cells:

Sub Relative2Absolute() For Each c In Selection If c.HasFormula = True Then c.Formula = Application.ConvertFormula(c.Formula, _ xlA1, xlA1, xlAbsolute) End If Next c End Sub

The key to how this macro works is, of course, in the ConvertFormula method. The last parameter used by the method is—in this case—xlAbsolute. If you want to adapt the macro so that it changes to other types of addressing, you can change xlAbsolute to xlRelative, xlAbsRowRelColumn, or xlRelRowAbsColumn. (I’m sure you can figure out the purpose of each constant by its name.)

ExcelTips 2008 Page 51

Page 65: Excel tips 2008

Editing Tips

INSERTING AND COPYING ROWS Applies to Excel 97, 2000, 2002, 2003, and 2007

As you are editing worksheets, you may notice that some of your work is done based on work you have done before. For instance, you may have a row of data that you entered in a previous Excel session. In this session, you need to copy that row of data and use it as the basis for your new data, but with a few changes.

In such a situation, it would be nice to have a quick way to enter a blank row after the current row, and copy the data in the current row to the new blank row. There are no intrinsic commands in Excel to do this, but a macro can do it very handily. Consider the following example:

Sub InsertCopyRow1() ActiveCell.EntireRow.Select Selection.Copy Selection.Insert Shift:=xlDown End Sub

In order to use the macro, all you need to do is select a cell in any row. When the macro is run, a duplicate of the current row is inserted just below the row you are in.

The only problem with this solution is that it leaves the Excel interface a bit “messy” (for lack of a better word). When completed, a complete row is still selected, and the new row has the “marching ants” marquee around it.

This problem can be overcome by including commands to collapse the selection and move it to a desired location. Another way is to simply use a different macro that relies on different VBA commands. The following macro will also insert and copy a row, but it leaves the cell that you selected active:

Sub InsertCopyRow2() ActiveCell.Offset(1, 0).EntireRow.Insert ActiveCell.EntireRow.Copy ActiveCell.Offset(1, 0).EntireRow End Sub

MOVING AND SELECTING ROWS Applies to Excel 97, 2000, 2002, 2003, and 2007

James asked if there is a keyboard shortcut to move down a row and select the entire row. In Excel there is no way to do this with a single keystroke, but there is a way to do it using two keystrokes. All you need to do is press the DOWN ARROW, immediately followed by pressing SHIFT+SPACE BAR.

ExcelTips 2008 Page 52

Page 66: Excel tips 2008

Editing Tips

If you do a lot of this type of moving about, however, you would probably be more interested in a macro that combines the two steps into a single step that can be initiated by a shortcut key. The following macro will work:

Sub SelectRowDown1() If ActiveCell.Row < 65536 Then ActiveCell.Offset(1, 0).Select ActiveCell.EntireRow.Select End If End Sub

If you assign this to a shortcut key, such as CTRL+D, then every time you press the shortcut key, you move down a row and it is selected. The problem with this approach, however, is that after the macro has been run, the first cell in the row is always the active cell. This is different than if you use the DOWN ARROW, SHIFT+SPACE BAR method of moving and selecting.

It is apparently the EntireRow.Select method that results in the first cell being activated. To get around this problem, all you need to do is determine which column you were in, and then activate that cell. The following version of the macro does just that:

Sub SelectRowDown2() If ActiveCell.Row < 65536 Then ActiveCell.Offset(1, 0).Select iCP = ActiveCell.Column ActiveCell.EntireRow.Select ActiveCell.Offset(0, iCP - 1).Activate End If End Sub

If you are interested in a macro that moves up, you can use this macro:

Sub SelectRowUp() If ActiveCell.Row > 1 Then ActiveCell.Offset(-1, 0).Select iCP = ActiveCell.Column ActiveCell.EntireRow.Select ActiveCell.Offset(0, iCP - 1).Activate End If End Sub

You can assign this macro to the CTRL+U shortcut key, and then your movement macros will be complete.

If you need something that is more “high powered” than these macros, check out the RowLiner add-in from Pearson Software Consulting Services:

http://www.cpearson.com/excel/RowLiner.htm

ExcelTips 2008 Page 53

Page 67: Excel tips 2008

Editing Tips

ENTERING NUMBERS IN EXCEL Applies to Excel 97, 2000, 2002, 2003, and 2007

When you enter information into a cell in your worksheet, you may wonder exactly how Excel translates what you enter. Excel first tries to convert information into numbers. Numbers are just that—any of the digits (0 through 9), optionally with special characters. The most common of these special characters are the period (taken to be a decimal point), a comma between numbers, a minus sign or plus sign, and a percent sign after the number. If you use the percent sign, Excel assumes you are entering a percentage, and thereby divides the number by 100 for internal storage.

Other special characters can be used, as well. For instance, if you preface your number with a dollar sign, Excel assumes you are entering a currency amount. You can also enter numbers surrounded by parentheses—such as (123)—which is another way of indicating a negative number. The slash character (/) can be used to indicate either a fraction or a date. Finally, you can use the letter E (upper- or lowercase) to indicate that you are entering a number in scientific notation. All of these different numbers and symbols are summarized in the following table:

Symbol Meaning – If used before a number or after a number followed by the letter E (as in

123E–45), it is taken as a negative sign. If entered between numbers, assumed first to be a date separator, unless the numbers are illegal for a date; in which case it is considered text. If entered after a number, then the entry is assumed to be text.

+ If used before a number or after a number followed by the letter E (as in 123E+45), it is ignored. If entered between or after numbers, it is considered text.

() When completely surrounding a number, assumed to be a negative sign. In all other instances (except in formulas), assumed to be text.

, When followed by at least three digits, assumed to be a hundreds separator. In all other instances, assumed to be text.

/ If entered between numbers, assumed first to be a date separator—provided the numbers can be translated to a valid date. In all other instances, assumed to be text.

$ When preceding digits, assumed to indicate that the number represents currency. In all other instances, assumed to be text.

% When following digits, assumed to indicate that the number represents a percentage. In all other instances, assumed to be text.

. When used once within an entry, assumed to be a decimal point. In all other instances, assumed to be text.

E or e When used once within an entry, assumed to indicate that the number is being entered in scientific notation. The value to the left of the E is normalized to between 1 and 10, and the value to the right is used to represent the power to which the value is raised.

Remember that when you use symbols in your numbers, they must make sense. For instance, you cannot input two decimal points or two percent signs and expect Excel to understand what you

ExcelTips 2008 Page 54

Page 68: Excel tips 2008

Editing Tips

are doing. If you try entering such a nonsensical number, chances are Excel will assume you are entering text.

ENTERING INFO INTO MULTIPLE CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

It is not unusual to enter the same information in multiple cells in Excel. If you have such a need, you might want to try this little gem:

1. Select all the cells that will contain the information. If the cells are not contiguous, hold down the CTRL key as you click on each cell in the set.

2. Type the information you want to enter, but don’t press ENTER. 3. Press CTRL+ENTER.

Presto! Every cell you selected contains the same information.

LIMITING ENTRIES TO NUMERIC VALUES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Gary has a worksheet that people in his office use for data entry. He wants to make sure that in a particular cell they can only enter a numeric value. He wonders how to stop them from entering other entries—like text or dates or times—in the cell.

The easiest way to do this is to use Excel’s data validation feature. This feature allows you to define the parameters of what can be entered in a cell. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Select the cell you want used for inputting a value. 2. Choose Validation from the Data menu. Excel displays the Settings tab of the Data

Validation dialog box.

ExcelTips 2008 Page 55

Page 69: Excel tips 2008

Editing Tips

The Settings tab of the Data Validation dialog box.

3. Using the Allow drop-down list, choose either Whole Number or Decimal, depending on which type of numeric input you want to allow. Excel changes the controls available in the dialog box.

4. Using the Data drop-down list, make sure Between is selected. 5. Enter in the Minimum and Maximum boxes the lower and upper bounds of what you

want users to enter in the cell. 6. On the other tabs of the dialog box, enter an input message and an error message, if

desired. 7. Click OK.

If you are using Excel 2007, follow these steps instead:

1. Select the cell you want used for inputting a value. 2. Display the Data tab of the ribbon. 3. In the Data Tools group, click the Data Validation tool. Excel displays the Data

Validation dialog box. 4. Using the Allow drop-down list, choose either Whole Number or Decimal, depending

on which type of numeric input you want to allow. Excel changes the controls available in the dialog box.

5. Using the Data drop-down list, make sure Between is selected. 6. Enter in the Minimum and Maximum boxes the lower and upper bounds of what you

want users to enter in the cell.

ExcelTips 2008 Page 56

Page 70: Excel tips 2008

Editing Tips

7. On the other tabs of the dialog box, enter an input message and an error message, if desired.

8. Click OK.

People can now enter only a numeric value within the range you specified. The one exception to this is dates and times. Since they are maintained internally, by Excel, as numbers, it is possible to enter a date, provided the date is parsed into a numeric value that is within the range you specify.

For instance, if you set up data validation to only allow values between 20,000 and 21,000, then someone could enter a date of 6/11/1956 because Excel parses the date to the whole number 20,617. The best way to handle dates and times is to format the cell so that it uses a numeric format, which will stop Excel from displaying dates and times.

LIMITING INPUT TO A FORMAT Applies to Excel 97, 2000, 2002, 2003, and 2007

As you are developing a spreadsheet, you may want to limit what users are able to put into a particular cell. For instance, you might want to make sure that entries in a cell are exactly four characters long, begin with the number 6, are followed by any digit, then by a letter, and then by any digit.

There are three ways to go about such a validation. The first, of course, is to write a macro that will check input and ensure that the entries follow the desired pattern. The way to concoct such a macro has been covered in other issues of ExcelTips.

Another method, without using macros, is to rely upon the data validation feature of Excel. If the number of valid entries is not terribly long, you might try these general steps:

1. On a blank worksheet, construct a list of the valid entries. 2. On the worksheet used for input, highlight the cell into which the entry will be made. 3. Choose Validation from the Data menu. Excel displays the Data Validation dialog box.

(To display the dialog box in Excel 2007 display the Data tab of the ribbon and click Data Validation in the Data Tools group.)

ExcelTips 2008 Page 57

Page 71: Excel tips 2008

Editing Tips

The Data Validation dialog box.

4. Using the Allow drop-down list, choose List. 5. With the insertion point in the Source box, choose the list you put together in step 1. 6. Click on OK.

Now, whenever someone tries to enter data that is not included in your list of acceptable values, the validation rules kick into effect and the user is forced to change the entry.

You can also use the data validation feature in a bit of a different way. If you have well-defined rules for your data entry then you can put together a formula that describes a valid entry. The following is one such formula:

=AND((LEN(A1)=4),(LEFT(A1,1)="6"),(ISNUMBER(VALUE( (MID(A1,2,1))))),(CODE(MID(UPPER(A1),3,1))>64),(CODE( MID(UPPER(A1),3,1))<91),(ISNUMBER(VALUE((MID(A1,4,1))))))

Remember that this is a single formula, entered all on one line, using the following general steps:

1. Highlight the cell into which the entry will be made. (The above formula assumes you are using cell A1. If a different cell is selected, you will need to make the appropriate reference changes to the above formula.)

2. Choose Validation from the Data menu. Excel displays the Data Validation dialog box. (To display the dialog box in Excel 2007 display the Data tab of the ribbon and click Data Validation in the Data Tools group.)

3. Using the Allow drop-down list, choose Custom. 4. Enter the above formula in the Formula box. (All one line, no spaces.) 5. Click on OK.

ExcelTips 2008 Page 58

Page 72: Excel tips 2008

Editing Tips

You may get an error when you click on OK, based on the contents of A1. (Excel may try to tell you that the contents of A1 don't validate according to the rule.) This is OK; the validation rule you are setting up will come into play when someone tries to enter something in the cell.

The formula basically pulls apart the entry being made and determines if each character is within bounds. If not, then the result of the formula is FALSE, and the validation rules come into play.

DEALING WITH LONG FORMULAS Applies to Excel 97, 2000, 2002, 2003, and 2007

Anyone who has been using Excel for any length of time knows that some formulas can get quite long. Excel handles them—as long as they are constructed correctly—but they can be a bear for humans to understand. Even after you develop your own formulas, you may have trouble understanding them weeks or months later.

One way to make formulas a bit easier to understand is to use ALT+ENTER in the middle of the formula to “format” how it appears on the screen. Consider, for instance, the following long formula:

=+IF($A2=0,0,IF($B2<4264,0,IF(AND($B2>=4264,$B2<=4895), (-22.31*$C2/365),IF(AND($B2>=4895,$B2<=32760),($B2*0.093- 476.89)*$C2/365,IF($B2>32760,($B2*0.128-1623.49)*$C2/365)))))

This formula could also be written in the following manner, with ALT+ENTER being pressed at the end of each line in the formula:

=+IF($A1=0,0, IF($B1<4264,0, IF(AND($B1>=4264,$B1<=4895),(-22.31*$C1/365), IF(AND($B1>=4895,$B1<=32760),($B1*0.093-476.89)*$C1/365, IF($B1>32760,($B1*0.128-1623.49)*$C1/365)))))

Now, the broken-up formula appears on five lines, even though it all appears in a single cell. The broken-up formula works just as if it were all on one line.

In addition, if you copy the complete broken-up formula from the Formula bar and paste it into a worksheet, each line in the formula is pasted into a different cell, making it easy to test each part. This is much quicker than copying and pasting parts of the original formula.

ExcelTips 2008 Page 59

Page 73: Excel tips 2008

Editing Tips

TRANSPOSING YOUR DATA Applies to Excel 97, 2000, 2002, 2003, and 2007

You probably know the feeling—you start creating a worksheet, get a good way into it, and realize that you should have made your columns into rows and your rows into columns. In other words, you want to turn your data by 90 degrees and continue working with the sheet.

Fortunately, Excel provides an easy way to accomplish this very task. In Excel's terminology, this process is known as transposing data. To transpose your data, follow these steps:

1. Select the range of cells you want to transpose. 2. Press CTRL+C to copy the data from the worksheet and place it in the Clipboard. 3. Select the cell that will be at the top-left corner of your newly transposed data. 4. Choose Paste Special from the Edit menu. Excel displays the Paste Special dialog box.

(To display this dialog box in Excel 2007, display the Home tab of the ribbon and click the down-arrow under the Paste tool at the left side of the ribbon. Select Paste Special from the resulting menu.)

The Paste Special dialog box.

5. Select the Transpose check box. 6. Click on OK. Your data appears at the point you specified, but it is transposed.

Notice that in step 2 you must use the copy command (CTRL+C) rather than the cut command (CTRL+X). This is because you can't choose Paste Special from the Edit menu when you cut information. For this reason, you may want to copy information from one worksheet (steps 1 and

ExcelTips 2008 Page 60

Page 74: Excel tips 2008

Editing Tips

2) and paste it into another (steps 3 through 6). You can play with this method of pasting and select the method that is best for you.

You should note, as well, that Excel 2007 provides a handy shortcut unavailable in earlier versions of the program. Instead of selecting Paste Special in step 4, you could skip the Paste Special dialog box entirely by choosing Transpose from the Paste menu. (Very handy, indeed.)

DRAGGING TO CLEAR CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

Want a really quick way to clear the cells in a range you’ve selected? If you’ve got a hold of the mouse, simply grab the fill handle (the small square at the bottom-right corner of the selection) and drag it back over the selection area. As you drag, the cells are grayed out, and when you release the mouse button the values in the cells are cleared.

If you also want to clear the formats in the cells, just hold down the CTRL key as you drag the fill handle back over the selection.

DELETING BLANK COLUMNS Applies to Excel 97, 2000, 2002, 2003, and 2007

When importing information from an external source, it is possible that the data will contain blank columns—columns with nothing in them. If you import a lot of data, then deleting these columns can be a bother. There are a couple of ways you can approach how to delete these columns.

The first approach works very well if your data is sorted by column. In other words, the data that you import is in ascending order, or you want it in sorted order. In this case, follow these steps:

1. Select the columns that represent your data. Make sure you select, as part of the range, all the blank columns as well.

2. Choose the Sort option from the Data menu. Excel displays the Sort dialog box. (To display the dialog box in Excel 2007, display the Data tab of the ribbon and then click Sort.)

3. Click the Options button. Excel displays the Sort Options dialog box.

ExcelTips 2008 Page 61

Page 75: Excel tips 2008

Editing Tips

The Sort Options dialog box.

4. Choose the Sort Left to Right radio button. 5. Click on OK to dismiss the Sort Options dialog box. 6. Using the first Sort By drop-down list, specify the row by which you want to sort. 7. Click on OK.

When sorting in this manner, all the empty columns end up “pushed” to the right, and your data is in a sorted order.

If you don’t want your data sorted, then you can use a nifty macro that will check for blank columns in a selected range and then delete those columns. The following macro will do the trick:

Sub DeleteEmptyColumns() first = Selection.Column last = Selection.Columns(Selection.Columns.Count).Column For i = last To first Step -1 If WorksheetFunction.CountBlank(ActiveSheet.Columns(i)) = 65536 Then Columns(i).Delete End If Next i End Sub

To use the macro, select the range of columns in which you want blank columns deleted. The macro steps through the columns and if the column is truly blank, it is deleted. You should note that this macro will delete only columns that are truly empty. If cells within a column include a formula that returns a zero value (and you have the display of zeros values turned off) or that returns an empty string, then the column isn’t empty—it contains formulas. In this case, the column won’t be deleted.

ExcelTips 2008 Page 62

Page 76: Excel tips 2008

Editing Tips

CONDITIONALLY DELETING ROWS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you are working with data tables containing information that you received from another person, you may want to prune the amount of data in the table by deleting rows if a particular condition is met. There are several ways you can approach such a task.

The first method is to use Excel’s AutoFilter feature. This works particularly well if you have a rather simple criteria by which to delete rows. When you turn on the AutoFilter, Excel places pull-down buttons at the right side of each cell in the data table’s header row. Using these pull-down buttons you can specify the records you want displayed. You should select a filter value that will result in displaying only those rows you want to delete. With those rows displayed, you can select them and use the menus or ribbon tools to get rid of the rows. When you turn AutoFilter off, then you are left with only the rows you wanted.

Another method involves the use of macros to do the deleting for you. This approach works well if you have to perform the deletions on lots of data, or if you do it quite often. The following macro can delete rows based on a key value:

Sub DeleteRows() Dim strToDelete As String Dim rngSrc As Range Dim NumRows As Integer Dim ThisRow As Integer Dim ThatRow As Integer Dim ThisCol As Integer Dim J As Integer Dim DeletedRows As Integer strToDelete = InputBox("Value to Trigger Delete?", "Delete Rows") Set rngSrc = ActiveSheet.Range(ActiveWindow.Selection.Address) NumRows = rngSrc.Rows.Count ThisRow = rngSrc.Row ThatRow = ThisRow + NumRows - 1 ThisCol = rngSrc.Column For J = ThatRow To ThisRow Step -1 If Cells(J, ThisCol) = strToDelete Then Rows(J).Select Selection.Delete Shift:=xlUp DeletedRows = DeletedRows + 1 End If Next J MsgBox "Number of deleted rows: " & DeletedRows End Sub

ExcelTips 2008 Page 63

Page 77: Excel tips 2008

Editing Tips

To use the macro, select the range the key range that covers the rows you want checked. For instance, if the key to be checked is in column G, and you want to check rows 5 through 73, then you would select the range G5:G73. When you run the macro, it asks you what value it should check for. If any cells in the range G5:G73 contain the value you specify, the corresponding row for that cell will be deleted.

There are obviously other ways to delete rows based on a value. For a good selection of different methods, take a look at this page by Dave Hawley at Ozgrid:

http://www.ozgrid.com/VBA/VBACode.htm

ADDING POP-UP DOCUMENTATION TO A CELL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Want a neat trick you can use to make your worksheets more helpful to users? How about adding a pop-up window that displays documentation whenever the cell is selected? To add such a feature, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Select the cell for which you want the pop-up to appear. 2. Choose Validation from the Data menu. 3. Make sure the Input Message tab is displayed.

ExcelTips 2008 Page 64

Page 78: Excel tips 2008

Editing Tips

The Input Message tab of the Data Validation dialog box.

4. Make sure the Show Input Message When Cell is Selected check box is selected. 5. In the Title box, enter a title for the pop-up window. (This title appears in bold at the top

of the pop-up window.) 6. In the Input Message box, enter the text of the documentation you want to appear in the

pop-up window. 7. Click OK.

If you are using Excel 2007 then you should follow these steps:

1. Select the cell for which you want the pop-up to appear. 2. Display the Data tab of the ribbon. 3. In the Data Tools group, click the Data Validation tool. Excel displays the Data

Validation dialog box. 4. Make sure the Input Message tab is displayed. 5. Make sure the Show Input Message When Cell is Selected check box is selected. 6. In the Title box, enter a title for the pop-up window. (This title appears in bold at the top

of the pop-up window.) 7. In the Input Message box, enter the text of the documentation you want to appear in the

pop-up window. 8. Click OK.

ExcelTips 2008 Page 65

Page 79: Excel tips 2008

Editing Tips

There are, obviously, other ways you can use the Data Validation feature of Excel to check and limit the data that is entered in a cell. However, if you follow the steps above, all data is still accepted, and Excel displays a helpful message whenever the cell is selected.

CORRECTING A CAPITAL MISTAKE

Applies to Excel 97, 2000, 2002, 2003, and 2007

I can’t tell you the number of times that I’ve been feverishly typing away, without glancing up at my worksheet. I get in a “groove,” and I keep typing away, figuring I will check things out when I get to the end of a row or a column. When I finally look up, I notice that I had the Caps Lock key selected, so all my normal text is in uppercase, and everything I wanted in upper case is in lowercase. This happened because I hit the Caps Lock key by mistake, and didn’t notice the mistake until I’d already entered quite a bit of data.

Fortunately, Excel can catch this type of mistake for me—if I tell it to catch it. Follow these steps:

1. Depending on your version of Excel, choose either AutoCorrect or AutoCorrect Options from the Tools menu. Excel displays the AutoCorrect dialog box. (To display the AutoCorrect dialog box in Excel 2007, click the Office button and then click Excel Options. Click Proofing, and then click AutoCorrect Options.)

2. Display the AutoCorrect tab.

ExcelTips 2008 Page 66

Page 80: Excel tips 2008

Editing Tips

The AutoCorrect tab of the AutoCorrect dialog box.

3. Make sure the Correct Accidental Use of cAPS LOCK Key check box is selected. 4. Click on OK.

Now, if I type something in a cell and the first letter is lowercase and the rest of the letters are uppercase, Excel figures that I’ve got the Caps Lock key selected, and helpfully turns it off. It also corrects the capitalization of my text entry.

MODIFYING PROPER CAPITALIZATION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Like many people, Kirk copies information into Excel worksheets that originates in other places. The information that Kirk copies typically is all in CAPS, and he wants to convert it to what Excel refers to as “proper case” (only the first letter of each word is capitalized). The problem is, the PROPER worksheet function, which does the conversion, doesn’t pay attention to the words it is capitalizing. Thus, words like a, an, in, and, the, and with are all initial-capped. Kirk doesn’t want those words (and perhaps some others) capitalized.

ExcelTips 2008 Page 67

Page 81: Excel tips 2008

Editing Tips

There are several ways you can approach this problem. One is to use a rather long formula to do the conversion:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE( SUBSTITUTE(SUBSTITUTE(PROPER($B$13);" A ";" a "); " An ";" an ");" In ";" in ");" And ";" and "); " The ";" the ");" With ";" with ")

Remember, this is all a single formula. It does the case conversion, but then substitutes the desired lowercase words (a, an, in, and, the, with). While this is relatively easy, the utility of the formula becomes limited as you increase the number of words for which substitutions should be done.

Perhaps a better approach is to use a user-defined function macro to do the case conversion for you. The following function checks for some common words that should not have initial caps, making sure they are lowercase.

Function MyProper(str As String) Dim vExclude Dim i As Integer vExclude = Array("a", "an", "in", "and", _ "the", "with", "is", "at") Application.Volatile str = StrConv(str, vbProperCase) For i = LBound(vExclude) To UBound(vExclude) str = Application.WorksheetFunction. _ Substitute(str, " " & _ StrConv(vExclude(i), vbProperCase) _ & " ", " " & vExclude(i) & " ") Next MyProper = str End Function

Words can be added to the array, and the code automatically senses the additions and checks for those added words. Notice, as well, that the code adds a space before and after each word in the array as it does its checking. This is so that you don’t have the code making changes to partial words (such as “and” being within “stand”) or to words at the beginning of a sentence. You can use the function within a worksheet in this way:

=MyProper(B7)

This usage returns the modified text without adjusting the original text in B7.

If you prefer, you can use a function that takes its list of words from a named range in the workbook. The following function uses a range of cells named MyList, with a single word per cell. It presumes that this list is in a worksheet named WordList.

Function ProperSpecial(cX As Range)

ExcelTips 2008 Page 68

Page 82: Excel tips 2008

Editing Tips

' rng = target Cell Dim c As Range Dim sTemp As String sTemp = Application.WorksheetFunction.Proper(cX.Value) For Each c In Worksheets("WordList").Range("MyList") sTemp = Application.WorksheetFunction.Substitute( _ sTemp, Application.WorksheetFunction.Proper( _ " " & c.Value & " "), (" " & c.Value & " ")) Next c ProperSpecial = sTemp End Function

(Thanks to Andrija Vrcan, Steve Aprahamian, and Adrian Fielden for contributing to this tip.)

SELECTING FORMULAS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to quickly select all the formulas in a worksheet. You may want to do this in preparation for applying formatting, or for some other purpose. To select all your formulas, follow these steps:

1. Press F5. Excel displays the Go To dialog box. 2. Click on Special. Excel displays the Go To Special dialog box.

ExcelTips 2008 Page 69

Page 83: Excel tips 2008

Editing Tips

The Go To Special dialog box.

3. Choose the Formulas radio button. 4. Using the four check boxes under the Formulas radio button, indicate the type of results

that should be produced by the formulas you want selected. 5. Click on OK.

DELETING EVERYTHING EXCEPT FORMULAS

Applies to Excel 97, 2000, 2002, 2003, and 2007

At the beginning of each year Richard makes a copy of the previous year's Excel workbook. To get ready for the new year’s data, he then needs to delete everything in the copy except for formulas. Richard wonders if there is a quick way to do this.

Actually, there is a very quick way to manually delete all the non-formula information in a worksheet. Follow these steps:

1. Press F5. Excel displays the Go To dialog box. 2. Click Special. Excel displays the Go To Special dialog box.

ExcelTips 2008 Page 70

Page 84: Excel tips 2008

Editing Tips

The Go To Special dialog box.

3. Make sure the Constants radio button is selected. 4. Click OK. All the cells containing constants (everything except formulas) are selected. 5. Press the DEL key.

If you have a lot of worksheets in a workbook and you want to delete all the constants from each of the worksheets, you might want to use a macro that automates the above steps for the entire workbook.

Sub DelAllConstants() Dim wks As Worksheet Dim rng As Range For Each wks In ThisWorkbook.Worksheets On Error Resume Next Set rng = wks.Cells.SpecialCells(xlCellTypeConstants, 23) On Error GoTo 0 If Not rng Is Nothing Then rng.ClearContents End If Set rng = Nothing Next Set wks = Nothing End Sub

(Thanks to Saurabh Gupta, Steve Aprahamian, Richard Raciborski, Tony James, Benazir Ibrahim, Bert Neuenschwander, Chris Purtill, Russell Hendel, and Jeff Pelletier for contributing to this tip.)

ExcelTips 2008 Page 71

Page 85: Excel tips 2008

Editing Tips

GETTING RID OF EVERYTHING EXCEPT NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Linda has a column that contains alpha and numeric characters. She needs to retain the numeric characters and delete the alpha ones. For example, a cell may contain 10003E111 and she wants to end up with 10003111.

There are a few ways you can approach this problem. Before proceeding with any solution, however, you should make sure that you aren’t trying to change something that isn’t really broken. For instance, you’ll want to make sure that the “E” that appears in the number isn’t part of the format of the number—in other words, a designation of exponentiation. If it is, then you don’t really want to remove the character because it will end up changing the nature of the underlying number.

If you determine that the characters aren’t part of the number’s format, then you can first try using formulas to remove the alpha characters. If the values you want to change are in column A, you could enter the following (very long) formula in column B:

=MID(A1,MATCH(TRUE,ISERROR(1*MID(A1,ROW(INDIRECT ("1:"&LEN(A1))),1)),0),-MATCH(TRUE,ISERROR(1*MID (A1,ABS(ROW(INDIRECT("1:"&LEN(A1)))-LEN(A1)-1),1)) ,0)+LEN(A1)+2-MATCH(TRUE,ISERROR(1*MID(A1,ROW (INDIRECT("1:"&LEN(A1))),1)),0))

Make sure you enter this as an array formula by pressing CTRL+SHIFT+ENTER. Then enter the following into column C:

=SUBSTITUTE(A1,B1,"")

The result is that column C contains the values from column A, without the alpha characters. You could use Paste Special to copy the information from column C to another column so that you end up with actual values instead of formula results.

This approach may work great for short-term use on a single workbook, but if you need to do this sort of data processing more often then you will want to create a user-defined function to do the processing. Here’s an example:

Function OnlyNums(sWord As String) Dim sChar As String Dim x As Integer Dim sTemp As String sTemp = "" For x = 1 To Len(sWord) sChar = Mid(sWord, x, 1)

ExcelTips 2008 Page 72

Page 86: Excel tips 2008

Editing Tips

If Asc(sChar) >= 48 And _ Asc(sChar) <= 57 Then sTemp = sTemp & sChar End If Next OnlyNums = Val(sTemp) End Function

You use this function by calling it from within a worksheet cell:

=OnlyNums(A1)

The function returns a numeric value. If you want to create an even shorter macro to do the processing, consider the following:

Function StripChar(aText As String) Dim I As Integer StripChar = "" For I = 1 To Len(aText) aChar = Mid(aText, I, 1) Select Case aChar Case "0" To "9" StripChar = StripChar & aChar End Select Next End Function

To use this function, use either of the following in your worksheet:

=STRIPCHAR(A1) =VALUE(STRIPCHAR(A1))

The first returns a text string consisting of the digits, the second returns the numeric version of that string.

(Thanks to Andrija Vrcan, Steve Aprahamian, Armando Montes, Dave Latham, Ron Solecki, Richard Raciborski, Marc Prosl, Russell Hendel, Michael Mitchelson, David Coop, Kishore Muktinutalapati, Dwaine Charbonneau, Scott Huish, Brian Bowling, Marilou Borries, Benazir Ibrahim, and Nick Stafford for contributing to this tip.)

ExcelTips 2008 Page 73

Page 87: Excel tips 2008

Editing Tips

RANGES ON MULTIPLE WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Most everyone knows that if you want to refer to a range of cells, you simply specify the beginning and ending point of the range and then separate those points by a colon. For instance, the following formula would return the sum of all cells in the range A1 through C4:

=SUM(A1:C4)

You may not know, however, how you can refer to the same cell or range of cells on a range of multiple worksheets in your workbook. For instance, you may want a cell to return the sum of each cell A1 on the first three worksheets in your workbook. If the worksheets are named Sheet1, Sheet2, and Sheet3, then the formula would appear as follows:

=SUM(Sheet1:Sheet3!A1)

Similarly, if you wanted the sum of all cells in the range A1 through C4 on each of the same worksheets, you would use the following formula:

=SUM(Sheet1:Sheet3!A1:C4)

At times this notation can be a bit difficult to remember. You can easily use the mouse to build such a range by following these steps:

1. Select the cell in which you want to enter your formula. 2. Enter the equal sign and the first part of the function, followed by the opening

parenthesis. In the examples given above, you would enter =SUM(. 3. Click on the sheet tab of the first sheet in the range. 4. Hold down the SHIFT key as you click on the sheet tab of the last sheet in the range. 5. Use the mouse to select all the cells in the range on the visible worksheet. 6. Press ENTER.

Your formula should now be complete, with the desired range in place.

ExcelTips 2008 Page 74

Page 88: Excel tips 2008

Editing Tips

EDITING THE SAME CELL IN MULTIPLE SHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

It is not unusual for all the worksheets in a particular workbook to be very much the same as each other. For instance, you might have a workbook that contains your annual budget data. Each worksheet in the workbook is devoted to a different month of the year. Each worksheet contains the same rows, the same columns, and the same formulas. The only thing that may be different is the heading on each worksheet—along with the raw data for each month, of course.

If your worksheets are very similar to each other, Excel provides a very easy way to modify the contents of a particular cell on each workbook, all at the same time. Simply follow these steps:

1. Select the first workbook in the series that you want to edit. 2. Hold down the SHIFT key as you click on the tab for the last worksheet in the series you

want to edit. A range of worksheets should now be selected. Excel also adds the word [Group] to the title bar to indicate you have a group of worksheets selected.

3. Make your changes to the worksheet shown on the screen. Your changes are automatically made on every other sheet in the range as well.

4. When done, select a single worksheet by clicking on its tab. (Click on the tab of a worksheet other than the first in the range.)

Step 3 may sound a bit confusing, but it isn’t really. If you have a range of worksheets selected, and you enter a formula in cell D4, then the same formula is entered in cell D4 on each of the selected worksheets. This is very powerful, and Excel won’t notify you if you are going to overwrite an existing formula on one of the worksheets. That is why step 4—deselecting the worksheets—is so important. If you forget to do so, you can easily mess up all your worksheets without intending to do so.

UNDERSTANDING AUTOCOMPLETE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel includes a handy time-saving feature called AutoComplete. This feature can save you time when you are entering lots of similar information in a column. You may already have noticed this feature before—when you start to type something in a cell, Excel tries to guess what you are typing and shows a “match” that you can accept simply by pressing ENTER.

The “matches” that Excel uses in its “guess” is nothing but the contents of the cells in the column, above where you are making your entry. For instance, if you have information in cells

ExcelTips 2008 Page 75

Page 89: Excel tips 2008

Editing Tips

A1 through A6 and you are entering a value in cell A7, Excel looks at what you are typing. If the first few characters uniquely match something in any of the six cells previously entered in the column, then Excel offers to AutoComplete A7 with the contents of the cell that matched.

Excel only tries to match your new entry with immediately adjacent cells above the one in which you are entering the information. It stops trying to match entries when a blank cell is reached. For instance, suppose you have information in cells A1 through A14 and A16 through A23. When you start typing an entry in cell A24, Excel only tries to match it with values in A16 through A23; the blank cell at A15 halts the comparisons.

In addition, Excel does not try to match with cells that contain only numbers, dates, or times. The cells must contain either text or a combination of text and numbers.

For some people, AutoComplete can be annoying rather than time-saving. If you want to turn off the AutoComplete feature, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Edit tab is displayed.

The Edit tab of the Options dialog box.

3. Clear the check box named Enable AutoComplete for Cell Values. 4. Click on OK.

ExcelTips 2008 Page 76

Page 90: Excel tips 2008

Editing Tips

If you are using Excel 2007, follow these steps instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Advanced. 3. Clear the check box named Enable AutoComplete for Cell Values. 4. Click on OK.

QUICKLY FILLING A COLUMN Applies to Excel 97, 2000, 2002, 2003, and 2007

When creating a many-row worksheet, it is often necessary to type a formula in one of the top rows and fill the column with that same formula. A convenient way to find the bottom of the column is to go there once (when you are first working with the worksheet) and place a character in each cell of the last row.

Now, when you place your formula at the top of the column, you can simply do this:

1. Select the cell that has your formula in it. (The one you just entered.) 2. Press CTRL+SHIFT+DOWN ARROW. This selects all the cells from the formula through the

“bottom marker” in the column. 3. Press CTRL+D. The selected cells are filled with the formula.

FAST AUTOFILL Applies to Excel 97, 2000, 2002, 2003, and 2007

The AutoFill feature in Excel is a great boon to certain types of editing. The basic use of the feature (clicking and dragging on the AutoFill handle) has been covered in other ExcelTips. There is another way you can use the AutoFill handle, however, that is a wonderful time-saving feature.

Suppose you have a column full of values in column A. For instance, you have values in the cells A3 through A417. Now, suppose you want to fill adjacent cells in column B with a sequential values, 1 through 415. Try this:

1. In cell B3, place the value 1. 2. In cell B4, place the value 2. 3. Select the range B3:B4.

ExcelTips 2008 Page 77

Page 91: Excel tips 2008

Editing Tips

4. Double-click on the AutoFill handle.

That’s it! No dragging at all, and you now have cells B5:B417 filled with sequential values. Cool, huh?

AUTOFILL WON'T WORK AS EXPECTED

Applies to Excel 97, 2000, 2002, 2003, and 2007

Deb is trying to AutoFill record numbers in a column of her worksheet. The first record 1, the second record 2, etc. The "Enable Fill Handle" box is checked in Excel options. However, when she uses the AutoFill handle, it just pastes the same number in every cell. Deb is wondering how she can fix this.

Based upon the described behavior, it sounds like you are trying to use AutoFill to create a series (1, 2, 3, etc.) when you aren’t giving AutoFill enough information to determine that is what you want to do. For example, enter the value 1 into cell A1 and the value 2 into cell A2. If you select cell A2 and use the AutoFill handle to drag downward, what happens is that Excel fills each of the cells with the value 2. Why? Because you only started by selecting a single cell.

On the other hand, if you select cells A1:A2 and then drag down, AutoFill will increment the value placed into each of the cells. Why? Because it can analyze what you started with to determine you want to fill the cells with a series of values.

If, for some reason, you don’t want to start with a selection of two cells, you could simply select one cell (A2) and hold down the Ctrl key as you drag the fill handle downward. AutoFill will override its normal determination (copy the selected value downward) by forcing a series of numbers into the filled cells.

(Thanks to Khushnood Viccaji, Nisha Kumari, Dave Theron, Steve Aprahamian, Vinay Pagaria, David Thwaites, Rose Wilson, Leo Mansi, Nora Abbott, Chandra Kumar, Jerrold Dolins, Eddie Kidd, Dave Pettit, Richard Raciborski, Syed Muneeb, Saskia Jacobsen, Russell Hendel, David Coop, Kishore Muktinutalapati, Tony Dalton, Tony Nunan, Rob Kattenburg-Schuler, Curtis Izen, Florence Wohl, Tina Woodsmall, Marilyn Lemmen, Gini Carrow, Janet Turner, Michael Cutler, Brian Bowling, Anne Sneller, Jef Van Rompaey, Paul McCulloch, and Marilou Borries for contributing to this tip.)

ExcelTips 2008 Page 78

Page 92: Excel tips 2008

Editing Tips

TURNING OFF AUTOFILL FOR A WORKBOOK

Applies to Excel 97, 2000, 2002, 2003, and 2007

The AutoFill feature of Excel can be a great timesaver when entering information. However, you may want to disable the feature for a particular workbook; perhaps you don’t want the feature to be used by anyone using your workbook. Doing so is easy if you create a macro that can recognize when you are working with that particular workbook.

To turn off the AutoFill feature for a particular workbook, follow these steps:

1. Open the workbook for which you want to disable the AutoFill feature. (It should be the only workbook you have open.)

2. Press ALT+F11 to open the VBA editor. 3. Using the Project window, select the ThisWorkbook object within the workbook you

opened in step 1. 4. Press F7. The Code window appears for the ThisWorkbook object. 5. Within the Code window, enter the following two macros:

Private Sub Workbook_Activate() Application.CellDragAndDrop = False End Sub

Private Sub Workbook_Deactivate() Application.CellDragAndDrop = True End Sub

6. Close the VBA editor. 7. Save your workbook.

The first macro is only run when the particular workbook is activated. In other words, when the workbook attains focus or is selected. When a different workbook attains focus, then the second macro is executed.

FINDING UNUSED NAMES Applies to Excel 97, 2000, 2002, 2003, and 2007

Richard has a workbook that he’s been using for a while, and it has quite a few names in it (named ranges, named formulas, etc.). He wonders if there is an easy way to find names that are not used at all, as he’d like to get rid of those names.

ExcelTips 2008 Page 79

Page 93: Excel tips 2008

Editing Tips

There is no built-in way to get rid of these unused names. You can, however, create a macro that will do the trick for you. This is most easily done by using the Find method to figure out which names have references that can be “found.” If the reference cannot be found, then the name is not in use.

Sub RidOfNames() Dim myName As Name Dim fdMsg As String On Error Resume Next fdMsg = "" For Each myName In Names If Cells.Find(What:=myName.Name, _ After:=ActiveCell, _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False).Activate = False Then fdMsg = fdMsg & myName.Name & vbCr ActiveWorkbook.Names(myName.Name).Delete End If Next myName If fdMsg = "" Then MsgBox "No redundant Names found in the workbook" Else MsgBox "Names Deleted:" & vbCr & fdMsg End If End Sub

The macro steps through all the elements of the Names collection and does a search for each name. If the name cannot be found, then the name is deleted. When the macro is completed, it displays a message box that lists the names that were removed from the workbook.

If you would rather not create your own macro, you can opt to use a free add-in by Jan Karel Pieterse. The add-in, called Name Manager, allows you to (guess what?) manage names better than you can do with native Excel. One of the functions it provides is the ability to get rid of names that are no longer needed. You can find the add-in here:

http://www.jkp-ads.com/OfficeMarketPlaceNM-EN.asp

(Thanks to Steve Aprahamian, Richard Raciborski, Gavin Tameris, Stephen Pike, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 80

Page 94: Excel tips 2008

Editing Tips

ADJUSTING FORMULAS WHEN PASTING

Applies to Excel 97, 2000, 2002, 2003, and 2007

The Paste Special feature of Excel never ceases to be full of surprises. One way you can use the feature results in pasting formulas into cells. That may sound weird, but perhaps an example will clarify the behavior.

1. Open a brand new workbook. 2. Put some values in a few contiguous cells, and some simple formulas in others. You can

put just a few; you won’t need many. (For this example, I’ll assume you put the content into the range of B3:D5.)

3. In a different cell, separated from the range you created in step 2, put a very simple formula, such as =1.1.

4. Select the cell you created in step 3 and press CTRL+C. This copies the cell contents to the Clipboard.

5. Select the range you set up in step 2 (B3:D5). 6. Choose Paste Special from the Edit menu. (In Excel 2007, display the Home tab of the

ribbon and click the down-arrow under the Paste tool at the left side of the ribbon. Select Paste Special from the resulting menu.) Excel displays the Paste Special dialog box.

The Paste Special dialog box.

7. Make sure the Formulas radio button is selected.

ExcelTips 2008 Page 81

Page 95: Excel tips 2008

Editing Tips

8. Make sure the Multiply radio button is selected. 9. Click OK. The cells are updated.

Take a look at how the target cells were updated. The formula from the source cell (step 4) was pasted into any formulas in the target range. If a cell in the target range contained a value instead of a formula, the value was converted to a formula and the source formula appended to it.

This can be a great way to use Paste Special when you want to maintain a trail of how you’ve modified the cells in a range.

UNWANTED DATA CHANGES Applies to Excel 97, 2000, 2002, 2003, and 2007

Have you ever been typing data into a worksheet, only to look back and find that Excel had made changes to words or letters you entered. For instance, you may have a client named Hempstead-Gorton Enterprises, and you enter their initials into a cell as HGE. When you press the space bar or move to another cell, Excel changes the initials to HE.

This is one of those cases where Excel is second-guessing you and is doing a poor job of it. What is happening is that AutoCorrect is kicking into play, and sees HGE as a common typing error. Thinking that you meant to type “he,” AutoCorrect makes the change for you.

If such unwanted changes are giving you the fits, you can follow these steps to correct the problem:

1. Choose AutoCorrect Options from the Tools menu. Excel displays the AutoCorrect tab of the AutoCorrect dialog box. (To display the dialog box in Excel 2007, click the Office button, Excel Options, Proofing and then AutoCorrect Options.)

ExcelTips 2008 Page 82

Page 96: Excel tips 2008

Editing Tips

The AutoCorrect tab of the AutoCorrect dialog box.

2. At the bottom of the dialog box you see a list of AutoCorrect entries. Scroll through the list and select the one that is giving you problems. For instance, if you don’t want “hge” corrected to “he,” then locate and select the entry that has “hge” on the left and “he” on the right.

3. Click Delete. 4. If there are other entries you need to remove, repeat steps 2 and 3 for each of them. 5. Click OK to dismiss the AutoCorrect dialog box.

Now you can type away without Excel incorrectly changing your acronym.

TURNING OFF AUTOMATIC CAPITALIZATION

Applies to Excel 97, 2000, 2002, 2003, and 2007

As you busily enter data into a worksheet, you may have noticed that periodically Excel will second-guess what you are doing and capitalize words for you. In general, Excel does this when it thinks you are starting a new sentence. (And, it assumes that the beginning of a cell is always the beginning of a sentence.)

ExcelTips 2008 Page 83

Page 97: Excel tips 2008

Editing Tips

If you find yourself undoing Excel's decisions on this issue quite a bit, you can turn off the feature completely by following these steps:

1. Choose AutoCorrect Options from the Tools menu. Excel displays the AutoCorrect dialog box. (To display the AutoCorrect dialog box in Excel 2007, click the Office button and then click Excel Options. Click Proofing, and then click AutoCorrect Options.)

2. Make sure the AutoCorrect tab is displayed.

The AutoCorrect tab of the AutoCorrect dialog box.

3. Clear the Capitalize First Letter of Sentences check box. 4. Click on OK.

ENSURING UNIQUE VALUES IN A COLUMN

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you are entering information in a worksheet, you may want to ensure that the data being entered is actually unique for a particular column. For instance, if you are entering a series of

ExcelTips 2008 Page 84

Page 98: Excel tips 2008

Editing Tips

invoice numbers in column D of a worksheet, you may want to ensure that you don’t enter the same invoice number twice.

There are a couple of ways that you can approach such a problem. If you are always entering your new information at the bottom of a column, you can use Excel’s data validation feature to make sure that whatever you are entering in the current cell does not match anything higher up in the column. Simply follow these steps:

1. Select column D. 2. Display the Data Validation dialog box. (In versions of Excel prior to Excel 2007,

choose Data | Validation. In Excel 2007 click the Data tab of the ribbon and then click Data Validation in the Data Tools group.)

3. Using the Allow drop-down list, choose the Custom option. 4. In the Formula box, enter the following formula:

=MATCH(D1,$D:$D,0)=ROW(D1)

5. Click on OK.

If you may be entering data anyplace within column D, and you want to know if you are entering a value that is elsewhere in the column (above or below the current cell), then you can follow the above steps, but use this formula in step 4:

=COUNTIF($D:$D,D1)<2

PUTTING ADDRESSES ON STATE-SPECIFIC WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Linda has a worksheet containing 250 addresses from all over the country. She wants to separate the addresses, by state, to different worksheets so that each worksheet contains addresses only from a specific state.

There is no way to do this with any of the built-in Excel functions or wizards. This is probably a reflection of the fact that most people leave the data on a single worksheet, and then use various Excel tools (such as filtering) to display only a subset of the overall data.

If you want to copy state-specific information to separate sheets, however, you can do so manually by using AutoFilter. This works particularly well if you have only a few states in your sources data. Just apply an AutoFilter and display only those rows that are in the state you want to copy. Select the visible rows, copy them, and paste them to a new worksheet. Repeat the process with each of the other states in your original data set.

ExcelTips 2008 Page 85

Page 99: Excel tips 2008

Editing Tips

If you have data for quite a few sheets, you can copy it by automating this process. The following macro will use the AutoFilter capabilities of Excel to copy the information to a new worksheet. It does this for each unique value in the state column, which is specified by the iCol variable. (In this example, iCol is set to 5, which means that the states are in column E.)

Sub NewSheetEachAutofilter() Dim wOri As Worksheet Dim wks As Worksheet Dim wPT As Worksheet Dim bAutoFilter As Boolean Dim PT As PivotTable Dim rPT As Range Dim rCell As Range Dim iCol As Integer Dim sHeader As String On Error GoTo Errhandler Application.ScreenUpdating = False iCol = 5 'Filter all on Col E Set wOri = ActiveSheet With wOri 'Save Autofilter status bAutoFilter = .AutoFilterMode If Not bAutoFilter Then 'turn on autofilter .Range("a1").AutoFilter End If If .FilterMode Then .ShowAllData 'use a PivotTable on a temp 'sheet to get a unique list Set PT = .PivotTableWizard _ (SourceType:=xlDatabase, _ SourceData:=.Range("a1").CurrentRegion, _ TableDestination:="", _ TableName:="PivotTable1") sHeader = .Cells(1, iCol) With PT .AddFields RowFields:=sHeader .PivotFields(sHeader).Orientation = xlDataField .ColumnGrand = False End With Set wPT = ActiveSheet With wPT Set rPT = .Range(.Range("A3"), _ .Cells(.Cells.Rows.Count, 1).End(xlUp)) End With 'loop through unique list For Each rCell In rPT .Range("a1").AutoFilter Field:=iCol, _ Criteria1:=rCell.Value 'create new sheet and name it with the state

ExcelTips 2008 Page 86

Page 100: Excel tips 2008

Editing Tips

Set wks = Worksheets.Add wks.Name = rCell.Value .AutoFilter.Range.Copy wks.Range("A1") Next .ShowAllData .Select End With Application.DisplayAlerts = False wPT.Delete ExitHandler: Application.DisplayAlerts = True Application.ScreenUpdating = True 'remove filter if no previous one If Not bAutoFilter Then wOri.AutoFilterMode = False End If Set rCell = Nothing Set rPT = Nothing Set PT = Nothing Set wOri = Nothing Set wks = Nothing Set wPT = Nothing Exit Sub Errhandler: MsgBox Err.Number & ":" & Err.Description Resume ExitHandler End Sub

The code may look complex because of its length, but it isn’t particularly difficult. It makes sure that the AutoFilter is turned on, and then it creates a PivotTable based on your original data. This PivotTable is used to gather the list of states from the data. Each state is then used on the original data as a filtering criteria. The filtered information is then copied to a new worksheet that is named using the state.

The macro does not modify the original data. If you prefer to have the original data deleted after it is moved to a worksheet, then all you need to do is add a single line of code. Add this line right after the line that deletes the PivotTable (wPT.Delete):

wOri.Delete

(Thanks to Steve Aprahamian, Andrija Vrcan, Richard Raciborski, Don Zugel, Robert Tillotson, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 87

Page 101: Excel tips 2008

Editing Tips

DELETING OLD DATA FROM A WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Gene is looking for a way to quickly delete data from a worksheet based on the date in a particular column. If the date is older than today (the date is passed) then the row should be deleted.

This can be rather easily done with a macro. All you need to do have the macro step through the data and compare the date in each row to today’s date. If the date is less than today, then the Delete method is used on the EntireRow object.

Sub DeleteRows1() Dim x As Long Dim iCol As Integer iCol = 7 'Filter all on Col G For x = Cells(Cells.Rows.Count, iCol).End(xlUp).Row To 2 Step -1 If Cells(x, iCol).Value < Date Then Cells(x, iCol).EntireRow.Delete End If Next End Sub

In this example, the macro checks column G (in the iCol variable) for the date. If your date is in a different column, then you should make the change to the variable. Depending on the number of rows of data in your worksheet, the macro may also take quite a while to run. If you notice a lag in performance, then you may want to use a different approach. The following example uses the AutoFilter capabilities of Excel to first filter the data to show only the old data, and then deletes those rows.

Sub DeleteRows2() Dim Dates As Range Dim nRows As Double Dim currDate As Variant 'Format dates as text Range("Dates").NumberFormat = "@" 'Today’s date in number format currDate = CDbl(Date) Range("Dates").AutoFilter Field:=1, _ Criteria1:="<" & currDate nRows = Range("Dates").Rows.Count Rows("2:" & nRows).Select Selection.Delete Shift:=xlUp Range("Dates").AutoFilter Range("Dates").NumberFormat = "m/d/yyyy"

ExcelTips 2008 Page 88

Page 102: Excel tips 2008

Editing Tips

Range("C2").Select End Sub

This macro presumes that you have taken the step of assigning a name to your data range. Select all the cells in your data table—including any heading row—and give it the name “Dates.” When you run the macro, it uses this range as the target for the AutoFilter.

(Thanks to Steve Aprahamian, Andrija Vrcan, Richard Raciborski, Mike Hughes, Dennis Swearingen, and Russell Hendel for contributing to this tip.)

WORKING IN FEET AND INCHES Applies to Excel 97, 2000, 2002, 2003, and 2007

If you work in one of the construction trades, you may wonder if there is a way to have Excel work in feet and inches. The answer, of course, is yes and no. (How’s that for specific?)

Let’s look at the “no” answer first. If you are looking for a way to make Excel do things like math using feet and inches, there is no native ability to do that. In other words, you can’t tell Excel to consider a column as “feet and inches” and then have it automatically add a set of cells containing lineal feet. A quick search of the Internet reveals that there are a number of Excel add-ins that you can find—some for free—that will do real math for feet and inches. These, of course, would require learning exactly how to use them to achieve what you want. The following site was among those suggested by different ExcelTips subscribers:

http://lacher.com/examples/lacher18.htm

Now for the “yes” portion of the answer. You can, of course, use separate columns for feet and inches. In this way it is relatively easy to add the values in the columns—one would simply be the sum of feet, and the other the sum of inches. Since the sum of the inches would most likely exceed 12, you could, in a different cell, adjust the finished feet and inches as necessary.

Another approach is to simply work in inches, which is the lowest common denominator. For instance, if you had a length of 5 feet 6 inches, you would put the value 66 in a cell. You could then do any number of math functions on these values. In another cell you could use a formula, such as the following, to display an inches-only value as feet and inches:

=INT(A1/12) & " ft. " & MOD(A1,12) & " in."

ExcelTips 2008 Page 89

Page 103: Excel tips 2008

Editing Tips

SHORTENING ZIP CODES Applies to Excel 97, 2000, 2002, 2003, and 2007

In the United States, ZIP Codes come in two formats: five-digit and nine-digit. (Actually, the five-digit ZIP Code is a subset of the nine-digit ZIP Code.) If you are an Excel worksheet that contains address information, you may want to convert nine-digit ZIP Codes to their five-digit equivalent.

This is a rather easy task to accomplish, since all you need to do is strip everything after the fifth digit in the ZIP Code. Follow these steps:

1. Insert a new column, just to the right of the existing ZIP Code column. 2. Assuming the ZIP Codes are in column G and you added a new column H, you can

enter the following in cell H3:

=Left(G3, 5)

3. Copy this formula into all the appropriate cells of column H. 4. Select the entire column H. 5. Press CTRL+C. Excel copies the entire column to the Clipboard. 6. Display the Paste Special dialog box by choosing Paste Special from the Edit menu. (In

Excel 2007 display the Home tab of the ribbon, click the down-arrow under the Paste tool, and then click Paste Special.)

The Paste Special dialog box.

ExcelTips 2008 Page 90

Page 104: Excel tips 2008

Editing Tips

7. Make sure the Values radio button is selected. 8. Click on OK. Column H has now been transformed from formulas into the formula

results. 9. Delete column G.

If you have an empty column to the right of your ZIP Codes, you can also use Excel's Text to Columns feature:

1. Select all the cells that contain your ZIP Codes. 2. From the Data menu, choose Text to Columns. (In Excel 2007 display the Data tab of

the ribbon and click the Text to Columns tool in the Data group.) Excel displays the Convert Text to Columns Wizard.

The Convert Text to Columns Wizard

3. Make sure the Delimited option is selected, then click on Next. 4. Select the Other check box, place a single dash in the box just to the right of Other, then

click on Next. 5. In the Column Data Format area, select Text. (You want your ZIP Codes to be

formatted as text so that you don't lose any leading zeros.) 6. Click on Finish.

ExcelTips 2008 Page 91

Page 105: Excel tips 2008

Editing Tips

At this point you have the first five digits of the ZIP Code in the original column, and the last four digits (if any) in the previously empty column to the right. You can delete the column containing the four digits, if desired.

If you need to truncate ZIP Codes quite often, you may be more interested in a macro-based approach. The following macro will do the trick:

Sub ZIPShorter() For Each cell In Selection cell.Value = Left(cell.Value, 5) Next End Sub

All you need to do is select the cells containing the ZIP Codes, and then run the macro.

FORMATTING CANADIAN POSTAL CODES

Applies to Excel 97, 2000, 2002, 2003, and 2007

In Canada, postal codes consist of six characters with a space in the middle: a letter, a number, a letter, a space, a number, a letter, and a final number. Thus, A1B 2C3 is a properly formatted postal code. If you are retrieving postal codes from an external database, they might not have the required space in the middle. Excel makes it easy to add such a space.

Let’s assume that the improperly formatted postal codes are in column C. In column D you could use a formula such as the following:

=LEFT(B12,3) & " " & RIGHT(B12,3)

This formula uses string-manipulation functions to place a space in between the first and last three characters. Thus, if B12 contained A1B2C3, then the cell with this formula would display A1B 2C3.

DIVIDING VALUES Applies to Excel 97, 2000, 2002, 2003, and 2007

It is not uncommon to need to adjust values imported from a different program, once they are in Excel. For instance, you may need to divide all the imported values by 100 or by 1000, or by some other number.

ExcelTips 2008 Page 92

Page 106: Excel tips 2008

Editing Tips

There is an easy way to perform such an operation in Excel. Simply follow these steps:

1. Select an empty cell, somewhere outside the range used by your imported data. 2. Enter the value 100 or 1000 in the empty cell. (Use a value equal to what you want to

divide by.) 3. With the cell selected, press CTRL+C to copy its contents to the Clipboard. 4. Select the imported data range. You should not select any headers or non-numeric

information. 5. Choose the Paste Special option from the Edit menu. Excel displays the Paste Special

dialog box. (To display the dialog box in Excel 2007, display the Home tab of the ribbon, click the down-arrow under the Paste tool, and then choose Paste Special.)

The Paste Special dialog box.

6. In the Operation area of the dialog box, make sure you select the Divide option. 7. Click on OK. 8. Select the cell where you entered the value in step 2. 9. Press the DELETE key.

That's it! All the values in your data range have been divided by the appropriate amount.

ExcelTips 2008 Page 93

Page 107: Excel tips 2008

Editing Tips

AUTOMATICALLY PROTECTING AFTER INPUT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel offers protection for your worksheets, meaning that you can protect the contents of cells so they cannot be changed. Exactly how you use this protection has been discussed in other issues of ExcelTips. What if you want to allow cells to be edited, but you want them to become protected right after someone enters information in the cell? For instance, you have cells in which a user could enter information, but once entered, you don’t want them to have the ability to change the information they entered.

There is no inherent ability in Excel to protect your input, but you can create the ability through the use of a macro. The following macro is an example of how you can do this:

Private Sub Worksheet_Change(ByVal Target As Range) Dim MyRange As Range Set MyRange = Intersect(Range("A1:D100"), Target) If Not MyRange Is Nothing Then Sheets("Sheet1").Unprotect password:="hello" MyRange.Locked = True Sheets("Sheet1").Protect password:="hello" End If End Sub

This macro assumes that the worksheet has already been protected, and that all the cells where you want input to be possible are unlocked. What it does is check to see if the input was done in the proper range of cells, in this case somewhere in the range of A1:D100. If it was, then the worksheet is unprotected, the cell in which information was just entered is locked, and the worksheet is again protected.

If you are using this approach in your own workbook, you will need to modify the potential input range, and you will want to change the password used to unprotected and protect the worksheet.

SCROLL WHEEL DOESN'T WORK WHEN EDITING IN EXCEL 2007

Applies to Excel 2007

Sarah noted that when she is typing a formula or editing an existing one in Excel 2007, the scrolling wheel on her mouse doesn't allow her to scroll through the worksheet in order to select cells. Instead, she has to use the scroll bar on the right-hand side of the worksheet. This is really

ExcelTips 2008 Page 94

Page 108: Excel tips 2008

Editing Tips

annoying, as Sarah finds it easier to use the mouse's scroll wheel. She wonders if there is some setting that she is not aware of that might correct this.

There is only a single setting which controls the use of the mouse wheel. Follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box, click Advanced.

The Advanced options of the Excel Options dialog box.

3. In the Editing Options section, clear the check box entitled Zoom on Roll with Intellimouse.

4. Click OK.

(Thanks to Bernard Liengme for contributing to this tip.)

ExcelTips 2008 Page 95

Page 109: Excel tips 2008

Editing Tips

TYPING CHECK MARKS INTO EXCEL

Applies to Excel 97, 2000, 2002, 2003, and 2007

It is not unusual to use an Excel worksheet to create different types of checklists and forms that are used by other people. When you are developing your checklist, you may want to actually put a check mark into a cell. There are several ways you can go about doing this. Both methods involve changing the font applied to a cell and then typing the character you want in the cell.

For instance, try these steps:

1. Select the cell that you want to contain the check mark. 2. Using the Font drop-down list, select Wingdings. The cell is now formatted to use the

Wingdings font. 3. Start the Character Map accessory included with Windows. (Click on Start, then

Programs, then Accessories to find the program.)

The Character Map accessory.

4. In the Character Map, select the Wingdings font. 5. Scroll though the available characters until you find the check mark you like.

ExcelTips 2008 Page 96

Page 110: Excel tips 2008

Editing Tips

6. Copy the character to the Clipboard. (The controls in the Character Map accessory allow you to do this, although the controls differ from one version of Windows to another.)

7. Close the Character Map accessory. 8. In Excel, press CTRL+V to paste the character into the cell.

This is quite a few steps to put in a simple check mark. There is a simpler way, however, if you simply remember that you need to pick a font that contains check marks, and then put in the character to produce that check mark.

When it comes to fonts containing check marks, there are quite a few. The appearance of the check mark will depend on the font you use. The following information shows what you would type (on the keyboard) in various fonts to achieve a check mark:

Character to Type Font to Use a Marlett a Webdings b Marlett C Erilogo P Wingdings 2 Alt+129 Wingdings Alt+0214 Symbol Alt+0252 Wingdings

For those instances where an ALT combination is mentioned, you simply need to hold down the ALT key as you type the three or four numbers on the keypad.

There are undoubtedly numberless other character/font combinations that will result in a check mark in a cell. If you want to do your own exploring, you can use the Character Map accessory to look around through different fonts to find out what is available. (You can also find different fonts containing check marks at some Web sites, such as www.dingbatpages.com.)

RETAINING FORMATTING AFTER A PASTE MULTIPLY

Applies to Excel 97, 2000, 2002, 2003, and 2007

One of the really cool features of Excel is the many ways you can manipulate data using the Paste Special command. This command allows you to do all sorts of things to you data, as you paste it into a worksheet. One such manipulation you can perform is to multiply data as you paste. For instance, you can multiply all the values being pasted by -1, thereby converting them into negative numbers. To do so, follow these steps:

ExcelTips 2008 Page 97

Page 111: Excel tips 2008

Editing Tips

1. Place the value -1 in an unused cell of your worksheet. 2. Select the value and press CTRL+C. Excel copies the value (-1) to the Clipboard. 3. Select the range of cells that you want to multiply by -1. 4. Display the Paste Special dialog box. (In versions of Excel prior to Excel 2007 you do

this by choosing Paste Special from the Edit menu. In Excel 2007 you display the Home tab of the ribbon, click the down-arrow under the Paste tool, and then click Paste Special.)

The Paste Special dialog box.

5. Click on the Multiply radio button. 6. Click on OK.

At this point Excel multiplies the values in the selected cells by the value in the Clipboard. Unfortunately, if the cells in the selected range had special formatting, the formatting is also now gone, and the format of the cells is set to be the same as the cell you selected in step 2.

To make sure that the formatting of the target cells is not changed while doing the Paste Special, there is one other option you need to select in the Paste Special dialog box—Values. In other words, you would still select Multiply (as in step 5), but you would also select Values before clicking on OK.

With the Values radio button selected, Excel only operates on the values in the cells, and leaves the formatting of the target range unchanged.

ExcelTips 2008 Page 98

Page 112: Excel tips 2008

Editing Tips

INSERTING A RADICAL SYMBOL Applies to Excel 97, 2000, 2002, 2003, and 2007

A radical is a mathematical symbol used to denote “roots” of a value. The most common radical is used to denote a square root. The typical method of inserting a radical is to hold down the ALT key as you type 251 on the numeric keypad. Release the ALT key, and the symbol appears.

Of course, the appearance of the radical (or even whether it appears at all) depends on the font used in the cell. The ALT+251 method works for most normal fonts, but some fonts may not include the radical symbol (in which case it won’t appear) or may have the symbol mapped to a different position in the font. In that case, the best way to insert the symbol is to use the Symbol dialog box to search through the desired font and find the radical.

You can also use the Windows Character Map program to find the radical, copy it to the Clipboard, and then paste it into Excel. (You can locate the Character Map program by choosing Start | All Programs | Accessories | System Tools | Character Map. This works in Windows XP, but may not work in other versions of Windows.)

All of the methods described so far are great if the only thing you want in the cell is the radical. You can, however, format a cell so that the radical symbol is displayed just to the left of whatever value is in the cell. Perhaps the easiest way to apply this format to a cell is to use a macro, as shown here:

Sub Radical() ActiveCell.NumberFormat = ChrW(8730) & "General" End Sub

Select the cell you want to format, then run the macro. (You can see how this custom format is handled by Excel if you run the macro and then display the Format Cells dialog box.)

EASILY CHANGING LINKS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to link information from one worksheet to another, or even from one workbook to another. Many people do this very thing when they use one worksheet as a "summary" overview of information contained in other worksheets.

If you organize your data in this manner, you may be wondering about the best way to change links within your worksheet. When you link information, Excel keeps track within the link of the source of the link. For instance, the following link refers to cell C7 in the MayData worksheet of the 2008Budget.xls workbook:

ExcelTips 2008 Page 99

Page 113: Excel tips 2008

Editing Tips

=+[2008Budget.xls]MayData!$C$7

If you have quite a few of these links in a worksheet, it can be bothersome to update each link when you change the source workbook or worksheet used by the links. You could, of course, use Excel's find and replace feature to make the desired changes, but there is an easier way: Use the INDIRECT and ADDRESS functions.

For instance, let's assume that you have cells containing a workbook name (J1), a worksheet name (J2), a numeric row number (J3), and a column number (J4). In this instance, you could use the following formula to specify a link:

=INDIRECT(ADDRESS(J3,J4,1,TRUE,"["&J1&"]"&J2))

The result is that Excel will calculate an indirect address based on the contents of the cells. If you want to change the place from which Excel pulls information, all you need to do is change the contents of cells J1 through J4 so they represent the desired source.

You should note that you will need to have the source workbooks open in order to use this approach. If they are not open, Excel won't be able to update the information as desired.

UPDATING LINKS IN COPIED FILES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Let’s say you have two workbooks that you use for tracking sales in the current month, 2008JuneA.xls and 2008JuneB.xls, and that 2008JuneA.xls contains links to data in 2008JuneB.xls. When it comes time to copy the workbooks for the new month, you may be wondering about the best way to update all the links in the first workbook so they point to the second workbook for the new month.

To prepare workbooks for the new month, most people will open a Windows folder and copy the workbook files within Windows, not even in Excel. This, however, is the way to guarantee that you do the most work in updating the files. A simpler way is to bypass Windows and do the saving in Excel. Follow these general steps:

1. Open both 2008JuneA.xls and 2008JuneB.xls in Excel. 2. Use Save As to save the 2008JuneB.xls file under the name 2008JulyB.xls. 3. Use Save As to save the 2008JuneA.xls file under the name 2008JulyA.xls.

As part of saving out 2008JulyB.xls (step 2), Excel automatically updates all the links in 2008JuneA.xls so that they point to the new file name. When you then save 2008JulyA.xls (step

ExcelTips 2008 Page 100

Page 114: Excel tips 2008

Editing Tips

3), you complete the cycle and end up with the new workbooks for the new month, with the past month’s files still secure on disk.

If saving the files under new names in Excel is not possible for some reason (perhaps someone else already made a copy of the workbook for the new month and made changes in the file) then you will need to resort to doing some manual editing of the links. Fortunately you can use the Find and Replace features of Excel to help in this task:

1. Open the 2008JulyA.xls file. 2. Press CTRL+H to display the Replace tab of the Find and Replace dialog box.

The Find and Replace dialog box.

3. In the Find What box, enter the root portion of the old worksheet name (2008JuneB). 4. In the Replace With box, enter the root portion of the new worksheet name

(2008JulyB). 5. Click Replace All.

Excel goes through the entire worksheet—including the links—and makes changes to the appropriate text.

Another approach is to deal with your monthly files as a whole. In other words, don’t have the filenames reflect the month, but put all the workbooks for the month in a single folder that is named after the month. Under this scenario, you could have a February folder, and then make a copy of the whole folder and name it March. You would then have duplicate copies of the workbooks in separate folders. You could work with them independently, as long as you don’t try to open the same workbook from both months at the same time. (Excel won’t allow you to open multiple workbooks with the same name.)

If you want to make your linking strategy more flexible, you can always use the INDIRECT function. For instance, suppose that your link is something like this:

=[2008JuneB.xls]Sheet1!B3

ExcelTips 2008 Page 101

Page 115: Excel tips 2008

Editing Tips

You could put the name of the source file (2008JuneB.xls) in a cell in the current worksheet (D5, for example) and replace the above expression with one like this:

=INDIRECT("[" & D5 & "]Sheet1!B3")

Changing the contents of cell D5 to a different filename will make that file the new source of data. There are a couple of “gottchas,” however. First of all, you need to manually open the file that is the target of the link; Excel won’t do it for you as it would with a regular link. Also, workbook filenames that contain spaces will trip up the INDIRECT formula. If you think you might have spaces in your filenames, you should change the formula to this:

=INDIRECT("['" & D5 & "']Sheet1!B3")

COPYING A HYPERLINK TO LOTS OF WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Steven has a worksheet that has a hyperlink in cell B1. He wants to copy this hyperlink to cell D50 on each of the 75 worksheets in this particular workbook. He wonders if there is an easy way to do that.

Actually, there is a very easy way to do it, using editing techniques already familiar to most Excel users. All you need to do is follow these general steps:

1. Select cell B1. (You’ll need to do this by clicking one of the cells next to B1 and then using the arrow keys to move into cell B1. If you simply click the cell, you run the risk of activating the hyperlink, which you don’t want to do.)

2. Press CTRL+C to copy the cell contents (the hyperlink) to the Clipboard. 3. Right-click one of the worksheet tabs at the bottom of the screen, then choose Select All

Sheets. 4. Select cell D50. 5. Press CTRL+V.

That’s it. You end up with the hyperlink pasted into cell D50 on each and every worksheet. To go back to working on a single worksheet, click a single worksheet tab.

(Thanks to Benazir Ibrihim, Charlie O’Neill, Hemant Trivedi, Andrija Vrcan, Steve Aprahamian, Tore Softing, Hans Juergen Plett, Stijn Berben, Florence Wohl, Mary Padilla, and Curtis Izen for contributing to this tip.)

ExcelTips 2008 Page 102

Page 116: Excel tips 2008

Editing Tips

REMOVING SPACES Applies to Excel 97, 2000, 2002, 2003, and 2007

Do you have a lot of data that contains spaces, and you need to remove those spaces? Perhaps you imported it from another program, or the spaces were entered by mistake. For example, you may have a large number of policy numbers in a worksheet, and there are spaces in the policy numbers. If you want to remove those spaces, there are two approaches you can use.

The first approach is to use the SUBSTITUTE function. Let’s say that a policy number is in cell A5. In cell B5 you could use this formula:

=SUBSTITUTE(A5," ","")

The result is that cell B5 contains the policy number with all the spaces removed.

The second approach works well if you have a lot of cells containing spaces, and you want to remove them in one step. Create the following macro:

Sub NoSpaces() Dim c As Range For Each c In Selection.Cells c = Replace(c, " ", "") Next End Sub

Select the cells you want to modify, and then run the macro. It examines each cell in the selected range, removing any spaces in that range. The result is then placed back in the same cell.

CONTINGENT VALIDATION LISTS Applies to Excel 97, 2000, 2002, 2003, and 2007

The data validation capabilities in Excel are quite handy, particularly if your worksheets will be used by others. When developing a worksheet, you might wonder if there is a way to make the choices in one cell contingent on what is selected in a different cell. For instance, you may set up the worksheet so that cell A1 uses data validation to select a product from a list of products. You would then like the validation rule in cell B1 to present different validation lists based on the product select in A1.

The easiest way to accomplish this task is in this manner:

ExcelTips 2008 Page 103

Page 117: Excel tips 2008

Editing Tips

1. Beginning at cell F1, set up a data table. This table will contain your product “matrix.” In the first cell of each column, indicate a category name, such as Computers, Televisions, and Recorders.

2. Under each heading in the product matrix, list the various products in the category. 3. Select the headings from the data table, such as F1:H1. 4. Choose Insert | Name | Define. Excel displays the Define Name dialog box. (To display

the equivalent dialog box in Excel 2007, display the Formulas tab of the ribbon and then click on Define Name in the Defined Names group. Excel displays the New Name dialog box.)

The Define Name dialog box.

5. In the Name box, enter a descriptive name, such as Choices. 6. Click OK to add the name and close the dialog box. 7. Select the actual products in column F. Don’t select the heading (F1); just select the

products under the heading. 8. Again display the Define Name dialog box, as described in step 4. 9. In the Name box, enter the same name you used as a heading in that column, such as

Computers. 10. Click OK to add the name and close the dialog box. 11. Repeat steps 7 through 10 for the other product columns. In each case, make sure you

define the name as the same name used in the column header. 12. Select cell A1 and choose Validation from the Data menu. Excel displays the Data

Validation dialog box. (To display the dialog box in Excel 2007, display the Data tab of the ribbon and then, in the Data Tools group, click the Data Validation tool.)

13. Using the Allow drop-down list, choose List. 14. In the Source box, enter an equal sign followed by the name you defined in step 5 (such

as =Choices).

ExcelTips 2008 Page 104

Page 118: Excel tips 2008

Editing Tips

The Data Validation dialog box.

15. Click OK. 16. Select cell B1 and again display the Data Validation dialog box as described in step 12. 17. Using the Allow drop-down list, choose List. 18. In the Source box, enter the following: =INDIRECT(A1). 19. Click OK. Excel displays a dialog box asking if you really want to use the rule. (This is

because the referenced cell, A1, currently resolves to an error condition.) 20. Click Yes.

That’s it. Now, whatever is chosen in cell A1 dictates which list is presented in cell B1.

REFERENCING THE LAST CELL IN A COLUMN

Applies to Excel 97, 2000, 2002, 2003, and 2007

Patty asked about a common scenario, in which column B contains quite a bit of data, and information can be added to the cells in the column at any time. In a formula in cell C4, Patty wants to see the value at the bottom of those cells in column B that contain values. Thus, if cells B1:B27 contain data, then in cell C4 Patty wants to see the value that is in cell B27. If three more pieces of data are added to column B, then the value in C4 should contain the value in B30.

ExcelTips 2008 Page 105

Page 119: Excel tips 2008

Editing Tips

The solution to this problem depends on whether you can count on the data in column B containing blank cells or not. If the data is contiguous—it doesn’t contain any blank cells—then you can use the following formula in C4:

=INDIRECT("B"&COUNTA(B:B))

This constructs an address based on the last cell in the column, and then uses the INDIRECT function to return the value at that address.

If it is possible for there to be blanks in column B, then the following formula will work:

=INDIRECT("B"&MAX(ROW(1:65535)*(B1:B65535<>"")))

Again, the INDIRECT function is used to fetch the actual value, but the address used by INDIRECT is put together differently.

A different approach is to use the VLOOKUP function to return the value. If column B consists of numeric values, then the following formula in C4 will work just fine:

=VLOOKUP(9.99999999999999E+307,B:B,1)

If column B contains text, then the numeric lookup won’t work, but the following will:

=VLOOKUP(REPT("z",50),B:B,1)

COUNTING WORDS Applies to Excel 97, 2000, 2002, 2003, and 2007

Words are normally associated with a word processor, such as Microsoft Word. However, many people also work with words in their spreadsheet program. (I had a coworker once who used Excel to write memos all the time.) There may be times when you want to count the number of words in a spreadsheet that you receive from someone. There are native abilities to perform such a task in Word, but not in Excel.

One solution, of course, is to load your spreadsheet into Word, perform the word count there, and then close the file. This is not nearly as flexible, however, as creating a macro to count words within Excel itself. The following macro, CountWords, will count the number of words in any range you select in a worksheet:

Sub CountWords() Dim MyRange As Range Dim CellCount As Long Dim TotalWords As Long

ExcelTips 2008 Page 106

Page 120: Excel tips 2008

Editing Tips

Dim NumWords As Integer Dim Raw As String Set MyRange = ActiveSheet.Range(ActiveWindow.Selection.Address) TotalWords = 0 For CellCount = 1 To MyRange.Cells.Count If Not MyRange.Cells(CellCount).HasFormula Then Raw = MyRange.Cells(CellCount).Value Raw = Trim(Raw) If Len(Raw) > 0 Then NumWords = 1 Else NumWords = 0 End If While InStr(Raw, " ") > 0 Raw = Mid(Raw, InStr(Raw, " ")) Raw = Trim(Raw) NumWords = NumWords + 1 Wend TotalWords = TotalWords + NumWords End If Next CellCount MsgBox "There are " & TotalWords & " words in the selection." End Sub

Notice that the macro steps through each cell in the range you select. It then ignores any cell that contains a formula. In all other cells it essentially counts the number of spaces in the cell. (One or more spaces are assumed to separate words.) The word count is then displayed in a message box for your edification.

The macro is pretty quick on relatively small ranges. If you pick a large range (such as the entire worksheet), then the macro can take a great deal of time to finish its work. The point of this is to make sure that you only select the actual range you want to analyze before invoking the macro.

GETTING HELP WHEN ENTERING FUNCTIONS

Applies to Excel 97, 2000, 2002, 2003, and 2007

One of the tools that Excel provides for adding functions to a formula is Insert | Function, which starts a wizard-like interface that leads you through constructing the function properly. If you are like most frequent users of Excel, this level of help is a little much; all you need is a memory-jog as to what parameters should be used with the function.

One obscure shortcut provided in Excel actually provides just the amount of help you want. For example, let’s say you know you want to use the SUBSTITUTE function, but you cannot

ExcelTips 2008 Page 107

Page 121: Excel tips 2008

Editing Tips

remember all the parameters that are used with it. Type an equal sign, followed by SUBSTITUTE and a left parenthesis, like this:

=SUBSTITUTE(

Now, press SHIFT+CTRL+A. Excel magically adds all the parameters for the formula, like this:

=SUBSTITUTE(text,old_text,new_text,instance_num)

What’s more, the first parameter (text) is highlighted, and you can simply start typing what you want used for that parameter. Replace or delete the other parameters, as desired, and you have your correctly constructed function ready to go.

AUTOMATICALLY BREAKING TEXT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Have you ever had a string in a cell that you wanted to wrap after every word? The normal way of doing this would be to press F2 and edit the string. You would delete each space and then press ALT+ENTER to add a new line character.

There’s an easier, less manual method of doing this, however—just use the SUBSTITUTE function. Suppose cell A1 contained “This is my text.” Enter the following into another cell:

=SUBSTITUTE(A1," ",CHAR(10))

What this results in is the text of cell A1 with small boxes where the spaces were. Turn on wrapping for the cell (done in the Format Cells dialog box) and each word appears on a different line, just as you wanted.

CHECKING FOR AN ENTRY IN A CELL

Applies to Excel 97, 2000, 2002, 2003, and 2007

There are times when it is helpful to know if a cell contains something—it doesn’t really matter what it contains, just so it contains something. In these instances there are two ways you can approach the problem.

ExcelTips 2008 Page 108

Page 122: Excel tips 2008

Editing Tips

The first solution is to simply use the LEN function to determine if there is a length to what is contained in a cell. For instance, let’s say you wanted to check if there was a value in cell F1. You could use the following:

=IF(LEN(F1)>0,"Found something there","Nothing is there")

If there is nothing in cell F1, then the length will be equal to zero. If there is something in the cell, even a number, then the length will be greater than zero.

The second solution is a variation on the LEN approach. All you need to do is check to see if there is anything in the cell. This may sound odd, but it is easier when you see the formula. For example, the following will check to see if there is anything in cell B4:

=IF(B4<>"","Found something there","Nothing is there")

The test in this formula is True if there is anything in the cell. If the cell is empty, then the test fails.

Another solution you can use is the ISBLANK worksheet function. This function returns True if the target cell is blank, and False if it contains anything.

As an example, let’s suppose you want to check if the user has entered something in cell D7. You can use the following to make the determination:

=IF(ISBLANK(D7),"Input values missing",D7)

In this case the cell containing this formula would contain the same value as in D7, provided something was there. If there is nothing in D7, then the cell contains the text “Input values missing.”

CONCATENATING RANGES OF CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel provides one workbook function and one operator that both have the same purpose—to combine strings into a longer string. The CONCATENATE function and the ampersand (&) operator have essentially the same purpose.

Many people use the ampersand operator in preference to the CONCATENATE function because it requires less typing, but CONCATENATE would become immensely more valuable if it would handle a range of cells. Unfortunately it does not, but you can create your own user-defined function that will concatenate every cell in a range very nicely. Consider the following macro:

ExcelTips 2008 Page 109

Page 123: Excel tips 2008

Editing Tips

Function Concat1(myRange As Range, Optional myDelimiter As String) Dim r As Range Application.Volatile For Each r In myRange Concat = Concat & r & myDelimiter Next r If Len(myDelimiter) > 0 Then Concat = Left(Concat, Len(Concat) - Len(myDelimiter)) End If End Function

This function requires a range and provides for an optional delimiter. The last "If" statement removes the final trailing delimiter from the concatenated string. With the CONCAT1 function, cells can be added and deleted within the range, without the maintenance required by CONCATENATE or ampersand formulas. All you need to do is call the function in one of the following manners:

=CONCAT1(C8:E10) =CONCAT1(C8:E10,"|")

The second method of calling the function uses the optional delimiter, which is inserted between each of the concatenated values from the range C8:E10. There is a problem with this, however: If a cell in that range is empty, then you can end up with two sequential delimiters. If you prefer to have only a single delimiter, then you need to make one small change to the function:

Function Concat2(myRange As Range, Optional myDelimiter As String) Dim r As Range Application.Volatile For Each r In myRange If Len(r.Text) > 0 Then Concat = Concat & r & myDelimiter End If Next r If Len(myDelimiter) > 0 Then Concat = Left(Concat, Len(Concat) - Len(myDelimiter)) End If End Function

ExcelTips 2008 Page 110

Page 124: Excel tips 2008

Editing Tips

CONVERTING TEXT TO VALUES Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are using Excel to massage data imported from another system, you know that often the data needs quite a bit of work. For instance, you might import information that represents a time value, but the data actually ends up being treated by Excel as a text string.

If you find your data in this condition, all is not lost. If you want to convert the text values into actual time values, there are several ways you can accomplish the task. The first is to follow these steps:

1. Insert a blank column to the right of the data you need to convert. 2. Just to the right of the first cell that has a text-formatted time value, enter the following

formula. Make sure you substitute the address of the cell for A1:

=VALUE(A1)

3. Copy the formula down, so that each cell to be converted has the formula to its right. 4. Select the column in which you just put the formulas. 5. Press CTRL+C. This copies the selected information to the Clipboard. 6. Choose Paste Special from the Edit menu. Excel displays the Paste Special dialog box.

(To display this dialog box in Excel 2007, display the Home tab of the ribbon and click the down-arrow under the Paste tool at the left side of the ribbon. Select Paste Special from the resulting menu.)

The Paste Special dialog box.

ExcelTips 2008 Page 111

Page 125: Excel tips 2008

Editing Tips

7. Make sure the Values radio button is selected. 8. Click on OK. All your formulas are replaced with actual values. 9. Format the column using a desired Time format. 10. Delete the original text-formatted time column.

Once you get going with this process, it is pretty quick. Not as quick, however, as the following approach:

1. Select the cells that contain the text-formatted times. If it is an entire column, select the entire column.

2. Choose Text to Columns from the Data menu. (In Excel 2007, select Text to Columns from the Data tab of the ribbon.) Excel launches the Convert Text to Columns Wizard.

The Convert Text to Columns wizard.

3. Don't worry about any of the settings in the Wizard—your data should be converted just fine with the defaults.

4. Click on Finish.

ExcelTips 2008 Page 112

Page 126: Excel tips 2008

Editing Tips

USING SLASHED ZEROES Applies to Excel 97, 2000, 2002, 2003, and 2007

For some printouts it may be beneficial to use a zero with a slash through it rather than the standard zero without a slash. There are several ways you can go about using the slashed zeroes. The first is to insert the Alt+216 symbol, which is a capital O with a slash through it. There are two problems with this approach, however. First is that the symbol is just a bit wider than a regular zero, so it may look a bit funny. The second (and more serious) problem is that the symbol is not viewed as a number by Excel, so you can’t use the values that include this symbol in your calculations.

A better solution is to simply change to a different font that uses a slashed zero in place of the regular zero. There are any number of such fonts that may already be installed on your system. Good candidates are the Terminal, WST_Engl, Fixedsys, Consolas, or Sydnie fonts. You’ll need to experiment with whatever font you select; it may not be available in all the font sizes you expect.

If you cannot locate a suitable font on your own system, there are any number of free fonts available on the web. These are places you can start your search:

http://www.allfontz.com http://www.k8zt.com/zero.html http://www.wm8c.com/slashed_zero_fonts.htm

(Thanks to Kirk Mays, Armando Montes, Chris Bennett, Mary Bartholomew, Dave Latham, Steve Aprahamian, Dave Pettit, Barry Kruse, Richard Raciborski, Henry Noble, Barb Wagner, Dave Berg, Hans Plett, Kishore Muktinutalapati, Jeff Pelletier, Glenn Bamford, Mike Purseglove, Howard Strunk, Ondrej Synac, Paul Podbielski, David Young, Linda Ramirez, and Hector Polla for contributing to this tip.)

COMBINING MULTIPLE ROWS IN A COLUMN

Applies to Excel 97, 2000, 2002, 2003, and 2007

Bonnie described a common problem that occurs when importing a file into Excel. The file being imported is a scanned text file, and the import goes just fine, with one small glitch: in one column where there was wrapped text in the original document, the text now occupies several rows in the worksheet. Bonnie is looking for a way to combine those rows back into a single cell in that column.

There are a couple of ways this can be done. If you don’t have to do this too often, a formulaic approach may be best. Just use the ampersand (&) to concatenate the contents of the rows you want to combine:

ExcelTips 2008 Page 113

Page 127: Excel tips 2008

Editing Tips

=C6 & " " & C7 & " " & C8 & " " & C9

The result is all the text combined into a single cell. You can copy this result to the Clipboard, and then use Paste Special to put it into the final cell where you need it. Finally you can delete the original multiple rows that are no longer needed.

If you need to perform this type of concatenation more than a few times, a simple macro may help:

Sub Combine() Dim J As Integer If Selection.Cells.Count > 1 Then For J = 2 To Selection.Cells.Count Selection.Cells(1).Value = _ Selection.Cells(1).Value & " " & _ Selection.Cells(J).Value Selection.Cells(J).Clear Next J End If End Sub

To use this macro, select the cells you want to concatenate and then run the macro. The contents of all the cells are combined into the first cell in the selection, then whatever is in the other cells is cleared. The macro doesn’t delete any rows; that is left for you to do. It does, however, combine the contents quickly—even more quickly if you assign a shortcut key to the macro.

ERRORS WHEN COPYING REFERENCES TO EXTERNAL CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Kirk noted that if he copies a cell referencing a cell in an external workbook, he gets an error. However, if that external workbook is open when he does the very same steps, he does not get an error message. Kirk wonders why this occurs.

There could be a variety of reasons for this happening. The most probable is that for whatever reason the information that it must get from the external sheet is unavailable or cannot be located.

Another possible reason is that your formula could be an INDIRECT link or the workbook could have been opened and the links not updated. If the formula is complex, Excel requires that the

ExcelTips 2008 Page 114

Page 128: Excel tips 2008

Editing Tips

external workbook be open. (Microsoft has never provided a clue as to what constitutes “complex” in this case. Basically, if you get an error, the formula is “complex.”)

In general, you could consider a formula complex if it does a calculation on the external data to get a result, such as with MATCH, LOOKUP, etc. An example would be storing a month number in workbook A and using that value to calculate year-to-date costs from monthly data stored in individual cells in workbook B. (In other words, you use the month number as an index to access the information in workbook B.)

A workaround for some (but not all) situations is to do the complex calculations completely in workbook B with workbook B linking to workbook A to get the data needed for that calculation. Retrieving the month number from workbook A is not complex and can be easily done by Excel. You could then open workbook A and have it read the result of the calculation from workbook B.

(Thanks to Steve Aprahamian, Lyn Birnie, and Sandy Badkas for contributing to this tip.)

DELETING ALL NAMES BUT A FEW

Applies to Excel 97, 2000, 2002, 2003, and 2007

Do you routinely work with worksheets that contain dozens (or hundreds) of named cells, and most of those names are unnecessary? Cleaning up the names is a huge task, but getting rid of the ones you don’t need can make your workbook smaller and more efficient. The problem is, how do you get rid of a lot of unnecessary names all at once? You can certainly delete them one at a time, but such a process quickly gets tiresome.

One possible solution is to simply create a new workbook and copy the cells from the old workbook to the new one. Highlight the cells in the old workbook, use CTRL+C to copy them, then paste them into worksheets in the new workbook. This will copy almost everything from the old workbook—formulas, formatting, etc. It does not bring copy over print settings or range names. The only task then remaining is to redefine the few names you want in the new workbook.

If you prefer to work with the old workbook (the one with all the names), it is best to create a macro that will do the name deletion for you. You need a macro that will allow you to delete all the names except those you want to keep. The following is a simple approach that accomplishes this task:

Sub DeleteSomeNames() Dim vKeep Dim nm As Name Dim x As Integer Dim AWF As WorksheetFunction

ExcelTips 2008 Page 115

Page 129: Excel tips 2008

Editing Tips

'Add Names to keep here vKeep = Array("Name1", "Name2") Set AWF = Application.WorksheetFunction For Each nm In ActiveWorkbook.Names x = 0 On Error Resume Next x = AWF.Match(nm.Name, vKeep, 0) On Error GoTo 0 If x = 0 Then nm.Delete End If Next Set AWF = Nothing End Sub

Before using the macro, modify the line that creates the vKeep array. Simply enter the names you want to keep within the array, each name surrounded by quotes and separated by commas. (In the example shown here, the names “Name1” and “Name2” will be kept.) The macro loops through all the names in the workbook and uses the Match function to see if the name is one in the array. If it is not, then it is deleted.

If you prefer to use a third-party solution to managing the names in your workbook, a great choice is the Name Manager add-in, written by Jan Karel Pieterse. You can find more information on the add-in here:

http://www.jkp-ads.com/officemarketplacenm-en.asp

TURNING OFF INSERT OPTIONS Applies to Excel 2002, 2003, and 2007

Excel 2002 and later versions include a feature that allows you to modify how you insert rows, columns, or cells in your worksheet. When you insert any of these, Excel displays a small, floating “button” right near the inserted row, column, or cell. The button, called “Insert Options,” has a small paintbrush on it, similar to the Format Painter tool. Click the button, and Excel displays some options about how the inserted row, column, or cell should be formatted.

If you find the Insert Options button distracting, or if you never use it, you may want to turn it off. Follow these steps if you are using Excel 2002 or Excel 2003:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Edit tab is displayed.

ExcelTips 2008 Page 116

Page 130: Excel tips 2008

Editing Tips

The Edit tab of the Options dialog box.

3. Clear the Show Insert Options Buttons check box. 4. Click on OK.

If you are using Excel 2007, follow these steps instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left of the dialog box click Advanced. 3. Scroll through the available options until you see the section named Cut, Copy, and

Paste. 4. Clear the Show Insert Options Buttons check box. 5. Click on OK.

TURNING OFF PASTE OPTIONS Applies to Excel 2002, 2003, and 2007

The latest versions of Excel include a feature that really annoys some people: Paste Options. When you paste some tidbit of information in your worksheet, Excel displays a small, floating

ExcelTips 2008 Page 117

Page 131: Excel tips 2008

Editing Tips

“button” right near the end of the pasted information. The button looks like the Paste tool on the toolbar: a small clipboard with a piece of paper over it. This is the Paste Options button. If you move your mouse pointer over the button, you find that it is really a drop-down menu, and clicking on the menu gives you a few options that you can apply to what you just pasted.

If you find the Paste Options button distracting, or if you never use it, you may want to turn it off. Follow these steps in Excel 2002 or Excel 2003:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Edit tab is displayed.

The Edit tab of the Options dialog box.

3. Clear the Show Paste Options Buttons check box. 4. Click on OK.

You’ll need to follow these steps if you are using Excel 2007:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left of the dialog box.

ExcelTips 2008 Page 118

Page 132: Excel tips 2008

Editing Tips

The Advanced options of the Excel Options dialog box.

3. In the Cut, Copy, and Paste section, clear the Show Paste Options Buttons check box. 4. Click OK.

SYMBOLS CONVERT TO NUMBERS IN EXCEL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Alan wants to enter a symbol into a cell. (In this case he is entering a tick mark.) When he does this using Insert | Symbol, the symbol is placed into the cell properly, but as soon as Alan presses ENTER to move to another cell, the symbol converts to a number. Alan, of course, wonders why this is happening.

It could be that the cell contents are being modified by some event-driven macro. For instance, there could be a macro that is triggered each time a change is made in the workbook, and the macro is making the change to what you are entering. You would only find out if this is the case by doing some digging in the workbook to see if there are any macros there and checking out what they do.

The more likely scenario, however, is that you have a formatting or font problem in the cell where you are entering the symbol. When you use the Symbol dialog box, you are inserting a character into your worksheet. How the character appears depends on the way in which the cell is formatted into which the symbol is being inserted.

ExcelTips 2008 Page 119

Page 133: Excel tips 2008

Editing Tips

Like any other character in a worksheet, a symbol inserted using the Symbol dialog box has a character code associated with it. The code indicates which character from a particular font is displayed. If that code, for instance, is 49 and the font is Wingdings, then the character will look like an open file folder. The same character code in most any other font will produce a number, in this case the number 1.

Thus, if your cell is formatted using the Calibri typeface, then the character codes inserted into the cell will use the characters from that typeface. If you want to use a different typeface, such as Wingdings or some other symbol font for your symbols, then you may need to format the cell to use that font.

(Thanks to Sadnesh Badkas, Steve Aprahamian, John Brown, Charlie O’Neill, Richard Raciborski, and Carole Jean Dorak for contributing to this tip.)

USING SUBTOTALS AND TOTALS Applies to Excel 97, 2000, 2002, 2003, and 2007

There are many times you may need to have both subtotals and totals in the same column of data. The easiest solution would be to put subtotals and totals in different columns (like accountants often do), but this is not always practical for the data at hand. In these instances, there are three different approaches you can use.

The first approach is to place your various subtotals, as desired. Then, when it comes time to place your totals, simply use a modified SUM formula. For instance, if you want to get a total for the range F10:F32, and there are subtotals interspersed in the column, you would use this formula for your total:

=SUM(F10:F32)/2

This works because the addition of the subtotals simply doubles the real value of the column. The second way is to use the familiar AutoSum feature of Excel, accessible through the toolbar. Insert your subtotals as normal in the column. When you are ready to add your total, select all the cells you want to total, as well as the cell where your total will appear. So if you want a total for the range B3:B20 (which includes some subtotals), and you want the total to appear in B21, select cells B3 through B21. Then click on the AutoSum tool. The total inserted by Excel in cell B21 is the sum of all the subtotals in the column.

If you are using a well-defined data table (headings, multiple columns, etc.), then you may also want to use the built-in subtotals feature of Excel. This works particularly well if you need subtotals based on a change in a particular column value. For instance, you may have a table that lists products in one column, quantities in another, and values in another. You can insert subtotals and totals for this table by following these steps:

1. Sort the table by the values in the Products column.

ExcelTips 2008 Page 120

Page 134: Excel tips 2008

Editing Tips

2. Display the Subtotal dialog box. (In versions of Excel prior to Excel 2007 choose Subtotals from the Data menu. In Excel 2007 display the Data tab of the ribbon and click Subtotal tool in the Outline group.)

The Subtotal dialog box.

3. Make sure the At Each Change In drop-down list is set to Products. (This indicates where Excel will insert subtotals.)

4. The Use Function drop-down list should be set to Sum. 5. Using the list in the Add Subtotal To box, choose the columns to which subtotals should

be added. 6. Make sure the Summary Below Data check box is selected. (This inserts the total you

need.) 7. Click on OK.

COPYING SUBTOTALS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel has a handy feature that allows you to automatically add subtotals to a data list. (How to create subtotals was covered in other issues of ExcelTips.) You may be wondering, once the subtotals are in place, how you can copy the subtotals to a different worksheet. This is actually rather easy to do, if you follow these steps:

1. Add your worksheet subtotals as you normally would.

ExcelTips 2008 Page 121

Page 135: Excel tips 2008

Editing Tips

2. Collapse the information in the list so that only the subtotals are showing. (Click on the small 2 in the outline levels shown at the top of the gray area at the left of the worksheet.)

3. Select the range of cells containing the subtotals you want to copy. (Do not select complete rows or columns; just select the range of cells.)

4. Press F5. Excel displays the Go To dialog box. 5. Click on Special. Excel displays the Go To Special dialog box.

The Go To Special dialog box.

6. Make sure the Visible Cells Only option is selected. 7. Click on OK. Excel selects just the visible information from the range you specified in

step 3. 8. Press CTRL+C to copy the rows to the Clipboard. 9. Select the cell where you want to paste the subtotals. 10. Press CTRL+V to paste the information.

ExcelTips 2008 Page 122

Page 136: Excel tips 2008

Editing Tips

WILDCARDS IN 'REPLACE WITH' TEXT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Anne-Mie realizes that she can use wildcards (*?) to search in Excel, but she wonders if she can use wildcards in the replace string. For instance, she would like to search for “ab*de” and replace it with “aa*de”, where the asterisk represents any number of characters, or none at all.

The short answer is that there is no way to do this in Excel, as described. If you only wanted to convert the second character of a text value from “b” to “a”, then that can be done rather easily:

=REPLACE(A1,2,1,"a")

This, however, is probably not what you want to do; you want a way to use wildcards in the “replace with” text. The technical term for doing such string replacements is called REGEX, which is short for Regular Expressions. REGEX started with languages like Perl but was so powerful that many other programming languages added it on.

The VBA used in Excel is no exception. REGEX was added to Visual Basic 6.0, which means that it made its way to Excel’s VBA in Excel 2003. The first step in using REGEX is to turn it on. You do this in the VBA Editor by choosing Tools | References and then making sure there is a check mark next to the Microsoft VBScript Regular Expressions 5.5 option.

Enabling this reference allows you to create REGEX objects. These objects possess a Test method and a Pattern property. This means that you set the Pattern property, and then the Test method checks to see if the pattern exists. A REGEX object also has a Replace method, which is used to do replacements.

Before proceeding, it is important to understand that regular expressions can get very complex and, well, “geeky.” There is no way around it; how to work with regular expressions has been the subject of entire books. Fortunately, for the purposes of this tip, the expressions are rather simple in nature. In this case we’ll use the pattern “^ab.*de$”. This pattern refers to a word that starts (indicated by the ^) with “ab” followed by an arbitrary expression (indicated by *) consisting of at least one character (indicated by the period) and ending (indicated by the $) with “de”.

Here is the code that implements the use of the REGEX object to do the actual replacements.

Public Function SearchNReplace1(Pattern1 As String, _ Pattern2 As String, Replacestring As String, _ TestString As String) Dim reg As New RegExp reg.IgnoreCase = True reg.MultiLine = False reg.Pattern = Pattern1 If reg.Test(TestString) Then

ExcelTips 2008 Page 123

Page 137: Excel tips 2008

Editing Tips

reg.Pattern = Pattern2 SearchNReplace = reg.Replace(TestString, ReplaceString) Else SearchNReplace = TestString End If End Function

To use this macro, start with the strings you want to change in column A. Assuming that the first string is in cell A1, you could place the following into another cell in order to get the changed text:

=SearchNReplace1("^ab.*de$","^ab","aa",A1)

This tells the macro that the pattern you want to look for is “^ab.*de$” (the first parameter), and that you want to replace “^ab” with “aa”. This formula can be pasted down the column, and you end up with a conversion of column A where the string “ab*de” is replaced by “aa*de”.

If you are using an older version of Excel that does not allow you to create REGEX objects, or if you would prefer not to do so, then you can create a macro that will simply step through a group of selected cells and look for any cell that begins with “ab” and ends with “de”, and then replaces the beginning part with “aa”.

Sub SearchNReplace2() Dim sFindInitial As String Dim sReplaceInitial As String Dim iLenInitial As Integer Dim sFindFinal As String Dim sReplaceFinal As String Dim iLenFinal As Integer Dim sTemp As String Dim rCell As Range sFindInitial = "ab" sReplaceInitial = "aa" sFindFinal = "de" sReplaceFinal = "de" For Each rCell In Selection sTemp = rCell.Value iLenInitial = Len(sFindInitial) iLenFinal = Len(sFindFinal) If Left(sTemp, iLenInitial) = sFindInitial And _ Right(sTemp, iLenFinal) = sFindFinal Then sTemp = Mid(sTemp, iLenInitial + 1) sTemp = Left(sTemp, Len(sTemp) - iLenFinal) sTemp = sReplaceInitial & sTemp & sReplaceFinal rCell.Value = sTemp End If Next Set rCell = Nothing

ExcelTips 2008 Page 124

Page 138: Excel tips 2008

Editing Tips

ExcelTips 2008 Page 125

End Sub

To use this routine, simply select the cells you want to change, and then execute the macro. You should also make changes to the sFindInitial, sReplaceInitial, sFindFinal, and sReplaceFinal variables, as needed.

(Thanks to Steve Aprahamian, John Rose, and Russell Hendel for contributing to this tip.)

Page 139: Excel tips 2008

Formatting Tips

NUMBER FORMATTING SHORTCUTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

The typical way that people apply formatting to cells is to use the tools on the toolbars or ribbons, or to display the Format Cells dialog box and make formatting choices. For those who prefer to not remove their hands from the keyboard, however, Excel also provides a number of handy shortcuts you can use to format your cells.

Shortcut Effect Ctrl+Shift+~ General format Ctrl+Shift+! Number format with two decimal places and thousands separator Ctrl+Shift+$ Currency format with two decimal places and negatives in parentheses Ctrl+Shift+# Date format Ctrl+Shift+@ Time format with minutes and am/pm Ctrl+Shift+% Percentage format with no decimal places Ctrl+Shift+^ Scientific notation with two decimal places

UNABLE TO FORMAT CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

Bill has a large worksheet that he can no longer format cells within. When he right-clicks on a cell and selects Format, the Format Cells dialog box never appears. Likewise, if he chooses Cells from the Format menu, the dialog box never shows up.

This, obviously, is not the way that Excel is supposed to behave. Since the problem occurs with only a single workbook, the problem is most likely not with Excel itself, but with the workbook. There are a few things you can try to track down the problem.

ExcelTips 2008 Page 126

Page 140: Excel tips 2008

Formatting Tips

First, make sure that you open the workbook with macros disabled. Hold down the SHIFT key as you double-click the workbook in Windows Explorer, then indicate that you don’t want to enable the macros. If the problem persists, you can rule out it being rooted in a macro. If the problem goes away, then you know you need to examine the macros to see which one is causing the problem.

Second, the file (which Bill mentions is both old and large) could have so many formats defined within it that you can no longer do formatting. This problem has been covered in other issues of ExcelTips, and you can find related information, including a way to free up formats, here:

http://www.j-walk.com/ss/excel/eee/eee007.txt

Look for the macro entitled DeleteUnusedCustomNumberFormats; it can help clean up the no-longer-used custom formats.

Another thing to try is to save the worksheet as an HTML file, get out of Excel, get back into the program, and then load the HTML file. Sometimes the “round trip” for a worksheet will clear up some quirks that may be confusing Excel.

CHANGING FONT SIZE USING A SHORTCUT KEY

Applies to Excel 97, 2000, 2002, 2003, and 2007

One of the interesting shortcut keys in Excel is the one that allows you to change the point size of the selected cells. The shortcut key is CTRL+SHIFT+P, but exactly how the shortcut functions depends on what you have displayed on the screen.

This may sound odd, but you can try it out. If you have the Formatting toolbar displayed (as most people do), then pressing CTRL+SHIFT+P selects the Font Size control on the toolbar. You can then type the font size you want to use and press ENTER. (Pretty handy if you don’t want to take your hands off the keyboard.)

If you don’t have the Formatting toolbar displayed for some reason, then it seems obvious that the Font Size control can’t be selected—it isn’t even visible. Instead, pressing CTRL+SHIFT+P results in the Font tab of the Format Cells dialog box being displayed.

In Excel 2007 there is no differentiation of behavior based on the presence of the Formatting toolbar simply because there is no longer a Formatting toolbar. Pressing CTRL+SHIFT+P brings up the Format Cells dialog box, with the Font tab selected.

ExcelTips 2008 Page 127

Page 141: Excel tips 2008

Formatting Tips

NOTATION FOR THOUSANDS AND MILLIONS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jim wonders how he can get Excel to automatically display numbers using "k" for thousands and "m" for millions. As an example, if a cell contains the value $470,000 he would like it displayed as $470k; if it contains the value $1,107,432 he would like it displayed as $1.1m.

One obvious method is to create a formula that will display the information as desired. The following formula will take into account the magnitude of the number in cell B2 and then provide a formatted text string appropriate to that magnitude:

=IF(B2 < 1000,B2,IF(B2 < 1000000, "$" & ROUND(B2/1000,1) & "k", "$" & ROUND(B2/1000000,1) & "m"))

Remember that this is a single formula and should be entered entirely on one line. The drawback with such an approach, of course, is that the formula takes up space within your worksheet. To get around this you could, instead, create a custom format that will simply affect the display of the number in the cell.

To create a custom format if you are using a version of Excel prior to Excel 2007, choose Cells from the Format menu, display the Number tab, and click Custom at the left side of the dialog box. If you are using Excel 2007 then you should display the Home tab of the ribbon and click the small icon at the lower-right corner of the Number group. Again click Custom at the left side of the dialog box.

Here’s the custom format you should actually use:

[>1000000]$#.0,,"m";[>1000]$#,"k";$#,##0

This format will display both millions and thousands using the desired notation. If the number is below a thousand then it will be displayed without any special notation. As appropriate, values are rounded to one decimal place.

(Thanks to Steve Aprahamian, Benazir Ibrahim, Tom DeLuca, Dave Pettit, Tom Hamilton, Joe Edmiston, Gabor Mathe, Kirk Mays, John Vander Linden, Jim Wise, Nick Bafaloukos, Glenn Bamford, and Chris Purtill for contributing to this tip.)

ExcelTips 2008 Page 128

Page 142: Excel tips 2008

Formatting Tips

ALTERING THE DISPLAYED FORMAT OF NUMBERS TO THE NEAREST 100

Applies to Excel 97, 2000, 2002, 2003, and 2007

Frank asked if there is a way, using a custom number format, to round the display of numbers to the nearest 10, 100, etc., without affecting the original numbers.

The answer is that there is a way, and there isn’t a way. (Don’t you love those answers?) There are custom number formats that allow you to round the display to the nearest thousand or the nearest million, as follows:

[<=500] "0";#,"000" [<=500000] "0";#,,"000000"

The first format will round to the nearest thousand, and the second will round to the nearest million. If you are looking for a custom format that will round to some other power of 10, you are out of luck, however. In those instances, the best solution may be to simply create another worksheet that uses formulas for rounding and uses the contents of the original worksheet as the source.

USING AN EXACT NUMBER OF DIGITS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Henk asked if there is a way in Excel to display a number using six digits, independent of the placement of the decimal point. For instance, 0.1 would be displayed as 0.10000, 200 would be displayed as 200.000, and 25000 would be displayed as 25000.0.

Unfortunately, there is no formatting that will do the trick; all display formatting seems to be dependent on the position of the decimal point. You can format a display for a specific number of digits after the decimal point, but that number of digits will be used regardless of how many digits appear before the decimal point.

Several ExcelTips subscribers came up with suggestions that involve using formulas to display the number as desired. For instance, the following formula will display the value in A1 using six digits:

=FIXED(A1,IF(ABS(A1)<1,5,5-INT(LOG(ABS(A1)))),TRUE)

ExcelTips 2008 Page 129

Page 143: Excel tips 2008

Formatting Tips

Other readers provided formulas that relied on converting the number to a text string and displaying it as such. Converting a number to its textual equivalent, however, has the distinct drawback of no longer being able to use the number in other formulas. (Remember—it is text at this point, not a number.) The above formula does not have that limitation.

If you wanted to, you could also use a macro to set the formatting within a cell that contains a value. The advantage to such a macro is that you don’t have to use a cell for a formula, as shown above. The drawback to a macro is that you need to remember to run it on the cells whenever values within them change. The following macro is an example of such an approach:

Sub SetFigures() Dim iDecimals As Integer Dim bCommas As Boolean Dim sFormat As String Dim CellRange As Range Dim TestCell As Range bCommas = False 'Change as desired Set CellRange = Selection For Each TestCell In CellRange If Abs(TestCell.Value) < 1 Then iDecimals = 5 Else iDecimals = 5 - Int(Log(Abs(TestCell.Value)) / Log(10#)) End If sFormat = "0" If bCommas Then sFormat = "#,##0" If iDecimals < 0 Then sFormat = "General" If iDecimals > 0 Then sFormat = sFormat & _ "." & String(iDecimals, "0") TestCell.NumberFormat = sFormat Next TestCell End Sub

In order to use the macro, simply select the cells you want to format, then execute it. Each cell in the range you selected is set to display six digits, unless the number in the cell is too large or too small.

FORMATTING CURRENCY Applies to Excel 97, 2000, 2002, 2003, and 2007

Eric asked if there was a way to easily format cells so what would normally appear as $10,000.00 would appear as $10.000,00. This format being described is the difference between

ExcelTips 2008 Page 130

Page 144: Excel tips 2008

Formatting Tips

the US method of displaying figures (using commas as thousand separators and a period as a decimal sign) and the European method of displaying figures (using periods as thousand separators and a comma as a decimal sign).

There are three ways you can accomplish a switch. The easiest method is to simply change the Regional Settings in Windows. The exact way you do this depends on the version of Windows you are using, but in general there is a choice in the Windows Control Panel that allows you to specify regional settings. All you need to do is modify those settings to match the numeric display format desired. The change will affect not only the display of numbers in Excel, but in other Windows-compliant programs, as well.

The second method is to use a formula to handle the numeric display. This has the drawback of converting the numeric value to text, but it could be easily done. For instance, let’s assume that you have the formatted numeric value $10,000.00 in cell A1. The following formula, in a different cell, would display the text $10.000,00:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(TEXT(A1, "$#,##0.00"),".","^"),",","."),"^",",")

This formula first converts the number to an initial currency format in text. Then the SUBSTITUTE function is used to first change "." to "^" ("^" is used as a temporary placeholder), and then change "," to ".", and finally "^" to ",".

The final method has the advantage of leaving your numbers as numbers, instead relying on a custom format. All you need to do is to multiply your values by 100 and then use the following custom format:

#"."###"."###","##

The format allows any number up to 9.999.999,00 to be used. If you deal with numbers that have more than two decimal places, you will need to adjust your custom format accordingly, or adjust the value being displayed so that it has nothing to the right of the decimal point after it is multiplied by 100.

FILLING A CELL Applies to Excel 97, 2000, 2002, 2003, and 2007

There may be times when you need to fill a cell with a particular character or group of characters. For instance, you may need to fill a cell with the characters “ guess ” (with the spaces) for the entire width of the cell. Excel allows you to do this very easily. It repeats the characters over and over again, regardless of the cell width. To utilize this feature, follow these steps if you are using a version of Excel prior to Excel 2007:

ExcelTips 2008 Page 131

Page 145: Excel tips 2008

Formatting Tips

1. Type the characters that you want repeated in the cell. 2. Choose Cells from the Format menu. Excel displays the Format Cells dialog box. 3. Make sure the Alignment tab is displayed.

The Alignment tab of the Format Cells dialog box.

4. Use the Horizontal drop-down list to select the Fill option. 5. Click on OK.

If you are using Excel 2007 then you should follow these steps instead:

1. Type the characters that you want repeated in the cell. 2. Display the Home tab of the ribbon. 3. In the lower-right corner of the Alignment group, click the small icon. Excel displays

the Alignment tab of the Format Cells dialog box. 4. Use the Horizontal drop-down list to select the Fill option. 5. Click on OK.

Excel will repeat whatever you typed in the cell, until the entire cell is filled. For instance, if you typed two characters, then those two characters are repeated over the width of the cell.

ExcelTips 2008 Page 132

Page 146: Excel tips 2008

Formatting Tips

FILL COLOR DOESN'T DISPLAY Applies to Excel 97, 2000, 2002, 2003, and 2007

Rick wrote about a problem he was having when viewing cells that have a fill color. It seems that the color doesn’t show up on the display, but it does show up when he prints the worksheet.

This problem is most likely related to the settings in Windows, not in Excel. Follow these general steps:

1. Display the Control Panel. 2. Double-click the Accessibility Options applet. Windows displays the Accessibility

Options dialog box. 3. Make sure the Display tab is visible.

The Display tab of the Accessibility Options dialog box.

4. Clear the Use High Contrast check box. 5. Click OK.

ExcelTips 2008 Page 133

Page 147: Excel tips 2008

Formatting Tips

The fill colors should now be visible in the worksheet. They were “hidden” to make viewing data easier for those with certain types of visual limitations. This problem is detailed in the Microsoft Knowledge Base:

http://support.microsoft.com/?kbid=833258

REFERENCING EXTERNAL CELL COLORS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Beth asked how to copy the color formatting of an external cell to a cell in the current workbook. Unfortunately, there is no intrinsic way to do this by using the linking features of Excel. You can, however, copy formatting from one workbook to another by using a macro.

As an example, consider the following macro code:

Workbooks.Open Filename:= "<<Path of Source workbook>>" Range("<<Range of Source Data>>").Select Selection.Copy Windows("<<TargetBook.xls>>").Activate Range("<<Range of Target Data>>").Select Selection.PasteSpecial Paste:=xlPasteFormats, _ Operation:=xlNone, SkipBlanks:=False, _ Transpose:=False

This code does several things. First, it opens the external workbook and selects the range of cells you want to copy. The Copy method is then invoked, so the source range is now in the Clipboard. The macro then switches to the target workbook and select the range there. Finally, the PasteSpecial method is used to paste only the format of the source cells.

If you decide to use code like this, you can place it in the Auto_Open macro for the target workbook. Of course, you need to replace anything within angle brackets (<< and >>) , along with the angle brackets themselves, with the real information necessary to make the macro work. (In other words, provide the proper path and workbook names, along with the source and target ranges.)

ExcelTips 2008 Page 134

Page 148: Excel tips 2008

Formatting Tips

SETTING VERTICAL ALIGNMENT Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel provides several different ways you can align information from top to bottom (vertically) within a cell. You set the alignment by first selecting the cells you want to format and then displaying the Alignment tab of the Format Cells dialog box. To display the dialog box in versions of Excel prior to Excel 2007, choose Cells from the Format menu. If you are using Excel 2007, display the Home tab of the ribbon and click the small icon at the bottom-right of the Alignment group.

The Alignment tab of the Format Cells dialog box.

On the Alignment tab, use the Vertical drop-down list to make your selection. There are four different alignment options available in Excel 97 and Excel 2000, and five in later versions of Excel:

• Top. The information in the cell is situated such that the top line of text appears at the top of the cell.

ExcelTips 2008 Page 135

Page 149: Excel tips 2008

Formatting Tips

• Center. Information is centered half-way between the top and bottom borders of the cell.

• Bottom. This is the default vertical alignment. Information is aligned at the bottom of the cell.

• Justify. Text is spread evenly throughout the cell. The information within the cell is wrapped within the column (if necessary), and the row height is adjusted so that all lines fit within the cell and so all information reaches both the top and bottom borders of the cell. Column width is not affected at all.

• Distributed. This option is available in Excel 2002 or later versions. When selected, text is spread evenly between the top of the cell and the bottom. Effectively, blank space is placed between each line so that the complete cell is filled.

USING STRIKETHROUGH FORMATTING

Applies to Excel 97, 2000, 2002, 2003, and 2007

One of the character formats you can use within Excel is referred to as strikethrough. This simply means that Excel shows a horizontal line through the middle of the character (or characters) to which the attribute has been applied. Strikethrough can be applied in this manner:

1. Select the cell whose contents you want struck through, or select the characters within a cell, if you don’t want them all struck through.

2. Press CTRL+1 or, in Excel 2007, CTRL+SHIFT+F to display the Format Cells dialog box. 3. Make sure the Font tab is displayed.

ExcelTips 2008 Page 136

Page 150: Excel tips 2008

Formatting Tips

The Font tab of the Format Cells dialog box.

4. Select the Strikethrough check box. 5. Click OK.

DRAWING BORDERS Applies to Excel 97, 2000, 2002, 2003, and 2007

The normal way to add borders around a cell or range of cells is to select the cell or range, and then choose Format | Cells and use the Border tab. There is a quick shortcut you can use to actually “draw” borders around cells.

Take a look at the Borders tool on the Formatting toolbar (in versions of Excel prior to Excel 2007). Click the down-arrow at the right of the tool and you’ll see a number of different borders you can apply. At the bottom of the selections is a choice named “Draw Borders.” Choose this, and the mouse pointer becomes a small pencil and the Borders toolbar appears.

ExcelTips 2008 Page 137

Page 151: Excel tips 2008

Formatting Tips

If you are using Excel 2007 you can turn on this tool by displaying the Home tab of the ribbon. In the Font group, click the down-arrow at the right of the Border tool. Excel displays a whole range of options; you want to choose Draw Borders.

Now you can just click and draw borders where ever you want them. The controls in the Borders toolbar allow you to specify what type of line you want, along with the line color. The pencil tool (which is selected by default when you choose to Draw Borders) is used for drawing borders, and the eraser tool is used to clear borders.

When you are done creating your borders, just dismiss the Borders toolbar. The mouse pointer returns to normal, and you can use Excel like you normally do.

ADDING DIAGONAL BORDERS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to add all sorts of borders to cells in a worksheet. You can place borders on the left, right, top, and bottom of a cell. If you select a range of cells, you can add borders to the left, right, top, bottom, and in between, meaning that the borders could be between cells within the selected range.

Many people don't realize that you can also place diagonal borders. This means that a border can appear from the top-left to the lower-right corners of a cell, or from the top-right to the lower-left. To take advantage of diagonal borders, follow these steps:

1. Select the cell you want to have the diagonal border. 2. Choose Cells from the Format menu. Excel displays the Format Cells dialog box. (To

display the dialog box in Excel 2007, display the Home tab of the ribbon, click Format in the Cells group, and then choose Format Cells.)

3. Make sure the Border tab is selected.

ExcelTips 2008 Page 138

Page 152: Excel tips 2008

Formatting Tips

The Border tab of the Format Cells dialog box.

4. At the bottom left and right corners of the Preview area of the dialog box you should see buttons that have diagonal lines on them. Click the line that represents the type of diagonal border you want to use.

5. Click on OK.

Diagonal borders can only be applied to cells, not to rectangular areas you select onscreen. For instance, if you choose cells A5:C12, the diagonal border won’t go from the top-left corner of cell A5 to the bottom-right corner of cell C12. Instead, it is applied to the individual cells within the selected range.

ExcelTips 2008 Page 139

Page 153: Excel tips 2008

Formatting Tips

PARTIALLY BLOCKING SOCIAL SECURITY NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a worksheet that includes Social Security Numbers in it, you may be looking for a way to protect the numbers by only displaying the last four digits. So, instead of displaying 278-43-6128, you would only want to display ***-**-6128.

The way to accomplish this depends, in large part, on whether the Social Security Number is stored in the cell as a number or as text. If the SSN is entered with its dashes (as in 278-43-6128), then Excel stores it as text. If the SSN is entered without dashes (as in 278436128), then Excel stores it as a number.

If the SSN is stored as a number, you may be tempted to create a custom format that hides the first part of the number. Unfortunately, there is no way to do this with a custom format. You could create a custom format that would hide all except the first digits, as in this manner:

000,,"-**-****"

As you can surmise from this example, custom formats don’t allow you to mask out anything except the last portion of any value. Another drawback to this approach, however, is that Excel “rounds” the SSN, such that 278436128 is displayed as 278-**-****.

The best solution to displaying only the last part of a Social Security Number is to use a second column for the actual display. Instead of trying to format the number (or text) itself, it is best to use a formula that refers to the number and creates the desired result. For instance, if the SSN is in cell B7, then you would place the following formula in a different cell:

="***-****-" & RIGHT(B7,4)

This formula will work with any SSN, regardless of whether it is stored as a number or as text. The other big benefit to this approach is that it allows you to completely hide the original numbers. Even if you were able to use a custom format to hide the first portion of the number (which you can’t), someone could still see the SSN in the Formula bar if the cell containing the number is selected.

Using the formula approach, however, allows you to hide the source column, or use sheet protection to hide the contents of the column. This is a big benefit if your goal is to really protect the Social Security Number from prying eyes.

ExcelTips 2008 Page 140

Page 154: Excel tips 2008

Formatting Tips

ADDING DROP SHADOWS TO CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When formatting the data in your worksheet, you may wonder if there is a way to add a drop shadow to a single cell. There is a very simple way to do it, depending on your version of Excel. If you are using a version of Excel prior to Excel 2007, follow these steps:

1. Select the cell that you want to have the drop shadow. 2. Make sure the Drawing toolbar is displayed. (If you don't see it, click View | Toolbars |

Drawing.) 3. On the Drawing toolbar, click the Shadow Style tool. (It is the second from the right.)

You'll see a palette of various shadows you can apply. 4. Select the shadow desired.

That's it. What Excel technically does is to add a text box, the exact same size as the cell you selected in step 1, over the top of the cell. This text box is transparent so that the cell contents show through, but it has borders applied so that you see the drop shadow.

If you are using Excel 2007, which doesn't have a Drawing toolbar, then you are pretty much out of luck as far as a simple answer goes. Even searching through the tools available for the Quick Access toolbar, there is no command that functions the same as the Shadow Style tool on the old Drawing toolbar. The best you can do is to follow these general steps:

1. Add an AutoShape to the worksheet that is the same size as the cell. 2. Turn off the fill for the AutoShape. 3. Add a drop shadow to the AutoShape.

This, of course, could get a bit tedious over time. For this reason, you may want to use a macro to actually perform the steps. The following macro will add a drop shadow to whatever range you have selected in the worksheet.

Sub AddDropShadows() Dim ar As Range For Each ar In Selection.Areas AddDrop ar Next ar End Sub

Sub AddDrop(rng As Range, _ Optional vShadowType = msoShadow14, _ Optional vSchemeColor = 55) With rng.Parent.Shapes.AddShape( _ msoShapeRectangle, rng.Left, rng.Top, _

ExcelTips 2008 Page 141

Page 155: Excel tips 2008

Formatting Tips

rng.Width, rng.Height) .Fill.Visible = msoFalse .Shadow.Obscured = msoTrue .Shadow.Type = vShadowType .Shadow.ForeColor.SchemeColor = vSchemeColor .Shadow.Visible = msoTrue .ThreeD.Visible = msoFalse End With End Sub

There is one thing that you should know about adding drop shadows to cells in Excel 2007: The shadow, itself, is not as “smart” as in earlier versions of Excel. When adding a drop shadow in Excel 2003, for instance, the shadow is appears at the bottom and right side of the shape added, as if the shape is filled. In Excel 2007 the drop shadow is for all four sides, so it looks a bit unprofessional when applied to a cell.

(Thanks to Andrija Vrcan, Steve Aprahamian, Dave Pettit, and Mark Rotchell for contributing to this tip.)

UNHIDING A SINGLE COLUMN Applies to Excel 97, 2000, 2002, 2003, and 2007

I regularly hide and unhide columns in my worksheets. If I have an entire range of columns hidden, I find it a bother to unhide a single column out of all those hidden. For instance, if I hide columns C:M, and I want to unhide column F, then I need to unhide the entire range and then rehide C:E and G:M. (There are other ways I could accomplish the same task, but none of them are particularly endearing.)

However, I find that a single column can be unhidden very easily using a macro. Consider the following:

Sub UnhideSingleColumn() Dim Col As String Dim rng As Range StartHere: Col = InputBox("Enter column to unhide.", "Unhide Column") If Col = "" Then Exit Sub On Error Resume Next ' if not a valid range, an error occurs Set rng = ActiveSheet.Columns(Col) If Err.Number <> 0 Then On Error GoTo 0 Err.Clear MsgBox "Invalid input! Please input a valid column." GoTo StartHere End If

ExcelTips 2008 Page 142

Page 156: Excel tips 2008

Formatting Tips

rng.EntireColumn.Hidden = False MsgBox "Column " & UCase(Col) & " is now visible.", _ vbOKOnly, "Unhide Specified Column" Set rng = Nothing On Error GoTo 0 End Sub

The macro prompts the user for which column should be made visible, and then tries to select that column. If the column cannot be selected, then an error is generated and the user is again asked for input. If the column can be selected, then its .Hidden property is turned off, thereby making the column visible.

CONVERTING FROM NUMBERS TO TEXT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jocelyn asked if there is a way to easily convert numbers to their text equivalent. For instance, to convert the numeric value 6789 to the text digits “6789.”

There are multiple ways that you can approach this problem. One way is to simply specify to Excel that the cells should be treated as text. Display the Format Cells dialog box and then on the Number tab make sure that Text is selected. Any selected cells are then formatted as if they were text, and are moved to the left side of their cells (unless you have some other alignment format specified).

The applicability of this solution, however, depends on the version of Excel you are using. In some versions it will work as described here, but in others it may not. There is another thing you can try, however:

1. Select the cells you want to convert. 2. Choose Cells from the Format menu. Excel displays the Format Cells dialog box. (To

display the dialog box in Excel 2007, display the Home tab of the ribbon, click Format in the Cells group, and then choose Format Cells.)

3. Make sure the Number tab is selected.

ExcelTips 2008 Page 143

Page 157: Excel tips 2008

Formatting Tips

The Number tab of the Format Cells dialog box.

4. In the list of formatting Categories, choose Text. 5. Click on OK. 6. Press CTRL+C. This copies the cells you selected in step 1. 7. Choose Paste Special from the Edit menu. Excel displays the Paste Special dialog box. 8. Choose the Values radio button. 9. Click on OK.

Another thing you can do is to use the TEXT worksheet function. Let’s say you have the value 6789 in cell A7. In cell B7 you could place the following:

=TEXT(A1, "#,##0.00")

This usage of TEXT results in a text digits that have the thousands separator in the right place and two digits to the right of the decimal point, as in “6,789.00”. You can specify, as the second parameter to TEXT, any formatting desired. If you want the number converted to text without any special formatting, you can use the following:

ExcelTips 2008 Page 144

Page 158: Excel tips 2008

Formatting Tips

=TEXT(A1, "0")

The result is the textual equivalent of an integer value.

CONVERTING FORCED TEXT TO NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you enter information in a worksheet, Excel does its best to decipher what type of data you are entering. If your entry can be translated as a number or a date, then Excel treats it that way. You can overcome this natural tendency of Excel by formatting a cell as text before entering information in it. When you do, the information in the cell is always treated as text.

Of course, forcing Excel to treat your input as text can have unwanted repercussions later. For instance, you may decide that you want to add up the contents of cells that are formatted as text. If you use a formula such as the following, then Excel has no problem:

=A1 + A2

Excel provides the correct sum, provided at least one of the cells (A1 or A2) was not formatted as text. To make matters tricky, however, if you use the SUM function (which most people do when summing an entire column or row), then you won’t get the proper sum. The SUM function ignores any cells formatted as text. How do you get around this?

It is possible to remove the text formatting attribute from the cells you want to sum, but that won’t cause Excel to reassess the contents of the cells and treat them as numbers or dates, where appropriate. There are several different ways you can force the conversion of forced text into numeric values, ranging from macros to using formulas in other columns to perform the conversion. The following two solutions, however, seem to be the easiest and quickest.

The first method is accomplished by following these steps:

1. Enter the value 1 in an empty cell. 2. Select the cell and press CTRL+C. The value is now in the Clipboard. 3. Select the range of cells you want to convert to numbers. 4. Choose Paste Special from the Edit menu. Excel displays the Paste Special dialog box.

(To display the dialog box in Excel 2007, display the Home tab of the ribbon, click the down-arrow under the Paste tool, and then choose Paste Special.)

ExcelTips 2008 Page 145

Page 159: Excel tips 2008

Formatting Tips

The Paste Special dialog box.

5. Make sure the Multiply radio button is selected. 6. Click on OK.

This works because Excel multiples each cell in the range (step 3) by the value in the Clipboard and then again stores the value in the cell. Since any number multiplied by one is that same number, you effectively force Excel to replace the contents of the cell with the numerical equivalent of the text that was previously there.

If the range you want to convert contains only numbers formatted as text and not any actual text, then the following steps work well:

1. Select the range of cells you want to convert to numbers. 2. Choose Text to Columns from the Data menu. Excel displays the Convert Text to

Columns Wizard. (To start the Wizard in Excel 2007 make sure the Data tab of the ribbon is displayed and then choose Text to Columns in the Data Tools group.)

ExcelTips 2008 Page 146

Page 160: Excel tips 2008

Formatting Tips

The Convert Text to Columns Wizard.

3. Click on Finish.

If you try these three steps on a range of cells that has text containing spaces or tabs, it is possible that you could overwrite data in columns to the right of the selected range. That is why it is safest to use if the range only contains numeric values formatted as text.

HIGHLIGHTING CELLS CONTAINING SPECIFIC TEXT

Applies to Excel 97, 2000, 2002, 2003, and 2007

You can use the conditional formatting feature in Excel to help draw attention to cells that contain specific text in which you are interested. For instance, if you have a range of cells and you want to know which ones contain the letters “shawn,” then you can do the following in versions of Excel prior to Excel 2007:

1. Select the range of cells. 2. Choose Conditional Formatting from the Format menu. Excel displays the Conditional

Formatting dialog box.

ExcelTips 2008 Page 147

Page 161: Excel tips 2008

Formatting Tips

The Conditional Formatting dialog box.

3. In the drop-down Condition list, choose “Formula Is”. 4. In the formula box, enter the following formula. (Make sure you replace A1 with the

cell address of the cell in the upper-left corner of the range selected in step 1.)

=NOT(ISERR(SEARCH("Shaw",A1)))

5. Click on Format. Excel displays the Format Cells dialog box.

The Format Cells dialog box.

6. Using the controls in the dialog box, specify a format that you want used for those cells that contain the specified text. For instance, you may want bold text in a red typeface.

7. Click on OK to close the Format Cells dialog box. 8. Click on OK to close the Conditional Formatting dialog box.

ExcelTips 2008 Page 148

Page 162: Excel tips 2008

Formatting Tips

If you are using Excel 2007 then you should follow these steps, instead:

1. Select the range of cells. 2. With the Home tab of the ribbon displayed, click the Conditional Formatting option in

the Styles group. Excel displays a palette of options related to conditional formatting. 3. Choose Highlight Cells Rules and then choose More Rules from the resulting submenu.

Excel displays the New Formatting Rule dialog box. 4. In the Select a Rule Type area at the top of the dialog box, choose Use a Formula to

Determine Which Cells to Format.

The New Formatting Rule dialog box.

5. In the Format Values Where This Formula Is True box, enter the following formula. (Make sure you replace A1 with the cell address of the cell in the upper-left corner of the range selected in step 1.)

=NOT(ISERR(SEARCH("Shaw",A1)))

6. Click Format to display the Format Cells dialog box. 7. Using the controls in the dialog box, specify a format that you want used for those cells

that contain the specified text. For instance, you may want bold text in a red typeface. 8. Click OK to dismiss the Format Cells dialog box. The formatting you specified in step 7

should now appear in the preview area for the rule. 9. Click OK.

ExcelTips 2008 Page 149

Page 163: Excel tips 2008

Formatting Tips

You can make this approach even more general-purpose in nature by specifying a cell that contains what you want to search for. For instance, if you type “Shaw” in cell F7, then you could replace the formula in step 4 or step 5 with the following:

=NOT(ISERR(SEARCH($F$7,A1)))

Now, you can search for something different just by changing the characters in cell F7.

SETTING CELL WIDTH AND HEIGHT USING THE KEYBOARD

Applies to Excel 97, 2000, 2002, 2003, and 2007

Sawan wonders if there is a way to adjust the height and width of a cell by using the keyboard, without using the mouse. (Some people are really adverse to using the mouse!) The answer is yes, there is a way. The problem, however, is that it isn’t a terribly intuitive way. If you are using a version of Excel prior to Excel 2007, then you can do the following to change the row height:

1. Press ALT+O. Excel displays the Format menu. 2. Press R. Excel chooses the Row option and displays a submenu. 3. Press E. Excel chooses the Height option and displays the Row Height dialog box. 4. Type the value you want for the row height. 5. Press ENTER.

The method for changing the column width is equally obtuse:

1. Press ALT+O. Excel displays the Format menu. 2. Press C. Excel chooses the Column option and displays a submenu. 3. Press W. Excel chooses the Width option and displays the Column Width dialog box. 4. Type the value you want for the column width. 5. Press ENTER.

Of course, in Excel 2007 the menus were done away with and you are left to use a new obtuse key sequence for setting the row height:

1. Press ALT. This kicks Excel into a “shortcut key mode” and you should see the shortcut keys appear above each tab of the ribbon.

2. Press H to indicate you want to use the Home tab. New shortcut keys appear above each tool in the tab.

ExcelTips 2008 Page 150

Page 164: Excel tips 2008

Formatting Tips

3. Press O to indicate you want to use the Format tool in the Cells group. Excel displays a drop-down list of options.

4. Press H to choose the Row Height option. Excel displays the Row Height dialog box. 5. Type the value you want for the row height. 6. Press ENTER.

The only difference in these steps when you want to specify the column width is that you should press W in step 4.

Here’s a different method of changing the row height that will work in any version of Excel:

1. Press SHIFT+SPACEBAR. Excel selects the entire row. 2. Press SHIFT+F10 to display a Context menu. (This is the same menu you see if you

were to right-click on the selection.) 3. Press R to indicate you want to change the row height. Excel displays the Row Height

dialog box. 4. Type the value you want for the row height. 5. Press ENTER.

A similar sequence will work for setting the column width:

1. Press CTRL+SPACEBAR. Excel selects the entire column. 2. Press SHIFT+F10 to display a Context menu. (This is the same menu you see if you

were to right-click on the selection.) 3. Press C twice to choose the second “C” command in the Context menu (Column

Width). 4. Press ENTER. Excel displays the Column Width dialog box. 5. Type the value you want for the column width. 6. Press ENTER.

(Thanks to Steve Aprahamian, Benazir Ibrahim, Toni Powers, Dave Pettit, Abhay Jain, Terry-Anne McPhail, Maria Alaman, Bob Purosky, Erik van der Lee, Bill Foust, Anita Duvall, Glenn Bamford, and Chris Purtill for contributing to this tip.)

ExcelTips 2008 Page 151

Page 165: Excel tips 2008

Formatting Tips

USING FRACTIONAL NUMBER FORMATS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel supports fractional number formats when displaying numbers in a cell. In some industries, fractions are the norm. For instance, the building industry routinely uses fractions to measure lumber and distances. If you format a cell correctly, you can enter a number as 12.25 and have it displayed as 12 1/4.

You can specify a pre-defined fractional number format by following these steps:

1. Select the cell (or cells) you want to format. 2. Choose Cell from the Format menu. Excel displays the Format Cells dialog box. (To

display the dialog box in Excel 2007, display the Home tab of the ribbon, click Format in the Cells group, and then choose Format Cells.)

3. Make sure the Number tab is selected.

The Number tab of the Format Cells dialog box.

ExcelTips 2008 Page 152

Page 166: Excel tips 2008

Formatting Tips

4. In the Category list, at the left side of the dialog box, choose Fraction. 5. In the Type list, at the right side of the dialog box, choose the type of fraction you want

displayed. 6. Click on OK.

Even though you can use the predefined fractional formats, there is a good chance these will not meet all your fractional needs. When you define your own fraction formats, Excel assumes that if you provide digit place holders on both sides of the slash (/), you are defining a fractional format. For instance, if you are working with inches, you can define the following format:

#-#/##\"

This results in numbers such as 18.75 being displayed as 18-3/4". (The backslash indicates that the following character should be used literally as is, in this case the quote mark.) This is exactly what the building contractor may need to convey specifications or other measurements.

When you define fractional formats, make sure you use, as the denominator to the fraction, the maximum number of digits you want to appear there. Since there are two digits in the denominator of the above example, the largest fraction that can be displayed using this format is 98/99. If you want larger denominators, you must format for them explicitly, as in:

#–#/###\"

SELECTING A PAPER SIZE Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel supports any printer supported by Windows. This is because Excel uses the features offered by Windows to print documents. Many of the features associated with formatting your worksheets and printing are related to the type of printer you have installed and selected. For instance, many printers will support different sizes of paper. If your printer does this, and you want to change the paper size used for your worksheet, you should follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose the Page Setup option from the File menu. You will see the Page Setup dialog box.

2. Make sure the Page tab is selected.

ExcelTips 2008 Page 153

Page 167: Excel tips 2008

Formatting Tips

The Page tab of the Page Setup dialog box.

3. Use the Paper Size drop-down list to select the appropriate paper size for your worksheet.

4. Click on OK.

If you are using Excel 2007, follow these steps instead:

1. Make sure the Page Layout tab of the ribbon is displayed. 2. In the Page Setup group, click the Size tool. Excel displays a number of different

common paper sizes. 3. Click the paper size you want to use for your worksheet.

HIDING ROWS BASED ON TWO VALUES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Mike, as an accountant, has a need to hide rows in a worksheet based on the values in two cells in the row. His data tables have three columns, and if a row contains a zero in columns two and three, then the row should be hidden. If either column two or three is blank or contains some other value, then the row should not be hidden.

ExcelTips 2008 Page 154

Page 168: Excel tips 2008

Formatting Tips

There are a couple of ways you can approach this problem. The first is to use Excel’s AutoFilter. Just create another column that contains a formula such as this:

=AND(B2=0,C2=0)

The value returned by the formula will be True only if both the second (B) and third (C) columns contain a zero value. Copy the formula to the other appropriate cells in the column, and you can then use an AutoFilter to filter the data based on that column. When you display only those rows containing a False in the column, then you have effectively hidden the rows in which there is a zero value in columns two and three.

You can also use a macro to check out the rows for you. The following macro steps through each row in the worksheet, beginning with row 1. As long as there is something in column A, then the macro checks to make sure that there is a zero value in columns B and C. If there is, then the .Hidden property for the row is set.

Sub Hide() Dim Criteria as Boolean Dim i As Integer i = 1 Do Until Trim(Cells(i, 1).Value) = "" Criteria = True Criteria = True And (Cells(i, 2).Value = 0) _ And Cells(i, 2).Value <> "" Criteria = True And (Cells(i, 3).Value = 0) _ And Cells(i, 2).Value <> "" If Criteria Then Rows(i).EntireRow.Hidden = True i = i + 1 Loop End Sub

The macro runs until such time as it encounters a row where there is nothing in column A. This means that you need to make sure there is actually something in the rows before your data table. If your data table starts in row 4 of the worksheet, and cells A1 through A3 have nothing in them, then the macro will never run satisfactorily. You can, of course, adjust the macro in this situation so that it starts checking in row 4; simply change the initial assignment of the i variable to 4 instead of 1.

ExcelTips 2008 Page 155

Page 169: Excel tips 2008

Formatting Tips

ADJUSTING CELL MARGINS FOR MORE WHITE SPACE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Serena asked if there is a way to adjust the text margins with a cell so that there is more white space within a cell. The answer is that there is no intrinsic Excel command to add more space, as you can do in Word tables or with the CELLPADDING attribute in an HTML table. However, there is a way you can accomplish the desired goal, although it is somewhat more manual in nature. Follow these general steps:

1. Select the cell you want to adjust. 2. Display the Format Cells dialog box. (In versions of Excel prior to Excel 2007, click the

Cells option from the Format menu. In Excel 2007 display the Home tab of the ribbon and click the small icon at the bottom-right of the Alignment group.)

3. Make sure the Alignment tab is displayed.

The Alignment tab of the Format Cells dialog box.

4. Using the Horizontal drop-down list, choose Center.

ExcelTips 2008 Page 156

Page 170: Excel tips 2008

Formatting Tips

5. Using the Vertical drop-down list, choose Center. 6. Click on OK. 7. Adjust your column width to leave the desired white space on both sides of the cell

contents. 8. Adjust your row height to leave the desired white space above and below the cell

contents.

The drawback to this approach, of course, is that it affects the width of not just one cell, but of the entire column and row. In addition, your numbers will not line up properly—on the decimal point—if you choose to center horizontally. The way around this last issue is to still center the contents horizontally, but use a custom number format for the cells, as follows:

[???,??0.00;-??,??0.00]

The question marks in the format forces Excel to leave space as if there were a digit, even if there isn’t.

You cannot change the vertical white space without adjusting row height. There is, however, one thing you can try if you want to change the horizontal white space: Adjust the indent value used in a cell. All you need to do is display the Format Cells dialog box, and then set the indent on the Alignment tab. If you are using Excel 97 or 2000 you can only adjust the left indent. If you are using a later version of Excel you can adjust either the left or right indent (check out the Horizontal drop-down list), but not both.

USING AUTOFORMAT Applies to Excel 97, 2000, 2002, 2003, and 2007

At times formatting can be rather tedious, particularly if your worksheet is large or presents complex information. Excel includes a very powerful formatting tool that you can use to help with your formatting tasks.. This is the AutoFormat feature, which allows you to format data tables within your worksheet quickly and easily. With the click of a mouse button, you can format an entire table, including setting all formatting attributes and row and column sizes.

To use this feature, simply make sure you select a cell in or around a data table. When you select a cell within the data table, AutoFormat does real good at just selecting the cells that make up the data table. However, if you choose a cell around the data table (within one row or column of the data table), AutoFormat selects the entire data table plus the extra row or column that contains the cell you selected. If you want to format only the data table and no extra rows or columns, you will want to make sure the cell you select is actually within the data table.

Once you have selected a cell (or the entire data table), follow these steps if you are using a version of Excel prior to Excel 2007:

ExcelTips 2008 Page 157

Page 171: Excel tips 2008

Formatting Tips

1. Choose AutoFormat from the Format menu. Excel displays the AutoFormat dialog box.

The AutoFormat dialog box.

2. Scroll through the AutoFormat dialog box and pick the style that looks like you want your data to look.

3. Click on the OK button. Excel reformats your table to match the format you selected.

If you are using Excel 2007 then the step are different. You still need to start by selecting a cell within the data table or the entire data table, but then you should follow these steps:

1. Display the Home tab of the ribbon. 2. In the Styles group, click Format As Table. Excel displays a palette of available table

styles. 3. From the available styles, click on the style that looks like you want your data to look.

Excel displays the Format As Table dialog box. (The range for your table should already be filled in.)

ExcelTips 2008 Page 158

Page 172: Excel tips 2008

Formatting Tips

The Format As Table dialog box.

4. Click OK. Excel reformats your table to match the format you selected.

MAKING ALL OCCURRENCES BOLD

Applies to Excel 97, 2000, 2002, 2003, and 2007

Tom rightly notes that in Word you can use Find and Replace to make all occurrences of a word bold. (Search for the word, replace it with the same word with bold formatting turned on.) He wonders how he can do the same thing in Excel.

The answer depends, in part, on the version of Excel you are using. If you are using Excel 2002 or a later version of Excel, the answer is easy—you do it virtually the same way that you do in Word. Follow these steps:

1. Press CTRL+H to display the Replace tab of the Find and Replace dialog box. 2. Click the Options button to expand the dialog box.

The expanded Replace tab of the Find and Replace dialog box.

ExcelTips 2008 Page 159

Page 173: Excel tips 2008

Formatting Tips

3. In the Find What box, enter the word you want to make bold. 4. Enter the same word in the Replace With box. 5. Click the Format button to the right of the Replace With box. Excel displays the

Replace Format dialog box. 6. Click the Font tab.

The Font tab of the Replace Format dialog box.

7. In the Font Style list, choose Bold. 8. Click OK to close the Replace Font dialog box. 9. Click Replace All to perform the replacements.

While this appears quite easy, you need to remember that these steps change the formatting of entire cells, not just words within a cell. Thus, if you were searching and replacing the word “brown,” then any cell that contained the word “brown” would be made bold—the entire cell, not just the word.

ExcelTips 2008 Page 160

Page 174: Excel tips 2008

Formatting Tips

If you are using an older version of Excel (Excel 97 or Excel 2000) or you want to only affect words within the cell, then these steps won’t work. Instead you’ll need to resort to a macro to do the bolding. Basically, you’ll need a macro that looks through a worksheet and determines what can be changed. (You cannot make individual words or digits in formulas or numeric values bold; you can only make changes to the word-level formatting for text constants.)

Once the macro finds cells it can process, it needs to search through the cells for the desired word, and then make that text bold. The following macro implements this very strategy:

Sub FindAndBold() Dim sFind As String Dim rCell As Range Dim rng As Range Dim lCount As Long Dim iLen As Integer Dim iFind As Integer Dim iStart As Integer On Error Resume Next Set rng = ActiveSheet.UsedRange. _ SpecialCells(xlCellTypeConstants, xlTextValues) On Error GoTo ErrHandler If rng Is Nothing Then MsgBox "There are no cells with text" GoTo ExitHandler End If sFind = InputBox( _ Prompt:="What do you want to BOLD?", _ Title:="Text to Bold") If sFind = "" Then MsgBox "No text was listed" GoTo ExitHandler End If iLen = Len(sFind) lCount = 0 For Each rCell In rng With rCell iFind = InStr(.Value, sFind) Do While iFind > 0 .Characters(iFind, iLen).Font.Bold = True lCount = lCount + 1 iStart = iFind + iLen iFind = InStr(iStart, .Value, sFind) Loop End With Next If lCount = 0 Then MsgBox "There were no occurrences of" & _

ExcelTips 2008 Page 161

Page 175: Excel tips 2008

Formatting Tips

ExcelTips 2008 Page 162

vbCrLf & "' " & sFind & " '" & _ vbCrLf & "to bold." ElseIf lCount = 1 Then MsgBox "One occurrence of" & _ vbCrLf & "' " & sFind & " '" & _ vbCrLf & "was made bold." Else MsgBox lCount & " occurrences of" & _ vbCrLf & "' " & sFind & " '" & _ vbCrLf & "were made bold." End If ExitHandler: Set rCell = Nothing Set rng = Nothing Exit Sub ErrHandler: MsgBox Err.Description Resume ExitHandler End Sub

The macro first sets the search range to those cells that contain text constants. It then prompts the user for a word that needs to be changed. Once entered, the macro then starts looking through all the cells in the range. Each cell is checked to see if it contains the target word. If so, then the .Bold property for those characters is set and the macro continues searching.

The macro also keeps track of how many changes were made, displaying the total changes at the end of its work.

Page 176: Excel tips 2008

Conditional Formatting Tips

COPYING CONDITIONAL FORMATTING

Applies to Excel 97, 2000, 2002, 2003, and 2007

In Excel, conditional formatting is considered part of the regular formatting of a cell. If you want to copy conditional formatting from one cell to another, you can do so by simply copying the cell and pasting it (or its format) to another cell. If you want to copy a conditional format to a range of cells (and only the conditional format), the easiest way to do so is by following these general steps if you are using a version of Excel prior to Excel 2007:

1. Select the range to which you want the conditional format copied. Make sure, however, that the cell whose conditional format you want copied is part of the range.

2. Choose Conditional Format from the Format menu. You will see the Conditional Format dialog box. The format should already be filled in.

3. Click your mouse on OK.

That’s it. Excel does the rest and copies the conditional formatting, as you desired. If you are using Excel 2007 then you’ll want to follow these steps:

1. Select the cell that contains the conditional format you want copied. 2. Display the Home tab of the ribbon. 3. In the Styles section, click Conditional Formatting. Excel displays various options

related to conditional formatting. 4. Click Manage Rules. Excel displays the Conditional Formatting Rules Manager. The

format you want copied should already be filled in.

ExcelTips 2008 Page 163

Page 177: Excel tips 2008

Conditional Formatting Tips

The Conditional Formatting Rules Manger.

5. Select whatever appears in the Applies To box. 6. Using the mouse, click and drag to select the range of cells to which the conditional

format should be applied.

PROTECTING CONDITIONAL FORMATTING

Applies to Excel 97, 2000, 2002, 2003, and 2007

Larry wrote about a problem he was encountering with protecting a worksheet he developed. He has cells that contain both formulas and conditional formatting. He can protect both of them in a worksheet, but if someone selects a cell and copies it to another worksheet, the conditional formatting is visible.

When you copy a protected cell from one sheet to another, if the formulas in the source cell were hidden in the protection process, then the results of the formulas are pasted, unprotected, into the target cells. This is probably no big deal, as you wanted the formulas—not the results—protected.

Excel is not as protective about conditional formats, however. The conditional formats of the cells that you paste, since they are in an unprotected worksheet, can be viewed and modified, as desired. This can be a problem if the conditional formats contain formulas that you want to also keep private.

The only way around this problem is to disable the ability to copy anything from your protected worksheet. You do this through the use of a macro, added to the worksheet object, that would disable copying.

ExcelTips 2008 Page 164

Page 178: Excel tips 2008

Conditional Formatting Tips

Private Sub Worksheet_Deactivate() Application.CutCopyMode = False End Sub

This macro works because anytime the worksheet is deactivated (meaning, the target worksheet is selected), then CutCopyMode is set to False. This results in the “marching ants” that appeared around the source cells when the user pressed CTRL+C being removed, and pasting therefore no longer possible. Copying and pasting on the same worksheet is still fine; just not to a different (unprotected) worksheet.

SORTING OR FILTERING BY CONDITIONAL FORMAT RESULTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

John asked if it is possible to sort or filter based on the conditional formatting in a range of cells. He has a list of values in column A and a list in column B. He created a conditional format that makes any values in column A that are also in column B appear as bold red, and he wanted to sort or filter by that result.

The short answer is that no, you cannot sort by conditional formatting results. Doing so is much more complex than one might think, as shown at this page on Chip Pearson’s Web site:

http://www.cpearson.com/excel/CFColors.htm

The easiest answer is to simply recreate your conditional formula in column C, to the right of your two columns of data. The formula should return True or False, depending on whether the value in column A is found somewhere in column B. With the True/False value in column C, you can filter or sort based on what is there.

APPLYING CONDITIONAL FORMATTING TO MULTIPLE WORKSHEETS

Applies to Excel 2007

Prior to upgrading to Excel 2007, Paula was able to select more than one sheet and apply conditional formatting to a group of cells. But when she selects more than one worksheet in Excel 2007, the conditional formatting option fades. Paula is wondering how she can apply conditional formatting to more than one sheet at a time in a workbook in Excel 2007.

ExcelTips 2008 Page 165

Page 179: Excel tips 2008

Conditional Formatting Tips

Good question, Paula. It seems that Microsoft did make this change as part of their new user interface. Why? I have no idea, but users are stuck with the results of the change—not being able to apply conditional formatting across multiple worksheets at the same time.

We were able to come up with only two workarounds. The first workaround involves copying the conditional formatting from one worksheet to another. Apply the conditional formatting to the first worksheet, then select all those cells to which you applied the formatting. Next, click the Format Painter (on the Home tab of the ribbon), switch to the target worksheet, and select the cells to which the formatting should be applied. That’s it.

The second workaround involves running the macro recorder while setting up the conditional formatting on your first worksheet. You can then re-run the macro as you display each of your other worksheets, in turn. The conditional formats are applied to the same cells on the other worksheets.

(Thanks to Dave Pettit for contributing to this tip.)

CHANGING FONT FACE AND SIZE CONDITIONALLY

Applies to Excel 97, 2000, 2002, 2003, and 2007

Robin asks if there is a way to use Excel’s conditional formatting capabilities to change the font use in a cell or to change the font size in a cell. The short answer is no, that can’t be done—at least not with conditional formatting. (The controls that allow you to specify font name and size are grayed-out in the formatting dialog box used with conditional formatting.)

You can, however, use a macro to examine cell contents and make changes in the appearance of a cell. Consider the following macro, which examines any cells you have selected when you run the macro. If any of the cells have a length of more than two characters or a value of more than 10, then the cell’s font is changed.

Sub DoReformat() Dim rCell As Range For Each rCell In Selection.Cells If Len(rCell.Text) > 2 Or _ Val(rCell.Value) > 10 Then rCell.Font.Name = "Arial" rCell.Font.Size = 16 Else rCell.Font.Name = "Times New Roman" rCell.Font.Size = 12 End If Next End Sub

ExcelTips 2008 Page 166

Page 180: Excel tips 2008

Conditional Formatting Tips

To use the macro, just select the cells you want changed and then run the macro. If you want the formatting to change more automatically, then you can have the macro check to see if a change was made within a certain range of cells:

Private Sub Worksheet_Calculate() Dim rng As Range Dim rCell As Range Set rng = Range("A1:A10") For Each rCell In rng If Len(rCell.Text) > 2 Or _ Val(rCell.Value) > 10 Then rCell.Font.Name = "Arial" rCell.Font.Size = 16 Else rCell.Font.Name = "Times New Roman" rCell.Font.Size = 12 End If Next End Sub

This macro, when added to the worksheet object, will run every time the worksheet is recalculated. It checks the range A1:A10, applying the same tests as in the previous macro. The result is that the formatting of the cells is checked and changed continuously. To have the macro check a different range, just change the addresses assigned to the rng variable near the beginning of the macro.

One drawback of this macro is that it can get sluggish if you have a very large range for it to check. It will go very quickly if you are checking A1:A10 (ten cells), but may go much slower if you are continually checking B2:N465 (over 6,000 cells). In that case, you may want to design the macro so it runs whenever the worksheet is changed, but only takes action if the change was done to a cell in your target range. The following version is also added to the worksheet object:

Private Sub Worksheet_Change(ByVal Target As Range) Dim rCell As Range If Union(Target, Range("A1:A10")).Address = _ Range("A1:A10").Address Then Application.EnableEvents = False For Each rCell In Target If Len(rCell.Text) > 2 Or _ Val(rCell.Value) > 10 Then rCell.Font.Name = "Arial" rCell.Font.Size = 16 Else rCell.Font.Name = "Times New Roman" rCell.Font.Size = 12 End If Next Application.EnableEvents = True

ExcelTips 2008 Page 167

Page 181: Excel tips 2008

Conditional Formatting Tips

End If End Sub

The macro uses the Union function to check whether the cells changed (passed to the event handler in the Target variable) have any overlap with the range you want checked. If they do, then the checking is done on the cells in the Target range.

One thing to keep in mind with macros that affect formatting is that if you have conditional formatting applied to a cell that is also checked by a macro, the formatting in the conditional formatting takes precedence over the formatting in the macro. If your macro is changing font name and font size, this isn’t a big concern because conditional formatting won’t affect these attributes. However, if you change your macro to also change a different format attribute—such as cell color—and that attribute is also changed by the conditional format, then it won’t look like the macro did anything because Excel uses the conditional formatting in preference to what the macro does.

SHADING BASED ON ODDS AND EVENS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a series of values in a range of cells, you might want to use different formatting to differentiate the odd numbers from the even numbers. The way you do this is through the use of the Conditional Formatting feature in Excel. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Select the cells that contain the odd and even values. 2. Choose Conditional Formatting from the Format menu. Excel displays the Conditional

Formatting dialog box.

The Conditional Formatting dialog box.

3. Using the left-most drop-down list, choose Formula Is.

ExcelTips 2008 Page 168

Page 182: Excel tips 2008

Conditional Formatting Tips

4. In the formula area, enter =MOD(A1,2)=1. This formula will return True if the cell contains an odd value.

5. Click on Format and change the format to reflect the formatting you want applied for cells containing odd values.

6. In the Conditional Formatting dialog box, click the Add button. 7. Repeat steps 3 through 5 for the second condition, but use the formula =MOD(A1,2)=0.

This condition returns True if the cell contains an even value. 8. Click on OK to apply the conditional formats to the cells.

If you are using Excel 2007 then you should follow these steps instead:

1. Select the cells that contain the odd and even values. 2. With the Home tab of the ribbon displayed, click the Conditional Formatting option in

the Styles group. Excel displays a palette of options related to conditional formatting. 3. Click Manage Rules. Excel displays the Conditional Formatting Rules Manager dialog

box. 4. Click New Rule. Excel displays the New Formatting Rule dialog box. 5. In the Select a Rule Type area at the top of the dialog box, choose Use a Formula to

Determine Which Cells to Format.

The New Formatting Rule dialog box.

6. In the Format Values Where This Formula Is True box, enter the following: =MOD(A1,2)-1. This formula will return True if the cell contains an odd value.

ExcelTips 2008 Page 169

Page 183: Excel tips 2008

Conditional Formatting Tips

ExcelTips 2008 Page 170

7. Click Format to display the Format Cells dialog box. 8. Using the controls in the dialog box, specify a format that you want used for those cells

that contain an odd value. 9. Click OK to dismiss the Format Cells dialog box. The formatting you specified in step 7

should now appear in the preview area for the rule. 10. Click OK. The New Formatting Rule dialog box disappears and Excel again displays

the Conditional Formatting Rules Manager dialog box. The rule you just defined is listed in the dialog box.

11. Repeat steps 4 through 10 for the second condition, but use the formula =MOD(A1,2)=0. This formula returns True if the cell contains an even value.

12. Click OK. Excel applies the conditional formatting to the cells you selected in step 1.

With this conditional formatting applied, if the cell is odd it will be one color and if even it will be another. If the cell contains text, the cell will be uncolored, meaning it will have the color of the cell before you added the conditional formatting. The conditional formatting overrides any formatting you put on the cell, so even if you try to change the cell color via the toolbar, the conditional formatting takes precedence.

It is interesting to note that if you have the Analysis ToolPak enabled in Excel, you might be tempted to use the ISODD and ISEVEN functions in the conditional format. These functions cannot apparently be used with conditional formatting. If you try to do so, Excel generates an error that says "You may not use references to other worksheets or workbooks for Conditional Formatting criteria." The best bet is to use the MOD function, as described above.

Page 184: Excel tips 2008

Header and Footer Tips

DYNAMIC HEADERS AND FOOTERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a large worksheet, you may want to print it out in “parts” and automatically vary the information contained in the header or footer of each part. There is no intrinsic way to do this in Excel; the best approach is a macro to do the following:

1. Set the print area based on a named range. 2. Set the header or footer based on another named range. 3. Print the print area. 4. Repeat steps 1 through 3 for each desired print area.

Notice that these steps require the use of named ranges. You could have a named range for each portion of the worksheet that you want to print, and a named range (which would be a single cell) that represents the header or footer information that you want for each print area. The following macro will implement the above steps:

Sub PrintRegions() Dim x As Integer 'Change the dimension of the arrays to equal the number ' of printing areas you have Dim Region(4) As String Dim Head(4) As String 'Fill this array with the names of the ranges to be printed Region(1) = "North" Region(2) = "South" Region(3) = "East" Region(4) = "West" 'Fill this array with the names of the ranges to be in the header Head(1) = "NorthHead" Head(2) = "SouthHead" Head(3) = "EastHead"

ExcelTips 2008 Page 171

Page 185: Excel tips 2008

Header and Footer Tips

Head(4) = "WestHead" For x = 1 To UBound(Region) ActiveSheet.PageSetup.PrintArea = Range(Region(x)).Address ActiveSheet.PageSetup.LeftHeader = Range(Head(x)).Value ActiveWindow.SelectedSheets.PrintOut Copies:=1 Next End Sub

This example prints out only four areas of a worksheet. These areas are named ranges: North, South, East, and West. Similarly, the named ranges—which are really single cells—used for the left portion of the headers are NorthHead, SouthHead, EastHead, and WestHead.

USING A DIFFERENT FOOTER ON SECONDARY PAGES

Applies to Excel 97, 2000, 2002, 2003, and 2007

When creating a worksheet that will eventually be printed, you may want to use a different footer on the first page of your document than you do on the subsequent pages. There is no way to do this directly in Excel. There are a couple of workarounds you could use, however.

First of all, try using the Report Manager add-in for Excel. This add-in allows you to define different views and select the order in which those views are printed. Each view can also have its unique headers and footers, which means you could set up a view of the first page—with the footer desired—and a view of the subsequent pages with their own headers and footers. You would then print the report using the Report Manager, resulting in the desired output.

You should note that the Report Manager add-in was last distributed with Excel 2002. If you are using Excel 2003 or Excel 2007, you can still use the Report Manager. This Knowledge Base article explains how you can use it:

http://support.microsoft.com/?kbid=873209

Another workaround is to use a macro to do your printing. The following macro will set the footers for a worksheet depending on what is being printed. Actually, it sets the footers for the first page, and then prints that page. Then it sets the footers for the other pages, and prints them.

Sub PrintSheet() Dim sP1Left As String Dim sP1Center As String Dim sP1Right As String Dim sP2Left As String Dim sP2Center As String Dim sP2Right As String

ExcelTips 2008 Page 172

Page 186: Excel tips 2008

Header and Footer Tips

' Define first-page footers sP1Left = "First page left" sP1Center = "First page center" sP1Right = "First page right" ' Define second-page footers sP2Left = "Second page left" sP2Center = "Second page center" sP2Right = "Second page right" ' Set up and print first page With ActiveSheet.PageSetup .LeftFooter = sP1Left .CenterFooter = sP1Center .RightFooter = sP1Right End With ActiveSheet.PrintOut 1, 1 ' Set up and print other pages With ActiveSheet.PageSetup .LeftFooter = sP2Left .CenterFooter = sP2Center .RightFooter = sP2Right End With ActiveSheet.PrintOut 2 End Sub

To use the macro, all you need to do is change the footer definitions. Change the variable values in the “Define first-page footers” area and the “Define second-page footers” area in order to get just the output you want.

PUTTING A DIFFERENT DATE IN A HEADER

Applies to Excel 97, 2000, 2002, 2003, and 2007

Adding the current date to the header of a worksheet is easy—Excel provides a dialog box where you can specify the placement of the date and use the ‘&[date]’ coding to actually insert the date. But what if you want to insert yesterday’s date or tomorrow’s date into the header?

That’s not nearly as easy. In fact, you can’t do it without using a macro. Perhaps the most flexible approach is to write the macro so that it updates the date just before the worksheet is printed, as shown in the following:

Private Sub Workbook_BeforePrint(Cancel As Boolean) ActiveSheet.PageSetup.CenterHeader = _

ExcelTips 2008 Page 173

Page 187: Excel tips 2008

Header and Footer Tips

Format(Date - 1, "mmmm d, yyyy") End Sub

The macro places yesterday’s date into the center of the header; you can easily change the CenterHeader property of one of the other available header locations (LeftHeader or RightHeader). You can also change the macro to insert tomorrow’s date by changing the “- 1” to “+ 1”.

(Thanks to Steve Aprahamian, Andrija Vrcan, Bill Barry, Richard Raciborski, Dennis Swearingen, Russell Hendel, and Matthew Murphy for contributing to this tip.)

PRINTING A MULTI-LINE FOOTER Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to create headers and footers that you can use with your workbooks. If you want, you can create a multi-line header or footer, as desired. The trick is to remember that you cannot press ENTER while typing your footer. Instead, to start a new line you should hold down the ALT key as you type 0010 on the numeric keypad. This inserts a line-break character in the footer text.

Another thing to remember when doing footers in this way is that you will need to increase the bottom margin on your page setup. If you fail to increase it sufficiently, your footer may “overprint” the data in your worksheet, or vice-versa.

Finally, you must keep in mind that Excel places a limit on the length of your headers and footers. The total length of a header or footer cannot exceed 255 characters. If you need to create a header or footer that contains more characters, you will need to create them differently, without explicitly doing so as a header or footer.

USING COLOR IN HEADERS AND FOOTERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When creating headers and footers for your worksheets, you can modify many attributes used by Excel. When you design a custom header or footer you can click the A tool in the Header or Footer dialog box to select a font or to change other attributes of the font (size, style, etc.).

If you are using Excel 97 through Excel 2003, one thing you cannot change is the color used for the text. Early versions of Excel allowed you to modify header and footer colors, but the

ExcelTips 2008 Page 174

Page 188: Excel tips 2008

Header and Footer Tips

capability was removed beginning in Excel 4.0. It was only in Excel 2007 that the capability was again added to the program.

If you can’t change the color, the only thing you can do is try a workaround. If you are using Excel 97 or Excel 2000, you can simply create your “header” in the first row of your worksheet, and then repeat that row at the top of each printed page. (There is no way to repeat a row at the bottom of a page, so you’d be out of luck for color footers.)

If you are using Excel 2002 or Excel 2003, you can create a color graphic, and then place that graphic into the header or footer. This is often done when you need color in logos and other graphic elements, and you need them to repeat on multiple pages.

ADDING AMPERSANDS IN HEADERS AND FOOTERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

The ampersand character (&) is commonly used in company names (such as Burns & Foster, Inc.) or in standard business phrases (such as Mergers & Acquisitions). If you are creating a report in Excel, you may notice that the ampersand characters don’t show up properly if you add them to headers or footers for your worksheet.

The reason ampersands don’t show up is because the character is used as a “marker” that indicates a special formatting code is to follow. If you want to actually use an ampersand, then you need to double it—use two ampersands, such as “Burns && Foster, Inc.” Even though you enter two ampersands in the header or footer, Excel only displays one ampersand in the resulting header or footer.

LEADING ZEROS IN PAGE NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jackie asked if there was a way to include leading zeroes in the page numbers placed in a footer. She needs her page numbers to always be five characters long, with leading zeroes, as necessary, to fill out the length. Thus, page numbers would be 00001, 00002, etc.

Excel doesn’t provide very good formatting for its page numbers. One solution (perhaps the most viable) is to print each page in your worksheet, one at a time, changing the page number as you go. This macro takes that approach:

ExcelTips 2008 Page 175

Page 189: Excel tips 2008

Header and Footer Tips

Sub FormattedPageNums() Dim iPages As Integer Dim J As Integer Dim sFormat As String sFormat = "00000" ' Get count of pages in active sheet iPages = ExecuteExcel4Macro("Get.Document(50)") With ActiveSheet For J = 1 To iPages .PageSetup.CenterFooter = Format(J, sFormat) .PrintOut From:=J, To:=J Next J End With End Sub

The macro discovers how many pages are in the entire printout, and then steps through each page of that printout. Prior to printing each page, individually, the .CenterFooter property is set equal to a formatted string that represents the page number with leading zeros.

You can modify the macro, as desired, to place different information in the footer. You could also change the area of the footer that is changed by using .LeftFooter or .RightFooter instead of .CenterFooter.

HEADER AND FOOTER BACKGROUND COLOR

Applies to Excel 97, 2000, 2002, 2003, and 2007

Leonid asked if there was a way to set a background color for the header or footer of a page. The simple answer is that there isn’t such a capability in Excel. There are a couple of ways around the issue, however. For instance, if you are using Excel 2002 (or a later version) you can add a graphic to a header or footer. With the right graphic, you can make it appear that the header and footer contain color when, in fact, it is the graphic that contains the color.

Another option is to make “fake” headers and footers. If all you want to do is have a different color header, then you can use the first couple of rows of the worksheet as your header. These rows you could format as desired, including setting the color of the rows. You could then instruct Excel to repeat those rows at the top of every page of the printout (us the Page Setup dialog box for this).

Repeating rows for the footer area becomes more problematic, as Excel doesn’t include a feature that allows you to repeat rows at the bottom of each page. Creating a macro to add rows for the header and footer is possible, but it does result in a change to your worksheet—rows need to be added for the fake headers and footers.

ExcelTips 2008 Page 176

Page 190: Excel tips 2008

Header and Footer Tips

As an example, consider the following macro. It assumes that you want one-inch borders on the left and right of the printout, and that you want to print only 46 rows per page. It sets the margins and then steps through the worksheet, adding the fake header and footer rows, as necessary. (Because the macro adjusts the design of the worksheet, make sure you save your worksheet before running the macro.)

Sub FakeHeaderFooter() Dim LHeader As String Dim CHeader As String Dim LFooter As String Dim CFooter As String Dim CBottom As Integer Dim CRow As Integer Dim PageSize As Integer LHeader = "Top Left" CHeader = "Top Center" LFooter = "Bottom Left" CFooter = "Bottom Center" PageSize = 46 With ActiveSheet.PageSetup .PrintTitleRows = "" .PrintTitleColumns = "" .PrintArea = "" .LeftHeader = "" .CenterHeader = "" .RightHeader = "" .LeftFooter = "" .CenterFooter = "" .RightFooter = "" .LeftMargin = Application.InchesToPoints(1) .RightMargin = Application.InchesToPoints(1) .TopMargin = Application.InchesToPoints(0) .BottomMargin = Application.InchesToPoints(0) .HeaderMargin = Application.InchesToPoints(0) .FooterMargin = Application.InchesToPoints(0) .PrintHeadings = False .Orientation = xlPortrait End With CBottom = Range("A16000").End(xlUp).Row CRow = 1 Do Until CRow > CBottom If CRow Mod PageSize = 1 Then Rows(CRow).Select Selection.Insert Shift:=xlDown Selection.Insert Shift:=xlDown CBottom = CBottom + 2 Cells(CRow, 1).Value = LHeader

ExcelTips 2008 Page 177

Page 191: Excel tips 2008

Header and Footer Tips

ExcelTips 2008 Page 178

Cells(CRow, 4).Value = CHeader Range(Cells(CRow, 1), _ Cells(CRow, 8)).Interior.ColorIndex = 34 Range(Cells(CRow + 1, 1), _ Cells(CRow + 1, 8)).Interior.ColorIndex = xlNone CRow = CRow + 2 ElseIf CRow Mod PageSize = PageSize - 1 Then Rows(CRow).Select Selection.Insert Shift:=xlDown Selection.Insert Shift:=xlDown CBottom = CBottom + 2 Cells(CRow + 1, 1).Value = LFooter Cells(CRow + 1, 4).Value = CFooter Range(Cells(CRow + 1, 1), _ Cells(CRow + 1, 8)).Interior.ColorIndex = 34 CRow = CRow + 2 Else CRow = CRow + 1 End If Loop LastPageNumber = PageNumber + 1 LastRow = LastPageNumber * PageSize If CBottom <> LastRow Then Range(Cells(LastRow, 1), _ Cells(LastRow, 8)).Interior.ColorIndex = 34 Cells(LastRow, 1).Value = LFooter Cells(LastRow, 4).Value = CFooter End If CBottom = Range("A16000").End(xlUp).Row CRow = 2 Do Until CRow > CBottom If CRow Mod PageSize = 1 Then Cells(CRow, 1).PageBreak = xlManual End If CRow = CRow + 1 Loop End Sub

To change the number of lines per page, just change the value assigned to the PageSize variable. You can also change what appears in the “header” and “footer” area by changing what is assigned to the LHeader, CHeader, LFooter, and CFooter variables.

Page 192: Excel tips 2008

Online Tips

TURNING OFF HYPERLINK ACTIVATION

Applies to Excel 2000, 2002, 2003, and 2007

When you enter a Web address or a LAN server address of a file into an Excel cell, it automatically converts to a hyperlink when you leave the cell. This is part of the “Web-aware behavior” of Excel, first introduced in Excel 2000.

If you want to turn off the automatic conversion, you can follow these steps if you are using Excel 2007:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Proofing at the left of the dialog box. 3. Click the AutoCorrect Options button. Excel displays the AutoCorrect dialog box. 4. Make sure the AutoFormat As You Type tab is selected.

ExcelTips 2008 Page 179

Page 193: Excel tips 2008

Online Tips

The AutoFormat As You Type tab of the AutoCorrect dialog box.

5. Clear the Internet and Network Paths With Hyperlinks check box. 6. Click OK.

The steps to follow are different if you are using Excel 2002 or Excel 2003:

1. Choose AutoCorrect Functions from the Tools menu. Excel displays the AutoCorrect dialog box.

2. Make sure the AutoFormat As You Type tab is selected. 3. Clear the Internet and Network Paths With Hyperlinks check box. 4. Click OK.

If you are using Excel 2000, your options are severely limited—Excel doesn’t allow you to turn off the conversions. All you can do is press CTRL+Z after the hyperlink is created, or preface your entry with an apostrophe so that Excel treats it as text. You can also create an application-level event handler—which is beyond the scope of ExcelTips—as described in the Microsoft Knowledge Base, article 233073:

http://support.microsoft.com/?kbid=233073

ExcelTips 2008 Page 180

Page 194: Excel tips 2008

Online Tips

TYING A HYPERLINK TO A SPECIFIC CELL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Manoj created a hyperlink between two worksheets by using copy and paste hyperlink command (the hyperlink targets a specific cell). Later he inserted some rows on the target worksheet that caused the target cell to move down a bit. Even though the target cell moves down, the hyperlink continues to reference the old cell location. Manoj is wondering if there is a way to make sure that the hyperlink always targets the cell he intended when creating the link.

In Excel, hyperlink addresses are essentially text that references a cell. Formulas in Excel link to cell references which adjust when changes in the worksheet structure are made (inserting and deleting rows and columns, etc.). Hyperlink addresses, being text instead of cell references, will not adjust with such changes.

The solution is to create a named range that refers to the target cell you want used in the hyperlink. (You do this by choosing Insert | Name | Define or, in Excel 2007, display the Formulas tab of the ribbon and then click on Define Name in the Defined Names group.) When you create your hyperlink, you can then reference this named range in the Insert Hyperlink dialog box.

The Insert Hyperlink dialog box.

At the left of the dialog box, click Place In This Document. You’ll then see a list of named ranges in your workbook and you can choose which one you want to be associated with this hyperlink. In this way, you allow Excel to take care of translating between the name and the address for that name, which means that the hyperlink will always point to the cell you want it to point to.

ExcelTips 2008 Page 181

Page 195: Excel tips 2008

Online Tips

(Thanks to Andrija Vrcan, Steve Aprahamian, Richard D’Angelo, Charlie O’Neill, Benazir Ibrahim, Tore Softing, and Duncan Salmon for contributing to this tip.)

DROP-DOWN LIST OF HYPERLINKS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Greg knows that he can use data validation to create a drop-down list of choices for a particular cell. (How to do this has been covered in other ExcelTips.) He wonders if it possible to create a drop-down list of hyperlinks and, further, have those hyperlinks remain "hot" when they are selected.

The short answer is no, you can’t do that directly. You can, however, make whatever you select in the drop-down list become active. This behavior is a bit kludgy in Excel, however. Follow these general steps:

1. Select a URL from your drop-down list. (The list created using data validation.) The URL now appears in the cell.

2. Double-click the URL that appears in the cell. Excel lets you start to edit the hyperlink. 3. Press ENTER. The URL now becomes active (“hot”). 4. Click the URL one more time to follow to that link.

As you can tell, these steps are a bit awkward, and they become more so if you want to select a different URL from the drop-down list. (You must first right-click and remove the hyperlink and then do the above steps again.)

Perhaps a better solution is to use a workaround that relies on the HYPERLINK function to refer to whatever is selected in the drop-down list. For instance, if you have your data validation drop-down list in cell A1, then you might put the following formula in cell B1:

=HYPERLINK(A1, "Goto Link")

The second parameter in the function is optional; it provides the text you want displayed in the cell. (If you don’t provide the second parameter, then the contents of A1 are repeated in B1—something you may not want to see.) When someone picks an option in the drop-down list, the link in cell B1 becomes active and will link to whatever was selected in A1.

(Thanks to Steve Aprahamian, Andrija Vrcan, Richard Raciborski, Tim Cantley, Rick Taylor, Russell Hendel, and Dave Pettit for contributing to this tip.)

ExcelTips 2008 Page 182

Page 196: Excel tips 2008

Online Tips

CHANGING PORTIONS OF MANY HYPERLINKS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Kerstine has a worksheet with many, many different hyperlinks in it. She is wondering if there is a way she can replace just a part of each link. For instance, she might like to change any instance of http://www.mysite.com/ to c:/documents/mycopy/. If there is anything additional in the links, then that part should remain. So, for instance, if the original link is http://www.mysite.com/thispage.html, it would be changed to c:/documents/mycopy/thispage.html.

This can be easily done with a macro. The reason is because the hyperlinks can be examined and changed using regular string functions. The following macro provides a simple way to address the issue.

Sub EditHyperlinks() Dim lnkH As Hyperlink Dim sOld As String Dim sNew As String sOld = "http://www.mysite.com" sNew = "c:/documents/mycopy/" For Eack lnkH In ActiveSheet.Hyperlinks lnkH.Address = Replace(lnkH.Address, sOld, sNew) lnkH.TextToDisplay = Replace(lnkH.TextToDisplay, sOld, sNew) Next End Sub

This routine steps through all the hyperlinks in the current worksheet and makes modifications, if necessary, to each one. Both the hyperlink and the displayed text are changed, as appropriate. All you need to do is make changes to the sOld and sNew strings to specify what you are searching for and what you want to replace it with.

You should note that this macro uses the Replace function, which is built into the later versions of VBA. If you are using an older version that does not include the Replace function (you’ll know because you’ll get an error when you try to turn the macro) then you will need to create your own Replace function that replaces one portion of a string with another. Such functions have been covered in other issues of ExcelTips.

(Thanks to Tieying Zhang, Steve Aprahamian, Marc Schroven, Anthony Vanderplaats, Richard Raciborski, Chris Purtill, John Pomfret, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 183

Page 197: Excel tips 2008

Online Tips

REMOVING HYPERLINKS WITHOUT A MACRO

Applies to Excel 97, 2000, 2002, 2003, and 2007

Other issues of ExcelTips have featured macros that remove all the hyperlinks in a worksheet. If you have too few hyperlinks to justify the use of a macro (or you just don’t like to deal with macros), you may be interested in an easy way to delete hyperlinks without using macros:

1. Use the arrow keys to select the cell containing the first hyperlink. 2. Press CTRL+K. Excel displays the Edit Hyperlink dialog box.

The Edit Hyperlink dialog box.

3. Click Remove Link. The dialog box disappears and the hyperlink is removed. 4. Use the arrow keys to select the cell with the next hyperlink. 5. Press F4. The hyperlink disappears. 6. Repeat steps 4 and 5 to remove any other hyperlinks you want removed.

ExcelTips 2008 Page 184

Page 198: Excel tips 2008

Online Tips

REMOVING HYPERLINKS WITHOUT A MACRO

Applies to Excel 97, 2000, 2002, 2003, and 2007

Looking for a quick, easy way to remove hyperlinks without a macro? Believe it or not, you can accomplish this by using the Paste Special features of Excel. Follow these steps:

1. In a blank cell, enter the number 1. 2. Select the cell and press CTRL+C. The cell content (1) is now copied to the Clipboard. 3. Hold down the CTRL key as you click each hyperlink you want to remove. 4. Display the Paste Special dialog box. (In versions of Excel before Excel 2007 choose

Edit | Paste Special. In Excel 2007 display the Home tab of the ribbon, click the down-arrow under the Paste tool at the left of the ribbon, and then choose Paste Special.)

The Paste Special dialog box.

5. Select the Multiply radio button. 6. Click OK. All the hyperlinks are removed, but the text of the hyperlinks remain. 7. Delete the cell you created in step 1.

ExcelTips 2008 Page 185

Page 199: Excel tips 2008

Online Tips

GETTING RID OF MANY HYPERLINKS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Do you create worksheets by pasting information that was copied from the Internet? This is not unusual for some people, as there is quite a bit of public-domain information that can be copied from the Internet. When you paste your information into a worksheet, you may notice that there are quite a few hyperlinks. What if you want to get rid of those hyperlinks? Similarly, you might inherit a worksheet from someone, and it contains a lot of hyperlinks you want deleted.

The easiest approach is to run a macro that deletes all the hyperlinks. The following macro quickly removes all hyperlinks in a document, without affecting anything else in the worksheet:

Sub KillLinks() Do Until ActiveSheet.Hyperlinks.Count = 0 ActiveSheet.Hyperlinks(1).Delete Loop End Sub

GETTING RID OF ALL HYPERLINKS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you inherit worksheets from other people, you may find that some worksheets contain many, many hyperlinks. These hyperlinks are often automatically created by Excel as you import or enter information in the worksheet.

If you want to delete these hyperlinks, you can do so by right-clicking on them and choosing Hyperlink | Remove Hyperlink from the Context menu. Doing this with dozens or hundreds of hyperlinks can quickly consume a huge amount of time.

To delete all the hyperlinks in the active worksheet at the same time, you can use a handy one-line macro:

Sub DeleteHyper() ActiveSheet.Hyperlinks.Delete End Sub

Select the worksheet you want to affect, run the macro, and you just saved yourself tons of time!

ExcelTips 2008 Page 186

Page 200: Excel tips 2008

Online Tips

AUTOMATIC TEXT IN AN E-MAIL Applies to Excel 97, 2000, 2002, 2003, and 2007

Laura has an e-mail address that is a hyperlink in Excel. She edited the hyperlink so that the e-mail created when the link is clicked has a subject line. She wants to be able to have the e-mail automatically contain text, as well.

There is a way to do this rather easily in Excel. To see the way to do it, put the address of the e-mail recipient in A1, the desired message subject in A2, and the desired message body text in A3. Then, in a different cell, use this formula:

=HYPERLINK("mailto:" & A1 & "?subject=" & A2 & "&body=" & A3, "Linking text")

This results in a hyperlink that users can click and have both the subject and body filled in. The downside to this is that your message body can’t be terribly long. The total length permissible for any hyperlink is 255 characters, including the words such as “mailto,” “subject,” and “body.” Thus, if the length of the address in cell A1 is 16 characters, the length of the subject in cell A2 is 25 characters, and the “overhead” (“mailto,” “subject,” etc.) take 22, then that means your message in cell A3 cannot be over 192 characters. (That’s a relatively short message.)

You can also create the appropriate hyperlink using the Insert Hyperlink dialog box. Follow these steps:

1. Display the Insert Hyperlink dialog box. (Choose Insert | Hyperlink or, in Excel 2007, display the Insert tab of the ribbon and click the Hyperlink tool.)

2. Make sure the E-mail Address option is chosen in the Link To area.

The Insert Hyperlink dialog box.

ExcelTips 2008 Page 187

Page 201: Excel tips 2008

Online Tips

3. In the Text to Display field, enter the text you want to appear in the worksheet. 4. In the E-mail Address field, enter the address to be used in the link. 5. In the Subject field, enter the text you want used for the subject line. 6. Immediately after the subject text (in the Subject field), type an ampersand and the

word “body” followed by an equal sign (as in “&body=” without the quote marks). 7. Continue typing your desired body text, after the equal sign. 8. Click on OK.

You should note that this approach will work for most mail clients. If it doesn’t work for yours, then try replacing the spaces in the subject and the body with the characters %20.

(Thanks to Scott Huish, Martin Maes, Maarten Daams, Hafizullah Chishti, Steve Aprahamian, Andrija Vrcan, Attila Molnar, Richard Raciborski, Yngve Aneglskar, Richard Smolik, Eric Klokman, Robert DaVia, Henric Bladh, Russell Hendel, and David Gray for contributing to this tip.)

LINKING TO A SPECIFIC PAGE IN A PDF FILE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Gary wants to link from an Excel worksheet to a specific page in a PDF file. He can get Excel to link to the PDF but it starts on the first page of the PDF, not the page he wants. Gary believes that Excel is ignoring the PDF command that tells it the page he wants. As an example, he can use the formula =HYPERLINK("E:\\test\gary.pdf#5") and Excel ignores the #5 part and opens to the first page of the PDF.

This does, indeed, seem to be the case, Gary. The HYPERLINK worksheet function seems to ignore the page specification for some strange reason. There also doesn’t seem to be a way around this problem with the function.

Fortunately, you can use a macro to do the opening, if you desire. The following macro relies upon Internet Explorer to open the PDF and display the proper page:

Sub OpenPDFpage() Dim myLink As String Dim TargetPage As Double Dim objIE As New InternetExplorer myLink = "path/filename.pdf" TargetPage = 7 'Page number to be shown With objIE .Navigate myLink & "#page=" & TargetPage .Visible = True

ExcelTips 2008 Page 188

Page 202: Excel tips 2008

Online Tips

End With End Sub

The code could also be rather easily changed to a function to which you can pass the desired path and target page.

(Thanks to Richard Raciborski for contributing to this tip.)

SETTING WEB FONTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Starting with Excel 2000, Microsoft provided ways for you to have your Excel data available on the Web. You do this by saving your worksheet data in a Web-page format. You can specify which fonts you want Excel to use when it creates Web pages from the information in a workbook. You can set the default fonts that Excel uses by following these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the General tab is selected.

The General tab of the Options dialog box.

ExcelTips 2008 Page 189

Page 203: Excel tips 2008

Online Tips

3. Click on the Web Options button. Excel displays the Web Options dialog box. 4. Make sure the Fonts tab is selected.

The Fonts tab of the Web Options dialog box.

5. Using the Proportional Font drop-down list, select the font you want used as a default for your Web pages.

6. Using the Fixed-width Font drop-down list, select the font you want used when displaying monospace information on your Web pages.

7. Using the Size controls, specify the respective default sizes for the fonts. 8. Click on OK to close the Web Options dialog box. 9. Click on OK to close the Options dialog box.

If you are using Excel 2007, then you need to follow these steps, instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Advanced. 3. Scroll through the available options until you see the General section.

ExcelTips 2008 Page 190

Page 204: Excel tips 2008

Online Tips

The Advanced options of the Excel Options dialog box.

4. Click on the Web Options button. Excel displays the Web Options dialog box. 5. Make sure the Fonts tab is selected.

ExcelTips 2008 Page 191

Page 205: Excel tips 2008

Online Tips

The Fonts tab of the Web Options dialog box.

6. Using the Proportional Font drop-down list, select the font you want used as a default for your Web pages.

7. Using the Fixed-width Font drop-down list, select the font you want used when displaying monospace information on your Web pages.

8. Using the Size controls, specify the respective default sizes for the fonts. 9. Click on OK to close the Web Options dialog box. 10. Click on OK to close the Excel Options dialog box.

SPECIFYING YOUR TARGET MONITOR

Applies to Excel 2000, 2002, 2003, and 2007

If you are developing Web pages in Excel, it is a good idea to have in mind who the user is. The user, obviously, is the person who will view your Web page. However, there are certain assumptions that must be made about the user, and those assumptions will affect how you put your Web page together.

One of the prime considerations is what resolution of monitor the user will be using. This affects the presentation of graphics and text on their page. For instance, a graphic that shows up nicely

ExcelTips 2008 Page 192

Page 206: Excel tips 2008

Online Tips

centered on your screen at a high resolution may not give the desired impact if the user is working at a lower resolution.

You can instruct Excel to make certain assumptions about the user’s monitor resolution as you are developing Web pages. You set the target resolution by following these steps in versions of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the General tab is selected.

The General tab of the Options dialog box.

3. Click on the Web Options button. Excel displays the Web Options dialog box. 4. Make sure the Pictures tab is selected.

ExcelTips 2008 Page 193

Page 207: Excel tips 2008

Online Tips

The Pictures tab of the Web Options dialog box.

5. Using the Screen Size drop-down list, select the screen resolution you believe most of your users will have.

6. Click on OK to close the Web Options dialog box. 7. Click on OK to close the Options dialog box.

If you are using Excel 2007 then you can set the target monitor by following these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left side of the dialog box. 3. Scroll through the list of available options until you see the General group. 4. Click the Web Options button. Excel displays the Web Options dialog box. 5. Make sure the Pictures tab is selected. 6. Using the Screen Size drop-down list, select the screen resolution you believe most of

your users will have. 7. Click on OK to close the Web Options dialog box. 8. Click on OK to close the Excel Options dialog box.

ExcelTips 2008 Page 194

Page 208: Excel tips 2008

Worksheet Tips

VIEWING TWO WORKSHEETS AT ONCE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Dan asked if it is possible to see two Excel worksheets on the screen at the same time. Yes, you can do this, using the same general technique that you use to view multiple worksheets from different workbooks. Follow these steps:

1. Make sure you have only a single workbook open. 2. Choose New Window from the Window menu. (In Excel 2007 display the View tab of

the ribbon and click New Window in the Window group.) Excel opens a second instance of the same workbook.

3. Choose Arrange from the Window menu. Excel displays the Arrange Windows dialog box. (To display this dialog box in Excel 2007 display the View tab of the ribbon and click Arrange All in the Window group.)

The Arrange Windows dialog box.

4. Choose the method Excel should use to arrange your windows. 5. Click on OK. Excel arranges the windows as you directed.

In each of the windows you can display different worksheets, even though they are part of the same workbook. When you are done, simply close one of the windows.

ExcelTips 2008 Page 195

Page 209: Excel tips 2008

Worksheet Tips

It is interesting to note that if you have a need to do so, you can view more than two worksheets from the same workbook. All you need to do is perform step 2 as many times as necessary to open the desired number of windows.

REFERENCING WORKSHEET TABS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Myrna asked if there was a way to use the information in a worksheet tab within a cell. In particular, she named her tabs using dates, and wants to use those dates within the worksheet itself.

There are two ways to go about this. If the names of your worksheet tabs consist only of dates (no other text in them), then you can use the following Excel formula to extract the date:

=MID(CELL("filename"),FIND("]",CELL("filename"),1)+1,10)

This works because =CELL("filename") function returns the complete path and name of the current file along with the text on the worksheet tab. The filename itself appears in square brackets. The formula finds the position of the closing bracket and extracts the first eight characters from that position to the end. (Dates can be expressed in a maximum of 10 characters, as in 10-22-2005.)

One caveat with using this formula is that it only returns anything of value if you first save the workbook. If you use it in a brand new, unsaved workbook, it will return a #VALUE error.

Another approach that is very appealing, particularly if you have additional text in the worksheet tab, is to create a user-defined function. For instance, let’s assume that your worksheet tabs have the name “Month Ending 5-31-05”. In this case, you could use a function such as the following:

Function SheetName() As Date Dim sTab As String Application.Volatile sTab = ActiveSheet.Name sTab = Trim(Right(sTab, 8)) SheetName = CDate(sTab) End Function

To use this function in your worksheet, you simply enter the following in a cell:

=SheetName()

ExcelTips 2008 Page 196

Page 210: Excel tips 2008

Worksheet Tips

The function returns a date serial number, so you will need to format the cell using one of the available date formats. The function works because it assumes that the date is the last 8 characters of the text in the worksheet tab. If your worksheet tabs use a different naming convention (such as placing the date at the beginning of the tab or using 10 digits for the date), then all you need to do is pull the name apart differently in the macro.

QUICKLY COPYING WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you need to make a copy of a worksheet, you probably already know that you can use the Move or Copy Sheet option from the Edit menu. (In Excel 2007 the option is available when you display the Home tab of the ribbon and click the Format tool in the Cells group.) There is a quicker way to make a copy, however. All you need to do is follow these steps:

1. Select the tab of the worksheet that you want to copy. 2. Hold down the CTRL key and use the mouse to drag the worksheet tab left or right. A

small plus sign should appear next to the mouse pointer. 3. Release the mouse button when the pointer is between the tabs where you want the

worksheet copy to appear.

That’s it! Excel makes an exact copy of the worksheet, depositing it at the point where you released the mouse button.

DISABLING MOVING BETWEEN WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel provides a variety of ways that you can move from one worksheet to another in a workbook. If you want to disable moving between worksheets, you’ve got a difficult task in front of you because of the variety of methods you need to do something about.

For instance, one way to move between worksheets is to press CTRL+PAGE UP or CTRL+PAGE DOWN. To disable these keys for a particular workbook, you need to use the OnKey method, in the following manner:

Private Sub Workbook_Activate() Application.OnKey "^{PgDn}", ""

ExcelTips 2008 Page 197

Page 211: Excel tips 2008

Worksheet Tips

Application.OnKey "^{PgUp}", "" End Sub

Private Sub Workbook_Deactivate() Application.OnKey "^{PgDn}" Application.OnKey "^{PgUp}" End Sub

These two macros should be placed in the ThisWorkbook object. The first is run whenever the workbook is activated and it disables CTRL+PAGE UP and CTRL+PAGE DOWN by having nothing run when they are pressed. The second macro is run when the workbook is deactivated, and re-enables the keys.

There are still a number of other ways to switch between worksheets, such as manually selecting the sheet, using Go To, using hyperlinks, etc. The easiest way to prevent moving between worksheets is to hide the worksheets you don’t want accessed. Protecting the workbook and protecting the VB project will also aid in "thwarting" the user from moving between sheets.

If the sheets are hidden, they cannot be selected and thus you cannot move to them. Go To will not go to them, hyperlinks will not go to them. If you want users to be able to view the hidden worksheets later, you must create a macro routine with your own controls/buttons to go to those sheets. This routine would "unhide" the sheet you are going to, and hide the one you just left.

Depending on your needs, there is one other approach you can try. You could add the following macro to the ThisWorkbook object:

Private Sub Workbook_SheetDeactivate(ByVal mySheet As Object) Application.EnableEvents = False mySheet.Activate Application.EnableEvents = True End Sub

This macro is executed every time the current worksheet is deactivated. It essentially “reactivates” the worksheet that is being left, which means that no other worksheet can ever be selected.

PREVENTING SOMEONE FROM RECREATING A PROTECTED WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jack creates worksheets that he forwards to others in his group so they can input information, and then return the worksheet to him. He protects the worksheets, but has gotten burned a few

ExcelTips 2008 Page 198

Page 212: Excel tips 2008

Worksheet Tips

times by users who have used copy and paste to recreate the worksheet in its entirety. Checking everything to make sure the returned worksheets are the originals is very time consuming, so Jack is looking for a way to remove the ability to copy and paste the worksheets.

Disabling copying and pasting is theoretically easy enough to do. All you need to do is use a short macro, like the following, in the ThisWorkbook object:

Private Sub Worksheet_Deactivate() If ActiveSheet.ProtectContents = True Then Application.CutCopyMode = False End If End Sub

Using this macro essentially clears the Clipboard every time someone deactivates the worksheet by selecting another worksheet or another application.

Of course, this offers only the most rudimentary of protection. A determined user can still copy the worksheet by using Edit | Move or Copy Sheet, or they could disable macros when starting the workbook, and thereby disable your Clipboard-clearing routine.

Perhaps a better way is to look at how business is done in the organization. If you don’t want people to copy the worksheet, tell them up front, and make sure they know that you won’t accept any duplicates. There are very easy ways to check to see if what you get back is a duplicate. Here are a few of them:

• Put a formula in a cell, then hide the cell contents during your protection process. If you get the worksheet back and unprotect the worksheet, and the formula is not there, the worksheet is a copy.

• Protect the worksheet by using a password. If you cannot later unprotect the worksheet with the same password, you know that someone else copied the worksheet and used their own password.

• Have your worksheet use hidden formulas to access data on a hidden worksheet. If the user copies the worksheet, the hidden worksheet isn’t copied to the new workbook, so the formulas won’t give the correct answers.

• Insert a macro module in the workbook, and then protect the module. The module doesn’t need to do anything, but if the workbook you get back doesn’t have the protected module, it is a copy.

• Add something into the custom properties area of the workbook. If the custom property is not in the workbook you get back, chances are good that the workbook is not the original.

Another thing to try is to set the cell protection property to Hidden before password protecting your worksheet. Users can see the results of what is in the cells, but they cannot see the formulas. If they copy and paste the contents elsewhere, the formulas won’t be transferred, only the results. This is very easy to spot in the returned workbook.

ExcelTips 2008 Page 199

Page 213: Excel tips 2008

Worksheet Tips

CHANGING THE COLOR OF WORKSHEET GRIDLINES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Most people using Excel leave the gridlines visible so that they can easily see where the various cells are. By default the gridlines are a light gray. You can easily change the gridlines to a different color by following these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the View tab is selected.

The View tab of the Options dialog box.

3. Ensure the Gridlines check box is selected. 4. Using the Gridlines Color drop-down list, choose the color you want to use. 5. Click OK.

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left side of the dialog box.

ExcelTips 2008 Page 200

Page 214: Excel tips 2008

Worksheet Tips

3. Scroll through the options until you see the Display Options for this Worksheet section.

The Advanced options of the Excel Options dialog box.

4. Ensure the Show Gridlines check box is selected. 5. Using the Gridline Color drop-down list, choose the color you want to use. 6. Click OK.

LOCKING WORKSHEET NAMES Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are developing workbooks for others to use, you may want your worksheets to retain whatever names you give them. Excel normally allows users to change worksheet names, as desired. If you don’t want them to change, the only way to prevent it is to lock the workbook. You can take these steps if you are using a version of Excel prior to Excel 2007:

1. Display the Protect Workbook dialog box. Do this by choosing Tools | Protection | Protect Workbook. (In Excel 2007 display the Protect Structure and Windows dialog box by displaying the Review tab of the ribbon and clicking Protect Workbook in the Changes group.)

ExcelTips 2008 Page 201

Page 215: Excel tips 2008

Worksheet Tips

The Protect Structure and Windows dialog box.

2. Make sure that the Structure check box is selected. 3. Enter a password in the Password box. 4. Click on OK. Excel displays the Confirm Password dialog box, prompting you to

reenter the password. 5. Reenter the password and click on OK.

The user can no longer make changes to the names of the worksheet tabs, nor to anything else that affects the structure of the workbook. (For instance, they cannot enter new worksheets or delete existing ones.)

If you want to protect the workbook under the control of a macro, then you can use this code:

ActiveWorkbook.Protect Password:="MyPassword", Structure:=True

All you need to do is provide password you want to use in place of the “MyPassword” example.

SWITCHING HEADERS IN A FROZEN ROW

Applies to Excel 97, 2000, 2002, 2003, and 2007

Tim’s got some worksheets that have two separate sections (let's call them upper and lower sections) that have slightly different column headers. He’s frozen the top row to keep the upper section headers visible while scrolling down, but after scrolling past a certain point Tim ends up looking at lower-section data with upper-section headers still at the top. He'd like to know if there is a way to switch that frozen header row to show the lower section headers when he scrolls down to the point that only lower-section data is showing.

Yes, there is a way to do this, but it involves the use of macros. Before considering a macro-based solution, you may want to consider restructuring your data so that each of your sections

ExcelTips 2008 Page 202

Page 216: Excel tips 2008

Worksheet Tips

are on different worksheets. (From a design perspective, this would be the easiest solution.) If this is not possible, then you need to be looking at macros.

One easy approach is to simply change what is stored in the top row (row 1) of your worksheet, depending on what row is selected. For instance, the following macro will make changes in the top row based on where the active cell is located. If it is before row 40, then one set of headers are stuffed into the first row; if after row 40 then another set of headers are stuffed.

Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim iBottomData As Integer iBottomData = 40 If ActiveCell.Row < iBottomData Then Cells(1, 1).Value = "Last Name" Cells(1, 2).Value = "First Name" Cells(1, 3).Value = "Address" Cells(1, 4).Value = "Balance" Else Cells(1, 1).Value = "Account" Cells(1, 2).Value = "Sales Rep" Cells(1, 3).Value = "Status" Cells(1, 4).Value = "" End If End Sub

To use the macro, just make sure that you place it in the code window for the worksheet that contains the two data sections. You should also change the value assigned to the iBottomData variable to reflect the row number of where your bottom data section starts.

If you want to actually change the frozen row as you move down the worksheet, then the macro needs to be a bit more robust. Actually, there are two macros that follow (both go, again, in the code window for the worksheet), and they are kicked into action as you change the selected cell and as you right-click on the worksheet.

Private Sub Worksheet_BeforeRightClick(ByVal _ Target As Range, Cancel As Boolean) Application.ScreenUpdating = False ActiveWindow.FreezePanes = False ActiveWindow.Split = False Application.EnableEvents = False Application.Goto Cells(1, 1), scroll:=True With ActiveWindow .SplitColumn = 0 .SplitRow = 1 End With ActiveWindow.FreezePanes = True Application.Goto Cells(Target.Row - 1, _ Target.Column), scroll:=True Application.EnableEvents = True On Error Resume Next 'MUST reenable events

ExcelTips 2008 Page 203

Page 217: Excel tips 2008

Worksheet Tips

Application.EnableEvents = False ActiveCell.Offset(-1, 1 - Target.Column).Select ' so the right click menu doesn't popup ' only if this is the second header row. Cancel = True Application.EnableEvents = True End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.ScreenUpdating = False If Cells(Target.Row, 1).Value <> "title2" Then Exit Sub ActiveWindow.FreezePanes = False ActiveWindow.Split = False Application.Goto Cells(Target.Row, 1), scroll:=True With ActiveWindow .SplitColumn = 0 .SplitRow = 1 End With ActiveWindow.FreezePanes = True On Error Resume Next 'MUST reenable events Application.EnableEvents = False ActiveCell.Offset(1, 1 - Target.Column).Select Application.EnableEvents = True End Sub

The Worksheet_SelectionChange event handler automatically moves the frozen split to below the second row of headings when your active cell cursor hits that line. This line is detected in the If statement that checks if the first cell in the row contains the text “title2” or not. (Obviouly, this should be changed to reflect what will really be in that first cell.)

The Worksheet_BeforeRightClick event handler moves the frozen split back to the first set of headings but leaves the active cell at the row above the second set of headings.

You should understand that both of the macro solutions presented in this tip assume that you are actually scrolling through the worksheet and changing the selected cell as you go. (In other words, you are pressing the Down Arrow key to do your scrolling.) If you are simply changing what is displayed in the worksheet by using the vertical scroll bar, then the frozen headings won’t change because you are not changing the selected cell and the event handlers never trigger.

Creating a more extensive solution would be beyond the scope of this tip because it would involve interfacing with the actual operating system. If you are interested in going this route, however, a good starting place might be this page at Chip Pearson’s Web site:

http://www.cpearson.com/excel/DetectScroll.htm

(Thanks to Andrija Vrcan, Steve Aprahamian, Rob Tillotson, Russell Hendel, and Richard Taylor for contributing to this tip.)

ExcelTips 2008 Page 204

Page 218: Excel tips 2008

Worksheet Tips

PROTECTING WORKSHEETS FROM DELETION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Chris has a workbook composed of two control worksheets that contain setup data. The workbook's user runs macros that create many new worksheets in the workbook. The user then deletes any unwanted worksheets. Chris wants to make sure that the two control worksheets aren’t deleted by mistake.

This can be accomplished, to some extent, by protecting the structure of the workbook, as described in other ExcelTips. This protects the workbook structure from being changed, such that the user can’t add or delete worksheets. Since you want the user able to add and delete worksheets, you’d need to make two changes to how the workbook is used:

• Modify the macro that adds worksheets so that it removes the workbook protection before adding the sheets and then reinstates the protection after the sheets are added.

• Add a macro function that deletes worksheets. The macro could check to make sure that the user isn’t trying to delete the control worksheets. If it is OK for the user to delete a particular worksheet, the macro would remove workbook protection, delete the sheet, and then reinstate the protection.

Another approach is to create duplicates of the control sheets in the workbook. Make these worksheets hidden, which protects them to a degree. Your macros could then check to see if the non-hidden control sheets were deleted. If they were, then the macro could create another control sheet by copying the hidden version of the control sheets.

Still another approach is to modify the macro that currently adds a bunch of worksheets to the workbook. The modification would create a “backup” workbook that contains the controls sheets. Later, before closing the workbook, a macro can be invoked that checks for the control sheets. If they are not present, then the macro copies them from the backup workbook. If they are present, then the backup workbook can be deleted.

PROTECTING A WORKSHEET'S FORMAT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Klara knows how to protect the contents of a worksheet by protecting cells. She wonders, however, if there is a way to protect only the format. She’s not too concerned if the content changes, but she wants to protect the format.

ExcelTips 2008 Page 205

Page 219: Excel tips 2008

Worksheet Tips

You can easily protect the formatting of the worksheet, without regard for the contents. Just follow these steps:

1. Select all the cells in the worksheet. 2. Choose Cells from the Format menu. Excel displays the Format Cells dialog box. (To

display the Format Cells dialog box in Excel 2007, display the Home tab of the ruler, click Format in the Cells group, and then choose Format Cells.)

3. Make sure the Protection tab is displayed.

The Protection tab of the Format Cells dialog box.

4. Clear the Locked checkbox. 5. Click on OK to close the dialog box. 6. Choose Protection from the Tools menu, and then choose Protect Sheet from the

submenu. Excel displays the Protect Sheet dialog box. (To display the Protect Sheet dialog box in Excel 2007, display the Home tab of the ruler, click Format in the Cells group, and then choose Protect Sheet.)

ExcelTips 2008 Page 206

Page 220: Excel tips 2008

Worksheet Tips

The Protect Sheet dialog box.

7. If you see a Format Cells check box in the dialog box (it isn’t there in all versions of Excel), make sure it cleared.

8. You do not need to change any information in the dialog box, nor enter a password. Just click on OK.

(Thanks to Steve Aprahamian for contributing to this tip.)

IDENTIFYING THE LAST CELL CHANGED IN A WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

John wonders if there is a way in VBA to identify the last cell that was changed by a user. He doesn’t want to know if the cell was changed by a macro, but specifically by a user.

The answer is yes—sort of. You can use the Worksheet_Change event to write a handler that will record when any particular cell in a worksheet is changed. A macro that does this could be rather simple, such as this one:

Private Sub Worksheet_Change(ByVal Target As Range) Application.StatusBar = Target.Address End Sub

ExcelTips 2008 Page 207

Page 221: Excel tips 2008

Worksheet Tips

ExcelTips 2008 Page 208

The macro simply puts the address of the last change into the status bar. You could modify the macro so that it maintained the address in a global variable (declared outside of the event handler) in this manner:

Dim sAddr As String Private Sub Worksheet_Change(ByVal Target As Range) sAddr = Target.Address(False, False) End Sub

You then could use a regular macro to retrieve the address stored in the sAddr macro and do whatever you want with it.

As for making sure that the event handler doesn’t record any changes done by macros, the only way to do this is to turn off event handling before executing any macro command that will modify the worksheet. For instance, the following EnableEvents property change could be used before and after a command that changes the contents of cell A1:

Application.EnableEvents = False Range("A1") = "Hello" Application.EnableEvents = True

With event handling turned off, the Worksheet_Change event handler won’t be triggered and the “last changed” address won’t be updated. The result is that you end up tracking only those changes done by users, not changes done by macros.

(Thanks to Steve Aprahamian, Andrija Vrcan, Peter Sands, Mark Farrell, Scott Burkhart, and Peter Atherton for contributing to this tip.)

Page 222: Excel tips 2008

Worksheet Function Tips

RETURNING A WORKSHEET NAME

Applies to Excel 97, 2000, 2002, 2003, and 2007

Looking for a way to put the name of your worksheet directly into a cell? Excel makes this easy through the use of the CELL function. If you include the following in a cell, Excel returns the fully path of the workbook, along with the sheet name:

=CELL("filename")

For instance, if you entered this into a cell in the Sheet1 worksheet of the MyWB workbook, the information returned by Excel might be something like C:\My Documents\[MyWB.xls]Sheet1 (depending, of course, on the drive and directory in which the workbook is saved).

To return just the worksheet name from this value, you could use the following in your cell:

=MID(CELL("filename"),(FIND("]",CELL("filename"))+1),50)

This will work for any worksheet name up to 50 characters in length. (If you routinely use different lengths, simply change the value in the expression.) Continuing the earlier example, Excel would return Sheet1 as the result.

GETTING THE NAME OF THE PARENT WORKBOOK

Applies to Excel 97, 2000, 2002, 2003, and 2007

Many people use the CELL worksheet function to return the name of the current Excel workbook. A common way to use the function is as follows:

=CELL("filename")

ExcelTips 2008 Page 209

Page 223: Excel tips 2008

Worksheet Function Tips

Using the CELL function in this manner is fine, provided you only have one workbook open at a time. If you open more than one, then this usage can cause problems. Why? Because when used this way, CELL returns the name of the currently active workbook, not the workbook in which the formula is used.

To always return the name of the workbook in which CELL is used (sometimes called the “parent workbook”), you must alter the formula just a bit:

=CELL("filename", A1)

By adding a cell reference as the second parameter in the function, you are telling Excel that you want the name of the file containing that cell reference. In other words, CELL will return the name of the file in which cell A1 of the current worksheet is located. (You can also provide any other cell reference in place of A1, if more appropriate.)

LARGE NUMBERS IN THE MOD FUNCTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Cesarettin noted that the MOD worksheet function cannot produce a result when the number is being evaluated is 268,435,456 or larger and the divisor is 2. If the number is less than this, there is no problem. For example, if the function is MOD(268435455, 2) there is no problem. He wonders if there is a way to use the MOD function with larger numbers and a divisor of 2?

The problem is actually bigger than what Cesarettin proposes. Microsoft knows about this problem; it seems to stem from issues with the internal formulas used by MOD. You can find more information about the error here:

http://support.microsoft.com/?kbid=119083

Basically, the MOD function returns an error if the divisor (the second argument in the MOD function), multiplied by 134,217,728, is less than or equal to the number being evaluated (the first argument in the MOD function).

Thus, the problem occurs when the number being evaluated is 268,435,456 and the divisor is 2, the number being evaluated is 402,653,184 and the divisor is 3, the number being evaluated is 536,870,912 and the divisor is 4, etc.

The solution suggested by Microsoft is to simply not use the MOD function and instead rely upon the following formula:

=number-(INT(number/divisor)*divisor)

ExcelTips 2008 Page 210

Page 224: Excel tips 2008

Worksheet Function Tips

This is not the only solution, however. There are other formulaic approaches you can use, as well. For instance:

=MOD(MOD(number,134217728*divisor),divisor)

This will solve for larger numbers much larger than the limit for MOD, but theoretically will hit the same problem when the number being evaluated reaches 134,217,728*134,217,728*divisor. For most uses, this is limit is large enough that it will never be reached.

If you only need to find the modulus of a number divided by 2, then you can insert a check into your formula in the following manner:

=MOD(IF(A1>=268435456,A1-268435456,A1),2)

This checks if the number being evaluated (in this case, in cell A1) is larger than the limit, and if it is it subtracts the limit from the number before calculating the modulus. You could also effectively remove the MOD limit by using this formula:

=MOD(MOD(number,2^16),2))

This takes the large number modulo 2 to the 16th power, then takes the resulting value modulo 2. If the numbers are viewed as binary, it's easy to see what is happening. MOD(largenum,2^16) just drops all bits to the left of the 16th binary digit. For modulo 2, only the right-most digit is required to determine the result anyway, so the dropped bits never affect the result, regardless of value.

Of course, you could simply create your own MOD function in VBA and use it in your formulas instead of the built-in MOD function.

Function DblMod(Dividend, Divisor) ' Declare two double precision variables Dim D1 As Double Dim D2 As Double ' Copy function arguments to local variables D1 = Dividend D2 = Divisor DblMod = D1 Mod D2 End Function

The function simply lets you pass two arguments to the VBA function. It then relies upon the VBA Mod function, which doesn’t have the same limitation as the MOD worksheet function.

(Thanks to Andrija Vrcan, Steve Aprahamian, David Latham, Rick Dicks, John Nolan, Dave Pettit, Andrew Sugden, Rob Jansen, and Bill Foust for contributing to this tip.)

ExcelTips 2008 Page 211

Page 225: Excel tips 2008

Worksheet Function Tips

RETURNING A WEIGHT AND A DATE

Applies to Excel 97, 2000, 2002, 2003, and 2007

David asked how he could return a date associated with the maximum value in a particular column. In David’s application, he had two columns containing dates and weights associated with those dates. He could figure out how to determine the maximum weight, but not how to pull the date on which that weight occurred.

In this instance, let’s assume that the dates are in column A and the weights are in column B, rows 2 through 45. The following is the method of determining the maximum weight in column B:

=MAX(B2:B45)

You are not limited to using the MAX function; you can also use the LARGE function, which returns the largest specified value in a range. If you want the largest value, you use the function in this way:

=LARGE(B1:B45,1)

So far so good. In order to pull the corresponding date from the cell to the left of the date, all you need to do is use one of the lookup functions. The following example uses the INDEX function:

=INDEX(A2:A45,MATCH(MAX(B2:B45),B2:B45,FALSE),1)

The INDEX function pulls the value from row n, column 1 of range A2:A45. The value of n is determined by using MATCH to get the position number of the maximum value of range B2:B45 within that range. For example, if the highest weight is the fourth one on the list (the weight in row 5), the MATCH expression returns 4, therefore the INDEX function returns the date from row 5, column 1 of range A2:A45.

If you wanted, you could simplify the formula even more by just specifying column information within it. In this way, you could have as many entries as desired in columns A and B:

=INDEX(A:A,MATCH(MAX(B:B),B:B,FALSE),1)

You could just as easily use the LARGE function in place of the MAX function in these formulas. If there are two dates that have the same weight associated with them, then only the first matching date is returned. In addition, you will need to format whatever cell contains your formula with a date format.

If your columns are reversed, meaning that the weights are in column A and the dates are in column B, then you would use the VLOOKUP function instead of INDEX, as shown here:

ExcelTips 2008 Page 212

Page 226: Excel tips 2008

Worksheet Function Tips

=VLOOKUP(LARGE(A1:A45,1),A1:B45,2,FALSE)

Again, the MAX function could be used in this formula instead of the LARGE function, if desired.

COUNTING DISPLAYED CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

The AutoFilter feature in Excel makes it easy to display just the information that you want from a data table. How you use AutoFilter has been discussed in other issues of ExcelTips. Once you’ve applied an AutoFilter to your data, you may want to use a function to display the number of cells that are displayed in a filtered range.

If you just need to quickly know the count, highlight the filtered range, right-click anywhere on the status bar, and choose Count from the resulting Context menu. Excel displays, in the status bar, the number of cells displayed in the range you selected.

If you need a solution that you can use in a formula, you should look towards the SUBTOTAL function. This function provides a number of different “subtotal” results, but it only operates on data that is displayed. This means that the information filtered out by AutoFilter won’t count in what SUBTOTAL returns.

The general syntax of the SUBTOTAL function is as follows:

=SUBTOTAL(type,range)

All you need to do is specify a type and a range. The range part should be easy: it is just a standard range. The type specifier can be a number between 1 and 11, as follows:

Type Function Performed 1 AVERAGE 2 COUNT 3 COUNTA 4 MAX 5 MIN 6 PRODUCT 7 STDEV 8 STDEVP 9 SUM 10 VAR 11 VARP

ExcelTips 2008 Page 213

Page 227: Excel tips 2008

Worksheet Function Tips

Notice that the type specifier you use indicates what Excel function is applied to the displayed results. Thus, if you want to determine the count of the filtered results in the range of F3:F27, you would use a type specifier of 2, as follows:

=SUBTOTAL(2,F3:F27)

This usage will, of course, count numeric values in the range specified. If you want to count text values, then you should use a type specifier of 3 so that Excel relies on the COUNTA function instead.

If you are the type of person that prefers a macro-based solution, then you may want to refer to the Microsoft Knowledge Base, article 213330 for a fuller discussion:

http://support.microsoft.com/?kbid=213330

FINDING THE LOWEST NUMBERS Applies to Excel 97, 2000, 2002, 2003, and 2007

You may have a need at some point to find the lowest numbers in a list of values. This is relatively easy to do if you use the SMALL worksheet function. The function takes two parameters: the range of the values to be evaluated and an indicator of which smallest number you want. For instance, the following will return the second lowest number in the range of A1:A100:

=SMALL(A1:A100,2)

If you wanted to know the two lowest numbers in the range, then use two formulas containing the SMALL function—one with 1 as the second parameter (for the lowest number) and one with 2 as the second parameter (for the second lowest number).

There are situations, of course, where the two smallest numbers in the range could actually be the same number. For instance, if the lowest number is 3 and there is a second 3 in the list, then both the lowest numbers will be the same. If you want the two lowest unique numbers then you will need to use a macro to determine them.

Function SMALLn(rng As Range, n) Application.Volatile SMALLn = False If n < 1 Then Exit Function Dim i As Long, j As Long, k As Long, min, arr, arr2 arr = Application.Transpose(rng) ReDim arr2(n - 1) min = Application.WorksheetFunction.Min(arr) j = UBound(arr)

ExcelTips 2008 Page 214

Page 228: Excel tips 2008

Worksheet Function Tips

k = 0 arr2(k) = min For i = 1 To j If Application.Small(arr, i) <> arr2(k) Then k = k + 1 arr2(k) = Application.Small(arr, i) If k = n - 1 Then SMALLn = arr2(k) Exit For End If End If Next i End Function

This user-defined function is used in the following manner:

=SMALLn(A1:A100,2)

When called like this, the function returns the second lowest unique value in the specified range.

(Thanks to Arvin Djapermal, Steve Aprahamian, Fred Burg, Maarten Daams, Bhavik Khatri, Andrija Vrcan, Bob Umlas, Nick Bafaloukos, Richard Raciborski, Roger Mason, Lou Aiello, Tony Morse, Cleveland Grant, Jacob Rashford, Benazir Ibrahim, Steven Basford, and Russell Hendel for contributing to this tip.)

ROUNDING TO POWERS OF 10 Applies to Excel 97, 2000, 2002, 2003, and 2007

If you want to round a number to the nearest 10, 100, or 1000, you can use the ROUND function with negative values for the second parameter. This approach works very well—and very quickly.

For instance, if you have a value in cell D6 and you want to round it to the nearest 100, you could use the following formula:

=ROUND(D6,-2)

This rounds to second digit to the left of the current decimal place. For instance, if D6 contains the value 12345, then the formula returns 12300. Similarly, if D6 contains 12351, then the formula returns 12400.

You can use the same technique to round to the nearest 10 by using -1 as the second parameter, or to the nearest 1000 by using -3.

ExcelTips 2008 Page 215

Page 229: Excel tips 2008

Worksheet Function Tips

CHECKING FOR TEXT Applies to Excel 97, 2000, 2002, 2003, and 2007

Cells in a worksheet can contain either numeric values, text values, or error values. (Some people will mention dates and times as another type of value, but these are nothing but special types of numeric values, as are Boolean values such as True and False.) In some instances, you may need to know whether a particular cell contains a text value or not.

You can use the ISTEXT function to make this determination. For instance, if you need to know if cell B7 contains a text value, you would use the following formula:

=ISTEXT(B7)

The function returns either True or False, depending on the type of value in cell B7. ISTEXT takes a single value, normally a cell reference of some kind. This should be a reference to a single cell; if you use a reference to a range, then the function always returns a False value.

ROUNDING NUMBERS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel provides a number of built-in worksheet functions for rounding numbers. The exact function you should use depends on exactly what you need to do with a value.

The first worksheet function is ROUND. This function allows you to essentially round to any power of ten. The syntax is as follows:

=ROUND(num, digits)

The num argument is the number you want to round, while digits indicates how many digits you want the result rounded to. If digits is a positive value, then it represents the number of decimal places to use when rounding. Thus, if digits is 3, then num is rounded to three decimal places. If digits is zero, then ROUND returns a rounded whole number. If digits is a negative number, then ROUND returns a number rounded to the number of tens represented by digits. Thus, if digits is –2, then ROUND returns a number rounded to the nearest 100.

Two other worksheet functions that return rounded values are ROUNDUP and ROUNDDOWN. These functions use the same arguments as ROUND and behave virtually identically. The only difference is that ROUNDUP always rounds num up, meaning away from 0. ROUNDDOWN is the opposite, always rounding down, toward 0.

ExcelTips 2008 Page 216

Page 230: Excel tips 2008

Worksheet Function Tips

USING THE MROUND WORKSHEET FUNCTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

In the previous tip you learned how you can round numbers using regular worksheet functions. These functions work great when you want to round a number to some decimal position. What if you want to round a number to some odd value, however? For instance, what if you want to round a value to the nearest multiple of 7, or to the nearest 50?

For these times, you should use the MROUND worksheet function. This function is provided as part of the Analysis ToolPak; it is not inherent to Excel. To use it, install the Analysis ToolPak (which many people do when Excel is first installed), and then choose Add-Ins from the Tools menu to make sure the Analysis ToolPak is selected.

The syntax for the MROUND function is as follows:

=MROUND(num, multiple)

The num argument is the number you want to round, while multiple is the value you want used in the rounding. Thus, if you want to round to the nearest 50, then multiple would be 50.

If you decide to use MROUND, it is important to remember that num and multiple must be the same sign. If one of them is positive and the other negative, then Excel returns a #NUM! error.

SUMIF DOESN'T RECALC AUTOMATICALLY

Applies to Excel 97, 2000, 2002, 2003, and 2007

Johan wrote about a problem he was having with the SUMIF function in his worksheet. It seems that when the data in his worksheet changes, the SUMIF function doesn’t automatically update. He is, however, able to update the formula if he selects it, presses F2 (to jump into edit mode) and then press ENTER.

The first, easiest, and most obvious thing to check is whether you have automatic calculation turned on. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Calculation tab is displayed.

ExcelTips 2008 Page 217

Page 231: Excel tips 2008

Worksheet Function Tips

The Calculation tab of the Options dialog box.

3. In the Calculation area, at the top of the tab, make sure that the Automatic radio button is selected. The other radio buttons all limit, in some way, when recalculation is done.

4. Click OK.

If you are using Excel 2007 then you should follow these steps, instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left of the dialog box, click Formulas.

ExcelTips 2008 Page 218

Page 232: Excel tips 2008

Worksheet Function Tips

The Formulas options of the Excel Options dialog box.

3. In the Calculation Options section, make sure that the Automatic radio button is selected. The other radio buttons all limit, in some way, when recalculation is done.

4. Click OK.

If this does not fix the problem, then it must be related to the actual SUMIF formula. For instance, you may think that the data you are changing in the worksheet is actually referenced in the SUMIF formula, but it may not be. (If it isn’t, then changing the data won’t change the formula results.) Check the formula to make sure that it covers the proper range.

Remember, as well, that if your worksheet is large and complex, and the SUMIF formula is in a cell that is above your data table, it is possible that you may need two calculation passes to update the SUMIF function. Why? Because when you calculate a worksheet, Excel basically calculates the cells from left to right and top to bottom. If you have a very large worksheet, with lots of dependent calculations, and the calculations on which everything else is dependent are at the bottom or right side of the worksheet, then you may get incorrect results for the SUMIF function. (This happens only with the most complex of worksheets.) The answer is to reorganize your worksheets so that the primary calculations are placed near the top of the worksheet and as far left as possible, and the calculations that are based on those primary calculations are placed later in the worksheet.

ExcelTips 2008 Page 219

Page 233: Excel tips 2008

Worksheet Function Tips

CELL AND NAME REFERENCES IN COUNTIF

Applies to Excel 97, 2000, 2002, 2003, and 2007

Larry has a worksheet that uses the COUNTIF function extensively. A typical use would be similar to the following:

=COUNTIF(B5:B25,">=2")

This works fine, but Larry would like to specify the second parameter using a cell or name reference, as in ">=B3" or ">=Goal". Problem is, Larry can’t get those types of references to work.

Indeed, if you use the following syntax for COUNTIF, you will not get the results you want:

=COUNTIF(B5:B25,">=B3")

The reason is because everything within the quotes is considered to be part of a string literal. In other words, B3 doesn’t (in this case) represent a cell reference, but the two characters B and 3.

The solution is to take the cell reference outside of the quote marks, in this manner:

=COUNTIF(B5:B25,">=" & B3)

In this case the B3 is not literal, but a reference to the contents of cell B3. If, for instance, cell B3 contains the value 49, then this instance of COUNTIF is translated in this manner:

=COUNTIF(B5:B25,">=49")

If you want to use a cell reference in the formula, and you will be copying that cell reference elsewhere in your worksheet, then you may want to make sure that you use an absolute reference to the cell, as in this usage:

=COUNTIF(B5:B25,">=" & $B$3)

That way you can copy the formula without Excel changing the B3 cell reference to some other cell. You can similarly use a named cell reference in your formula using the same technique:

=COUNTIF(B5:B25,">=" & Goal)

If you prefer, you could also simply put a criteria for COUNTIF in the cell you are referencing. For instance, cell B3 could contain the text “>=49”, without the quote marks. You could then simplify your use of COUNTIF in this manner:

ExcelTips 2008 Page 220

Page 234: Excel tips 2008

Worksheet Function Tips

=COUNTIF(B5:B25,B3)

(Thanks to Armando Montes, Benazir Ibrahim, Somanath Viswan, John Nolan, Chris Yu, Fred Burg, Barry Dysert, Peter Grebenik, Steve Aprahamian, Daniel Houle, Scott Huish, Glenn White, David Eddleman, Stephen Pike, Hong Maa, Russell Hendel, Theo Claas, Allan Spencer, Josef Van Nel, Les Landau, Graeme Wiltsher, Tim Cantley, Dale Anderson, Joe Edmiston, Dave Boggess, Mike Grund, Tony Morse, Bob Umlas, Henric Bladh, John Hill, Nisha Kumari, Roger Mason, and Brian Rowe for contributing to this tip.)

USING THE INT WORKSHEET FUNCTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

There are many times that you simply need to work with whole numbers. Excel provides a handy function, INT, for just such times. This function takes a single argument and returns the integer value of that argument. For instance, consider the following:

=INT(12.34)

Using this formula, Excel returns a value of 12. You should be aware that INT always returns the next lower whole integer. This only seems odd when dealing with negative numbers. For instance, consider the following:

=INT(-43.21)

You may be tempted to believe that Excel would return a value of –43, but this would be wrong. When following the rule of always returning the next lower whole integer, Excel would return –44, which is the next integer lower than –43.21.

USING THE TRUNC WORKSHEET FUNCTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

There may be times when you need to “truncate” a number at a certain number of digits. For this purpose Excel provides the TRUNC worksheet function. TRUNC can work with either one or two arguments, as necessary for your purposes. When use with only a single argument, TRUNC simply drops off any part of the number after the decimal point. For instance, consider the following:

ExcelTips 2008 Page 221

Page 235: Excel tips 2008

Worksheet Function Tips

=TRUNC(12.34)

This returns a value of 12, which is everything to the left of the decimal point. This result may look familiar, and you may be tempted to think that TRUNC does the same thing as the INT function. There are several differences, however. Consider a scenario where the argument is less than zero:

=TRUNC(-43.21)

In this instance, TRUNC returns –43, not –44 as INT would. Remember, when using TRUNC with a single argument, it simply drops everything to the right of the decimal point.

If you use a second argument with TRUNC, you can specify the number of decimal places at which you want the truncation to occur. For instance, the following formula returns a value of 12.3:

=TRUNC(12.34,1)

If you use a negative value for the second argument, the truncation takes place to the left of the decimal point. This has the same effect as returning powers of 10. For instance, consider the following example, which returns the value of 1200:

=TRUNC(1234.5678,-2)

RETURNING BLANKS WITH VLOOKUP

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you use VLOOKUP to return a value from a data table, the function does not differentiate between blanks and zero values in what it returns. If the source value is zero, then VLOOKUP returns 0. Likewise, if the source is blank, then VLOOKUP still returns the value 0. For some purposes, this may not do—you need to know whether the cell being looked up is blank or if it really contains a 0.

There are many different solutions that could be pursued. One solution relies on the fact that even though VLOOKUP returns a 0, it will correctly report the length of the source cell. Thus, if you use the LEN function on what is returned, if the source cell is empty the LEN function returns 0, but if the source contains a 0 then LEN returns 1 (the 0 value is 1 character in length). This means that you could use the following formula in place of a standard VLOOKUP:

=IF(LEN(VLOOKUP(B1,D:E,2,0))=0,"",VLOOKUP(B1,D:E,2,0))

ExcelTips 2008 Page 222

Page 236: Excel tips 2008

Worksheet Function Tips

In this case if the length of what VLOOKUP returns is 0, then Excel doesn’t actually do a lookup—it forces a blank to be returned. Only if the length is not 0 is the actual VLOOKUP performed.

There are other variations on this same concept, each testing a different characteristic of the data being referenced and then making the decision as to whether to actually look up that data. This variation, for example, directly tests to see if the source is blank:

=IF(VLOOKUP(B1,D:E,2)="","",VLOOKUP(B1,D:E,2))

The formula can also be modified to check the source cell for multiple conditions. For instance, this variation returns a blank if the source is blank or if the source contains an #N/A error:

=IF(ISNA(VLOOKUP(B1,D:E,2,0))+(VLOOKUP(B1,D:E,2,0)=""),"",VLOOKUP(B1,D:E,2,0))

RETURNING BLANKS OR ASTERISKS FROM A LOOKUP

Applies to Excel 97, 2000, 2002, 2003, and 2007

Bob asked if there was a way to use VLOOKUP to return blanks or asterisks if the function cannot make a match in a lookup table.

Yes, this can be done, but not without making your formula just a bit more complex. The trick is to remember that VLOOKUP can operate in one of two ways. By default, it returns the next lower value to the one being looked for, if the data table is in ascending order and if there isn’t an exact match. However, you can force VLOOKUP to only return exact matches, if desired. Consider the following example:

=VLOOKUP(5,A1:B10,2,FALSE)

This example searches through the lookup table (A1:B10) looking for the value 5 in the first column of the table. If it is found, then the corresponding value from the second column is returned. If it is not found, then VLOOKUP returns an #N/A error, indicating it could not locate the value. (The FALSE value as the fourth parameter indicates you don’t want approximate matches.)

The key, then, is to play off this #N/A value and build what you want returned if there isn’t a match. The following formula will return a series of five asterisks if there wasn’t a match in the lookup:

=IF(ISNA(VLOOKUP(5,A1:B10,2,FALSE)),"*****",VLOOKUP(5,A1:B10,2,FALSE))

ExcelTips 2008 Page 223

Page 237: Excel tips 2008

Worksheet Function Tips

ExcelTips 2008 Page 224

The ISNA function is used to test if the result of VLOOKUP is the #N/A error. If it is, then the asterisks are returned; if not, then the lookup value is returned. If you want the formula to return “nothing,” then you can use this variation:

=IF(ISNA(VLOOKUP(5,A1:B10,2,FALSE)),"",VLOOKUP(5,A1:B10,2,FALSE))

This version returns a blank string if there was not a match in the lookup table. For some uses, this may not be exactly what you want. You may find it more appropriate to return a zero, and then hide zeroes in the worksheet (Tools | Options | View tab | clear the Zero Values check box). If you’d like a zero returned, then it takes only one change:

=IF(ISNA(VLOOKUP(5,A1:B10,2,FALSE)),0,VLOOKUP(5,A1:B10,2,FALSE))

Page 238: Excel tips 2008

Formula Tips

EVALUATING FORMULAS Applies to Excel 2002, 2003, and 2007

Often it is frustrating to figure out exactly how Excel arrives at a particular result—particularly if the formula returning the result is quite complex. Fortunately, Excel provides a tool you can use to help figure out what is going on when Excel evaluates a formula. To access this tool, follow these steps if you are using Excel 2002 or Excel 2003:

1. Select the cell containing the formula you want to evaluate. 2. Choose Formula Auditing from the Tools menu. Excel displays a submenu. 3. Form the submenu choose Evaluate Formula. Excel displays the Evaluate Formula

dialog box.

If you are using Excel 2007, then display the Formulas tab of the ribbon. In the Formula Auditing group click the Evaluate Formula tool. Excel displays the Evaluate Formula dialog box.

The Evaluate Formula dialog box.

ExcelTips 2008 Page 225

Page 239: Excel tips 2008

Formula Tips

At this point, Excel shows the full formula from the cell, and part of it is underlined. This underlined area represents the part of the formula that Excel will next evaluate. This allows you to see what intermediate steps Excel follows in arriving at a result. Every time you click the Evaluate button, Excel replaces the underlined portion of the formula with a result.

Nothing you do with the formula evaluator actually affects the formula in your worksheet; it remains unchanged. Instead, Excel simply shows you what happens as it works through each part of the formula to arrive at a result. When you are done using the formula evaluator, click the Close button.

EXACT FORMULA COPIES Applies to Excel 97, 2000, 2002, 2003, and 2007

Many formulas in a worksheet don’t occur in solitude—they often appear numerous times in a worksheet. For instance, you may copy a formula into a range of cells in a column, each formula operating on data on its own row.

When you copy formulas, Excel automatically adjusts any relative cell references in the formula so that they remain relative in the target cell. For instance, if a formula in cell C4 is =A4+B4, then copying the formula down to cell C5 results in the formula =A5+B5.

There may be times when you want to create an exact copy of a formula, without Excel adjusting the relative cell references during the copy process. Assuming you want to make an exact copy of the formula in cell C4 and copy it to C5, follow these steps:

1. Select cell C4. 2. Press F2. Excel enters Edit mode, with the insertion point at the end of the formula. 3. Press SHIFT+CTRL+HOME. Excel selects everything in the cell, back to the beginning of

the formula. 4. Press CTRL+C to copy the selected text (the formula’s text) to the Clipboard. 5. Press ENTER to move to cell C5. 6. Press CTRL+V to paste the Clipboard contents into the cell.

During this paste process, the relative cell references are not updated—the formula in cell C5 is now an exact duplicate of the one in cell C4.

ExcelTips 2008 Page 226

Page 240: Excel tips 2008

Formula Tips

IGNORING CASE IN A COMPARISON

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you use Excel’s IF function to compare two cells that contain text, Excel, by default, ignores the case of the text being compared. For instance, if cell B3 contains “Case” and cell B4 contains “case”, then the following formula returns “Match”.

=IF(B3=B4,"Match","No Match")

There is no way to modify this behavior using any settings in Excel. If you do not get these results, it is likely because of some other reason. For example, the text in the cells may look the same, but it may not really be the same. For instance, one cell could contain “Case “ (with the trailing space), and the other contain “case”. In this instance, the formula would return “No Match”, and you would assume it is because of the capitalized C in one of the cells, but the real reason is because of the trailing space. You can confirm this by changing the formula, as follows:

=IF(TRIM(B3)=TRIM(B4),"Match","No Match")

The only difference here, of course, is that the TRIM function is used to return a cell value that has all leading and trailing spaces removed.

If you want Excel to actually take text case into account, you should use the EXACT statement, as shown here:

=IF(EXACT(B3,B4),"Match","No Match")

The EXACT function returns True if the cells are exactly the same, otherwise it returns False.

SUMMING BASED ON FORMATTING IN ADJACENT CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Srinivas has data in both columns A and B. He needs to sum the values in column B for which the cell format of the corresponding cells in column A are yellow. For instance, if the format in cell A17 is yellow, then the value in cell B17 should be included in the sum.

There are numerous macros available on the Internet (including at ExcelTips) that allow you to do conditional summing based on the color or other format of a cell. This need is different,

ExcelTips 2008 Page 227

Page 241: Excel tips 2008

Formula Tips

however, in that it is not the color of the cell at issue, but the color of the cell one column to the left. This can still be done using a macro, as shown here:

Function SumNextYellow(ByVal r As Range) Dim c As Range Dim a As Double For Each c In r If c.Offset(0, -1).Interior.ColorIndex = 6 Then 'Yellow a = a + c.Value End If Next c SumNextYellow = a End Function

The function can be used in a worksheet formula, and accepts a range reference as an argument. It then steps through each cell in the range, and if the cell just to the left is yellow, then the value is included in the sum. (You should note that the ColorIndex used in the macro should be tested with your version of Excel to make sure that it is applicable; it may be different in different versions.)

A much more robust example is shown in the following listing. This function accepts one or more ranges of cells, along with an argument that represents a sample of the formatting you want to use.

Function ColorConditionSum(cSample As Excel.Range, rng As Excel.Range) ' This Function returns sum of values in rng.Columns(2) if ' corresponding cell in rng.Columns(1) is colored with sample ' color (cSample cell) ' Arguments: cSample = cell colored by sample color ' rng = cell range to be processed (2 columns) Dim rngCol2 As Excel.Range Dim rngConstants As Excel.Range Dim rngFormulas As Excel.Range Dim lColorIndex As Long Dim MySum As Double Dim area As Excel.Range Dim c As Excel.Range ColorConditionSum = False If Not TypeOf cSample Is Excel.Range Then Exit Function '>>> lColorIndex = cSample.Interior.ColorIndex MySum = 0 Set rngCol2 = Nothing If TypeOf rng Is Excel.Range Then If rng.Columns.Count < 2 Then Exit Function '>>> On Error Resume Next For Each area In rng.Areas

ExcelTips 2008 Page 228

Page 242: Excel tips 2008

Formula Tips

If rngCol2 Is Nothing Then Set rngCol2 = area.Columns(2).SpecialCells(xlCellTypeConstants, 1) If rngCol2 Is Nothing Then Set rngCol2 = area.Columns(2).SpecialCells(xlCellTypeFormulas, 1) Else Set rngCol2 = Application.Union( _ rngCol2, area.Columns(2).SpecialCells(xlCellTypeFormulas, 1)) End If Else Set rngCol2 = Application.Union( _ rngCol2, area.Columns(2).SpecialCells(xlCellTypeConstants, 1)) Set rngCol2 = Application.Union( _ rngCol2, area.Columns(2).SpecialCells(xlCellTypeFormulas, 1)) End If Next area For Each area In rngCol2.Areas For Each c In area.Cells With c.Offset(0, -1) If .Interior.ColorIndex = lColorIndex Then MySum = MySum + c.Value End If End With Next c Next area End If ColorConditionSum = MySum End Function

You use this function in the following manner in a worksheet:

=ColorConditionSum(A10, A12:B22)

In this case, is a cell that has the interior color you want to match and A12:B22 is the range of cells to be evaluated. The values are pulled from the second column in the range and the formatting is checked on the cells in the first column.

(Thanks to Andrija Vrcan, Andrew Coombe, Chris Purtill, Marcus Bowens, Lloyd Wuerth, Steve Aprahamian, Harry Ruchti, Jason Friedman, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 229

Page 243: Excel tips 2008

Formula Tips

FINDING THE NTH OCCURRENCE OF A CHARACTER

Applies to Excel 97, 2000, 2002, 2003, and 2007

Barry often finds himself wanting to identify the Nth occurrence of a character within a text string. He knows he can use the SEARCH and FIND worksheet functions for finding an initial occurrence, but is unsure how to find, say, the 3rd occurrence of the letter "B" within a text string.

Actually, the SEARCH function could be used to find the desired occurrence, in the following manner:

=SEARCHB("b",G20,(SEARCHB("b",G20,(SEARCHB("b",G20,1)+1))+1))

Notice how the SEARCHB function is used in a nested manner. The formula specifies what is being searched for (the letter “b”) and the number of nesting levels indicates which occurrence within the cell you want to find. The formula returns the position of the desired character within the cell.

The problem with such a formula, of course, is that it is difficult to maintain and can quickly get unusable if you want to find, say, the seventh occurrence.

A more flexible formula would be the following:

=FIND(CHAR(1),SUBSTITUTE(A1,"B",CHAR(1),3))

This formula examines the value in A1. It substitutes the CHAR(1) code for the third occurrence of “B” within the cell. The FIND function then looks within the resulting string for the position where CHAR(1) occurs. If the desired occurrence does not exist, then the formula returns a #VALUE error.

If you prefer, you could create a user-defined function that will look for the Nth position of a character. The following is a very simple macro that takes three arguments: the string to be searched, the text to match, and the position desired.

Function FindN(sFindWhat As String, _ sInputString As String, N As Integer) As Integer Dim J As Integer Application.Volatile FindN = 0 For J = 1 To N FindN = InStr(FindN + 1, sInputString, sFindWhat) If FindN = 0 Then Exit For Next End Function

ExcelTips 2008 Page 230

Page 244: Excel tips 2008

Formula Tips

The function is case sensitive in what it searches for, and it returns the position within the specified string at which the sFindWhat value occurs. If there is no occurrence at the specified instance, then the function returns a 0. The following shows how the function can be used in a worksheet:

=FindN("b",C15,3)

(Thanks to Steve Aprahamian, Dave Latham, Joe Smith, Daniel Houle, Richard Raciborski, Erik Haartmans, Mike Hughes, Russell Hendel, Tim Harris, Todd Corson, Tim Cantley, and Chris Purtill for contributing to this tip.)

DETERMINING BUSINESS QUARTERS FROM DATES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Robert is looking for a way to determine the business quarter in which a particular date falls. For example, if cell A1 has 2/15/08, he would want cell B1 to contain a formula that returned Q1-08. Similarly, if cell A1 has 8/1/07, he would want cell B1 to return Q3-07.

There are literally dozens of ways that you can determine a straight business quarter from a date. A few of these methods are worth examining, and they are easily modified to adapt to any specific needs. What is assumed here is that you really want to use a self-contained formula, rather than using a lookup table or a VBA macro. Both of those approaches will work just fine, but it is assumed that the simple formulas will work best for your purposes.

The key factor in determining the business quarter is to look at the month of the date. One way to do that examination is to use a formula that relies on the CHOOSE function. Consider the following:

=CHOOSE(MONTH(A1),"Q1","Q1","Q1","Q2","Q2", "Q2","Q3","Q3","Q3","Q4","Q4","Q4") & "-" & RIGHT(YEAR(A1),2)

This is a single formula; it is rather long, providing a choice for each of the 12 months in the year. Each month returns the quarter portion of the result, and then the text for the year is appended.

Another way is to rely on IF statements to determine the quarter. This is done in the following manner:

=IF(MONTH(A1)<=3,"Q1",IF(MONTH(A1)<=6,"Q2", IF(MONTH(A1)<=9,"Q3","Q4")))&"-"&TEXT(A1,"yy")

ExcelTips 2008 Page 231

Page 245: Excel tips 2008

Formula Tips

The IF statements check the month to see its relation to the various boundaries for the quarters (3, 6, and 9) and then assigns a proper quarter (Q1, Q2, Q3, or Q4) based on the result. A dash and the last two digits of the year is then appended to the quarter.

You can make the formula even shorter by calculating the quarter directly based upon the month. For instance, the following will take the month and return a value of 1 to 4 based on the month:

=INT((MONTH(A1)-1)/3)+1

This formula can be incorporated into a larger formula in this way:

="Q" & INT((MONTH(A1)-1)/3)+1 & "-" & RIGHT(YEAR(A1),2)

(Thanks to Steve Aprahamian, Peter Cloutier, Marc Schroven, Dave Latham, Fred Burg, Mary Lawrence, Scott Huish, Theo Claas, Kirk Mays, Sheldon Lennox, Terry Bradshaw, Andrija Vrcan, Jim Wise, Rob Tillotson, Nick Bafaloukos, Charlie O’Neill, Benazir Ibrahim, Tom De Luca, Richard Raciborski, Danny Whittaker, Samir Ashtikar, Sagar Chitre, Mike Hughes, Kim Hook, Henric Bladh, Roger Mason, Tim Harris, Adrian Fielden, Penny Ross, Andrew Coombe, Christian Rakvaag, Greg Baker, Chris Purtill, David Hill, Andrew Sugden, Russell Hendel, and Stephen Barrett for contributing to this tip.)

SUMMING ONLY POSITIVE VALUES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Alma has a worksheet that has a column of data containing both positive and negative values. She would like to sum only the positive values in the column and is wondering if there is a way to do it.

Fortunately Excel provides a convenient worksheet function you can use for just this purpose. Suppose, for instance, that all the values were in column A. In a different column you could enter the following formula:

=SUMIF(A:A,">0")

The SUMIF function returns a sum of all values in the range (A:A) that meet the criteria specified (>0). Any other values—those less than or equal to 0—are not included in the sum.

If you don’t want to use SUMIF on an entire column, a simple modification in the range being evaluated can be made:

=SUMIF(A1:A100,">0")

Here only the rante of A1:A100 is being evaluated and included in the sum.

ExcelTips 2008 Page 232

Page 246: Excel tips 2008

Formula Tips

(Thanks to Marc Schroven, Steve Aprahamian, Scott Huish, Theo Claas, Tore Softing, David Sipple, Fred Burg, Bob Hall, E. Nora Abbott, Flavio Ramirez, Peter Cloutier, John Nolan, Phil Richcreek, Audrey Felkel, Peter Mackin, Carolyn Gorup, Russell Hendel, Benazir Ibrahim, Nick Bafaloukos, Maarten Daams, Arvin Djapermal, Curtis Izen, Matthew Ralph, Greg Trapp, Richard Raciborski, Ahmet Kabadayi, Lokesh Mahajan, Glenn Bumford, Adrian Fielden, Mike Hughes, Peter Petersen, Tim Cantley, Peter Merante, Joe Edmiston, Darrel Danielson, Alan Meshaw, Mark Brandon, John Hubbard, Andrew Coombe, Tim Gwynn, Bill Foust, Chris Purtill, Nina Willis, Octavio Espinosa, Keny Drescher, Johan Maertens, Roger Mason, Anthony Hughes, and Don Scott for contributing to this tip.)

ERRORS WHEN SUBTRACTING Applies to Excel 97, 2000, 2002, 2003, and 2007

Fred expressed some confusion and concern about the results he received when subtracting certain numbers. For instance, when he subtracts 3809717.98 from 3799904.94, he should get -9813.04, but instead gets -9813.04000000003.

What Fred is witnessing is an artifact of Excel’s limitations. The problem is ultimately related to how Excel works with floating-point numbers. Computers must store numbers internally as binary values, not as the decimal values we see displayed on the screen. Whole numbers can be stored as binary values relatively easily. When you throw a decimal point into the mix, then storing very large or very small numbers becomes more problematic—Excel just isn’t able to store them with absolute precision. Instead, Excel provides an “approximate” result, out to 15 digits (the limits of its precision). Thus, you end up with something like -9813.04000000003, which contain the full 15 digits of precision possible in Excel.

A full discussion of how floating-point numbers are maintained in Excel and computers in general can very quickly get extremely technical. For those who want more information on the topic, here are two places you can start your research:

http://support.microsoft.com/?kbid=78113 http://docs.sun.com/source/806-3568/ncg_goldberg.html

The bottom line is that the only way to get the “exact” results you want, to the number of decimal places you want, is to use the ROUND function in your formulas, as shown here:

=ROUND(3799904.94 - 3809717.98, 2)

You can also, if desired, change the precision used to within all formulas by following these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Calculation tab is displayed.

ExcelTips 2008 Page 233

Page 247: Excel tips 2008

Formula Tips

The Calculation tab of the Options dialog box.

3. Ensure that the Precision As Displayed check box is selected. 4. Click OK.

In Excel 2007 you would follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left of the dialog box click Advanced. 3. Scroll through the available options until you get to the section entitled “When

Calculating this Workbook.”

ExcelTips 2008 Page 234

Page 248: Excel tips 2008

Formula Tips

The advanced options in the Excel Options dialog box.

4. Ensure that the Set Precision As Displayed check box is selected. 5. Click OK.

Now, Excel uses the precision shown on the screen in all of its calculations, instead of doing calculations at the full 15-digit precision it normally maintains.

FINDING THE FIRST NON-DIGIT IN A TEXT VALUE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Tony has a bunch of data in a worksheet that consists of digits and other characters. For instance, he might have a cell that contains “1234567Blue.” Tony wants to be able to figure out the character position at which the first non-digit character occurs. In the example of the text “1234567Blue” Tony wants some way to figure out that the first non-digit character is at position 8.

There are two primary ways to get the value you want. The first is to use an array formula to calculate the position. The following array formula (entered by using CTRL+SHIFT+ENTER) will work in the majority of cases:

=MATCH(TRUE,ISERROR(VALUE(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1))),0)

ExcelTips 2008 Page 235

Page 249: Excel tips 2008

Formula Tips

The only instances where this array formula won’t work is if cell A1 is either empty or contains a strictly numeric value. If your list may contain this type of data (or no data at all), then you should consider using a slightly longer array formula:

=IF(LEN(A1)=0,0,MIN(IF(1*ISNUMBER(1*MID(A1,ROW(INDIRECT("A1:A"& LEN(A1))),1))=0,ROW(INDIRECT("A1:A"&LEN(A1))),LEN(A1)+1)))* (ISNUMBER(A1)=FALSE)

Remember that that is a single array formula, entered by using CTRL+SHIFT+ENTER. It will properly handle instances where A1 contains no non-digit characters (as in a blank cell or a value such as “123”).

Of course, the other way you can handle finding out the position of the first non-digit character is to create a user-defined function. There are many different ways that such a macro can be implemented. One of the easiest ways to implement the macro is to simply step through each character in whatever is passed to the macro. When a character is found that is outside the ASCII code range for digits (48 to 57), then you know you’ve found the first position. The following macro shows a way to do this type of technique:

Function FirstNonDigit(str As String) Dim iChar As Integer Dim iPos As Integer Dim J As Integer Application.Volatile iPos = 0 For J = 1 To Len(str) iChar = Asc(Mid(str, J, 1)) If iChar <= 47 Or iChar >= 58 Then iPos = J Exit For End If Next J FirstNonDigit = iPos End Function

To use the function, simply use a formula such as this in your worksheet:

=FirstNonDigit(A1)

(Thanks to Theo Claas, Mike Hughes, Harold Druss, Marc Prosl, Steve Aprahamian, Kirk Mays, Charlie O’Neill, Russell Hendel, Attila Molnar, Bob Rodriguez, Richard Raciborski, Roger Mason, Andrew Coombe, and Nick Bafaloukos for contributing to this tip.)

ExcelTips 2008 Page 236

Page 250: Excel tips 2008

Formula Tips

REFERENCING THE LAST SIX ITEMS IN A FORMULA

Applies to Excel 97, 2000, 2002, 2003, and 2007

Darryl needs to find the average of the last six entries in a column. The number of items in the column can vary over time as more information is added, but he always wants the average of those last six items.

There are a number of different formulas you can use, probably too many to go over here in detail. With that in mind, it is instructive to look at two particular formulas. The one you choose to use will depend on the characteristics of the data in the column. If there are no blank cells in the column, then finding the average can be done with a relatively simple formula:

=AVERAGE(OFFSET(A1,COUNT(A:A)-6,0,6,1))

This formula uses the OFFSET function to calculate the proper cells to examine, at the bottom of the column. This formula won’t work if there are blank cells in the column. In that case you will need to use a formula that examines the contents of each cell and determines, as part of the calculation process, whether it is blank or not. Array formulas or regular formulas using array functions are great for this purpose. The following example uses the SUMPRODUCT function to accomplish the task:

=SUMPRODUCT((A1:A30*((MAX(ROW(A1:A30)*(A1:A30<>""))-ROW(A1:A30))<6))/6)

This formula assumes that the cells to be evaluated are in the range of A1:A30; it doesn’t matter if there are blank cells in this range. The ROW functions are used to create arrays that determine if the individual cells contain values or not. Only those rows containing values end up being counted, and those are divided by 6 and summed, providing the desired average.

(Thanks to Sander Neuraij, Cliff Edwards, Steve Aprahamian, Andre Croteau, Rick Stephens, Benazir Ibrahim, Theo Claas, Richard Raciborski, Russell Hendel, Johan Maertens, Bhavik Khatri, Henric Bladh, Mike Hughes, Francis Parkhe, Roger Mason, Mark Rotchell, Andrew Sugden, Marc Schroven, and Nick Bafaloukos for contributing to this tip.)

COUNTING CELLS ACCORDING TO CASE

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are using Excel to analyze a group of cells containing text, you may want to determine the number of cells that contain uppercase, the number that contain lowercase, and the number that

ExcelTips 2008 Page 237

Page 251: Excel tips 2008

Formula Tips

contain mixed case. There are two ways you can approach this task: Using a regular worksheet formula, or defining your own user-defined function.

If the text you want to evaluate is in column A, starting at cell A1, you could use the following formula in cell B1:

=IF(A1>"",IF(EXACT(UPPER(A1),A1),"Upper", IF(EXACT(LOWER(A1),A1),"Lower","Mixed")),"")

The formula checks to see if there is anything in A1. If there is, then it uses the EXACT function to compare the contents to various conversions of the cell’s contents. The formula returns an empty string if cell A1 is empty or the words Upper, Lower, or Mixed.

Copy the formula down column B as far as you need to, and then you can use the following type of formula to determine the count:

=COUNTIF(B:B,"Upper")

To find the count of lowercase or mixed-case cells, replace “Upper” with “Lower” or “Mixed”.

Obviously, using formulas in this manner involves adding a column to your worksheet. There is another formula approach you can use that doesn’t involve the use of an intermediate column in this manner. Consider the following formula, which returns the number of cells in the range A1:A100 that contain only uppercase letters:

=SUMPRODUCT(--(EXACT(A1:A100,UPPER(A1:A100))),--(A1:A100<>""))

A variation on this formula can be used to return the number of lowercase cells. The only thing that is changed in the following is the use of the LOWER function instead of the UPPER function:

=SUMPRODUCT(--(EXACT(A1:A100,LOWER(A1:A100))),--(A1:A100<>""))

To determine cells containing mixed case, you need to come up with a mix of the two SUMPRODUCT-based formulas:

=SUMPRODUCT(--(NOT(EXACT(A1:A100,UPPER(A1:A100)))),-- (NOT(EXACT(A1:A100,LOWER(A1:A100)))),--(A1:A100<>""))

There are some drawbacks to these formulas, drawbacks that aren’t evident in the earlier formulas. First, if a cell contains a numeric value, then these formulas count the cell as uppercase. Second, if a cell contains an error value, then the formula returns an error.

If you have the need to count case quite often, then you would probably be better served by creating a user-defined function that does the counting for you. There are many ways that such a function could be written, but the general guidelines are the following:

ExcelTips 2008 Page 238

Page 252: Excel tips 2008

Formula Tips

• Step through each cell of a range • Determine if the cell is upper, lower, or mixed case • Increment some counter • Return a value

The following macro is one example of how the above can be implemented:

Function CountCase(rng As Range, sCase As String) As Long Dim vValue Dim lUpper As Long Dim lMixed As Long Dim lLower As Long Dim rCell As Range lUpper = 0 lLower = 0 lMixed = 0 For Each rCell In rng If Not IsError(rCell.Value) Then vValue = rCell.Value If VarType(vValue) = vbString _ And Trim(vValue) <> "" Then If vValue = UCase(vValue) Then lUpper = lUpper + 1 ElseIf vValue = LCase(vValue) Then lLower = lLower + 1 Else lMixed = lMixed + 1 End If End If End If Next Select Case UCase(sCase) Case "U" CountCase = lUpper Case "L" CountCase = lLower Case "M" CountCase = lMixed Case Else CountCase = CVErr(xlErrValue) End Select End Function

Determining if a cell is upper, lower, or mixed case is obviously the crux of a macro such as this. Making such a determination uses the same process as was done in the worksheet formulas: compare the contents of the cell to the uppercase or lowercase conversion of those contents. In this macro the value of the cell (vValue) is compared to vValue transformed with either the UCase or LCase function.

ExcelTips 2008 Page 239

Page 253: Excel tips 2008

Formula Tips

The function also ignores cells that it doesn’t make sense to evaluate. It ignores cells containing numeric values, Boolean values, error values, empty cells, and cells that contain only spaces. If a numeric value is formatted as text, then the function counts that cell as uppercase. To use this user-defined function, use a formula such as the following in your worksheet:

=COUNTCASE(A1:A100, "L")

For the first argument you use the range you want evaluated. The second argument is a single character—L, M, or U—indicating which count you want returned. If you use some other value for the second argument, then the function returns an error.

STOPPING A FORMULA FROM UPDATING REFERENCES

Applies to Excel 97, 2000, 2002, 2003, and 2007

David wonders if there is a way he can make a formula not automatically update when he inserts a column that would otherwise affect the formula. For instance, if he has the formula =SUM(B:B) and then he inserts a column to the left of column B, the formula is automatically updated by Excel to =SUM(C:C). He doesn't want the formula to update; he still wants it to refer to column B after he inserts the new column.

One way to get the result you want is to use the OFFSET function to refer to column B. For instance, consider the following formula:

=SUM(OFFSET(A:A,0,1))

If this formula is in a cell, and you insert a column before column B, then the formula doesn’t update; it still refers to column B. Why? Because the formula refers to column A and you didn’t do anything to move column A. If you did insert a column before column A, then the formula would update to reference column B.

This means that the best way to handle the formula is to use the INDIRECT function, in this manner:

=SUM(INDIRECT("B:B"))

The INDIRECT function uses text for a parameter, and since it is text it is not considered a reference to be updated by Excel. Regardless of inserting or deleting columns, the formula will always refer to column B.

(Thanks to Steve Aprahamian, Stephe Ellis, Benazir Ibrahim, Richard Raciborski, Matthew Ralph, Johnny Tam, Mike Hughes, Colin Millerchip, Michael Stonek, Tony Morse, and Marianna Galstyan for contributing to this tip.)

ExcelTips 2008 Page 240

Page 254: Excel tips 2008

Formula Tips

CALCULATING THE MEDIAN AGE OF A GROUP OF PEOPLE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jan has a worksheet that has a list of ages in column A. The ages start at 1 and go through to 100. In column B she has the number of people in each of those ages. Jan needs a formula that will tell here the median age of this group of people.

It should be pointed out that the median age is going to be different than the average age for a group of people. The average can be calculated most easily by multiplying the age by the number of people that is each age. For instance, in column C you could place a formula such as =A1*B1 and then copy it down the column. Add up the values in columns B and C, and then divide the sum in column C by the sum in column B. The result is the average age for the list of people.

The median age, on the other hand, is the age at which half of the people fall below that age and half above that age. The median age can best be calculated by using an array formula, such as the following:

=MATCH(SUM($B$1:$B$100)/2,SUMIF($A$1:$A$100, "<="&$A$1:$A$100,$B$1:$B$100))

This is a single formula, entered by pressing CTRL+SHIFT+ENTER. The SUMIF function in the formula is used to generate an array of the cumulative number of people who are less than or equal to each age. The SUM portion of the formula gives the midpoint of the total frequency of ages. The MATCH function is then used to look up the midpoint value in the array of cumulative frequencies. This yields an “index number” in the initial array, and since the array consists of the all ages 1 through 100, this index number matches is equivalent to the median age.

(Thanks to John Nolan, Jan Nielsen, Steve Aprahamian, Richard Raciborski, Adrian Fielden, Yosef Kedem, Jason Friedman, and Anil Malhotra for contributing to this tip.)

GENERATING DOUBLE-DIGIT RANDOM NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Venkataramanan needs to generate random numbers in the range of -99 to +99, excluding single-digit numbers (-9 to +9). He wonders if there is a way to accomplish the task.

There are a couple of worksheet functions that are often used to generate random numbers in Excel. The RAND function is used to generate a random number between 0 and 1, while the

ExcelTips 2008 Page 241

Page 255: Excel tips 2008

Formula Tips

RANDBETWEEN function (part of the Analysis ToolPak) is used to generate a random number within a range of numbers.

There is no function to do what Venkataramanan wants to do, but you can write a formula that will do the trick. Consider this formula:

=IF(RAND()>0.5,1,-1)*(RANDBETWEEN(10,99))

The first RAND function determines if the result is '+' or '-' and the next RANDBETWEEN function returns the desired number between 10 and 99. When the function is done, you have the desired double-digit random number.

Another formula is similar in nature:

=ROUND(RAND()*89+10,0)*((RAND()<0.5)*2-1)

The first part generates whole numbers in the range of 0 through 89. The formula adds 10 to this, effectively giving a number from 10 to 99. The second part of the formula is then used to randomly determine whether the result should be positive or negative.

Another approach relies entirely on the RANDBETWEEN function and doesn’t use any multiplication:

=VALUE(IF(RANDBETWEEN(0,1)=0,"-","")&RANDBETWEEN(1,9)&RANDBETWEEN(0,9))

The formula puts together a string that consists of either a minus sign or a blank followed by two digits. The formula then uses the VALUE function to convert the string to a numeric value.

(Thanks to Abhay Jain, Steve Aprahamian, Peter Cloutier, Dana Allen, Marc Schroven, Andre Croteau, Kevin Combs, Charlie O’Neill, Richard Raciborski, Stephen Barrett, Danny Whittaker, Len Dvorkin, Johnny Tam, Tom de Groot, Mark Rotchell, Piers Morgan-Harvey, Alan Bates, Bob Purosky, John Hill, Peter Moseley, Louis Farrell, and Russell Hendel for contributing to this tip.)

EXCLUDING VALUES FROM AVERAGING

Applies to Excel 97, 2000, 2002, 2003, and 2007

You’ve seen it on the Olympics and in other sporting events: The average score for an athlete is determined by throwing out the highest score and the lowest score, and then averaging the rest. You may have a need to do similar types of averages. For instance, you may be a teacher and need to exclude the two lowest assignment scores before calculating an average.

ExcelTips 2008 Page 242

Page 256: Excel tips 2008

Formula Tips

To perform this type of averaging, all you need to remember is that an average is calculated by summing all the values in a range, and then dividing that sum by the number of items in that range. The SUM function easily provides the sum, and the COUNT function can be used to find out the number of items in the range. How to exclude the two lowest values in the range? You can us the SMALL function. Consider the following formula, which assumes you want to find an adjusted average of the range A10:A14:

=(SUM(A10:A14)-SMALL(A10:A14,1)-SMALL(A10:A14,2))/(COUNT(A10:A14)-2)

The SMALL function is used to determine the two lowest values in the range, and these are subtracted from the overall sum of the range. The resulting value is then divided by the COUNT of values in the range. Note, as well, that the COUNT value is decreased by 2 to compensate for the fact you are ignoring the two lowest values.

Another way to calculate the same average is to use an array formula. The following one does the trick:

=AVERAGE(IF(A10:A14>SMALL(A10:A14,2),A10:A14))

Since this is an array formula, you need to enter it by pressing CTRL+SHIFT+ENTER instead of just pressing ENTER. This formula still relies on the use of the SMALL function, but it also uses the actual AVERAGE function to return a result. Since this is an array formula, it examines each of the values in the array (the range) and only considers them for use in the average if they are larger than the second smallest value in the array.

While the array formula is shorter than the longer regular formula, there is one caveat to keep in mind: The array formula will produce an undesired result if there is a two-way “tie” in the second-lowest value in the range, or a three-way tie in the lowest value. For instance, if the values being averaged are 3, 2, 10, 3, and 7, then the array formula will produce an average of 8.5. Why? Because only the values 10 and 7 are above the second-lowest value, and the average of those two is 8.5. If you use the longer formula, first presented above, then the average returned is 6.666667, which is the average of 10, 3, and 7.

If you try these formulas and they don’t work, you should check to make sure that you have the Analysis ToolPak installed. The SMALL function is a part of that ToolPak.

ExcelTips 2008 Page 243

Page 257: Excel tips 2008

Formula Tips

RETURNING LEAST-SIGNIFICANT DIGITS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Glenn has a need to return the three least significant digits of a four-digit number and is wondering how this can best be done. As with many tasks in Excel, there are a number of ways you can derive the desired information. One way is to use the MOD function, in this manner:

=MOD(A1,1000)

This function divides the value in cell A1 by 1000 and then returns what is left over. Provided that the value in A1 is a four-digit integer, then you’ll get the result you desire.

Another similar method of determining the desired values is to use a function that is normally used with text values:

=RIGHT(A1,3)

This returns the three right-most characters (digits) of whatever is in cell A1. If you think that it is possible that A1 could have some non-digit characters in it, then you should wrap the function in the VALUE function, like this:

=VALUE(RIGHT(A1,3))

Of course, it is very possible that any of the approaches discussed so far will give undesired results. While they work well if the value in A1 is an integer value, they don’t work that well if the value is a real number, such as 12.36 or 105.2, having four significant digits. In these cases you may want to use a formula such as the following:

=RIGHT(0.0001*A1,3)

(Thanks to Benazir Ibrahim, Steve Aprahamian, Barry Dysert, Jan Lergner, Len Dvorkin, Richard Raciborski, Mike Hughes, Ira Artman, and Rick Taylor for contributing to this tip.)

ROUNDING TO THE NEAREST EVEN INTEGER

Applies to Excel 97, 2000, 2002, 2003, and 2007

Chuck asked if there was a way in Excel to force rounding to the nearest even integer. He expressed this desire based on some statistical analysis that he was doing.

ExcelTips 2008 Page 244

Page 258: Excel tips 2008

Formula Tips

There are several ways that you can round to the nearest even integer, but the answer you select depends on how you define “nearest.” For instance, if the number you want to round is 13, is the nearest even integer 12 or 14? Does the answer change if dealing with negative numbers, as in -13?

If you believe that the next even integer is always away from zero, then you can use the EVEN function, which always rounds to the next even integer away from zero. Thus, -13 is rounded to -14, and 13 is rounded to 14. This may work great when rounding integers, but it doesn’t work that great if you are rounding non-whole values. For instance, EVEN rounds 12 to 12, but rounds 12.1 to 14, even though 12.1 is clearly closer to 12 than to 14.

If the numbers you are rounding are non-whole numbers, you’ll need a formula. The following formula will work for this purpose:

=INT(A2/2+0.5)*2

Assuming your non-rounded value is in cell A2, this formula divides the value by 2 and then rounds that value to an integer, and then multiplies the result by 2. What this means is that all values, 11.1 through 13, are rounded to 12. (This works for negative values, as well.)

PULLING FORMULAS FROM A WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to display the formulas in a worksheet simply by making sure the Formulas check box is selected on the View tab of the Options dialog box. This can be a handy way to print a worksheet that shows the formulas used to create the worksheet.

However, this approach only works well if the formulas used in the worksheet are rather short. If the formulas are longer, then understanding a worksheet with formulas displayed can quickly become a bothersome chore.

One solution is to pull the formulas from Excel and place them in a program such as Word. Why Word? Because you can easily format text attributes (such as typeface and point size) to best display your formulas. You can also add additional text to explain the formulas, if desired.

The simplest way to get formulas from Excel into Word is to follow these steps if you are using a version of Office prior to Office 2007:

1. In Excel, choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the View tab is selected.

ExcelTips 2008 Page 245

Page 259: Excel tips 2008

Formula Tips

The View tab of the Options dialog box.

3. Ensure that the Formulas check box is selected. 4. Click on OK. Excel should now be displaying formulas. 5. Select the cells whose formulas you want to copy to Word. 6. Press CTRL+C to copy the cells to the Clipboard. 7. Switch to Word. 8. Position the insertion point where you want the information added. 9. Choose Paste Special from the Edit menu. Word displays the Paste Special dialog box.

ExcelTips 2008 Page 246

Page 260: Excel tips 2008

Formula Tips

The Paste Special dialog box in Word.

10. Choose the Unformatted Text option. 11. Click on OK.

If you are using Office 2007 then you should follow these steps, instead:

1. In Excel, click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Advanced. 3. Scroll through the list of options until you see the section entitled Display Options for

this Worksheet.

ExcelTips 2008 Page 247

Page 261: Excel tips 2008

Formula Tips

The Advanced options of the Excel Options dialog box.

4. Ensure the Show Formulas In Cells Instead of Their Calculated Result check box is selected.

5. Click on OK. Excel should now be displaying formulas. 6. Select the cells whose formulas you want to copy to Word. 7. Press CTRL+C to copy the cells to the Clipboard. 8. Switch to Word. 9. Position the insertion point where you want the information added. 10. Display the Home tab of the ribbon. 11. Click the down-arrow under the Paste tool, and then choose Paste Special. Word

displays the Paste Special dialog box. 12. Choose the Unformatted Text option. 13. Click on OK.

At this point your formulas are in Word, and you can do with them as you see fit. While this approach works well, it can become bothersome to do this over and over again if you have a large number of formulas to copy. If you are in such a situation, you would benefit from having a macro that actually pulled the formulas and placed them in a Word document for you. The following Excel macro will do just that:

Sub WriteFormulasToWord() Dim Wrd As New Word.Application Dim CellTxt As String

ExcelTips 2008 Page 248

Page 262: Excel tips 2008

Formula Tips

Dim CellAddr As String Dim SRow As Long Dim SCol As Long Wrd.Visible = True Wrd.Documents.Add Wrd.Selection.TypeText Text:="List of the Formulas of Sheet """ _ & ActiveSheet.Name & """ in Workbook """ _ & ActiveWorkbook.Name & """." Wrd.Selection.TypeText Text:=vbCrLf & vbCrLf 'Change the following line to pick the number of columns For SCol = 1 To 5 'Change the following line to pick the number of rows For SRow = 1 To 10 If Cells(SRow, SCol).HasFormula Then CellAddr = Chr(64 + SCol) & Trim(Str(SRow)) & vbTab CellTxt = ActiveSheet.Cells(SRow, SCol).Formula Wrd.Selection.TypeText Text:=CellAddr & CellTxt Wrd.Selection.TypeText Text:=vbCrLf End If Next SRow Wrd.Selection.TypeText Text:=vbCrLf Next SCol End Sub

There are a couple of things to note in this macro. First of all, you can change the range of rows and columns over which the macro works by changing the noted For statements that use both SCol and SRow. In the example shown above, the macro pulls formulas from columns 1 through 5 (A through E) and rows 1 through 10.

In addition, this macro will not work properly unless you set up Excel macros to handle references to Word objects. You do that by following these steps within the VBA Editor:

1. Choose References from the Tools menu. VBA displays the References dialog box.

ExcelTips 2008 Page 249

Page 263: Excel tips 2008

Formula Tips

The References dialog box.

2. Scroll through the list of references until you see one called Microsoft Word Object Library. (There may be a version number included in the reference name, such as Microsoft Word 12.0 Object Library.)

3. Make sure the check box to the left of the object library is selected. 4. Click on OK.

An advantage to using a macro to actually pull your formulas is that you can customize exactly what is placed in the Word document. In the case of this macro, the address of the cell is inserted, followed by a tab character, and then the actual formula. You could just as easily change the information inserted to be anything you need in your particular instance.

FIGURING OUT THE LOW-SCORE WINNER

Applies to Excel 97, 2000, 2002, 2003, and 2007

Mike asked if there is a way to determine the low-score winner on a hole-by-hole basis in a golf game. He uses Excel to track the individual hole scores, but he needs to know who has the lowest unique score on each hole. (If there is a tie on a hole, then he doesn’t need to know who was involved in the tie.)

ExcelTips 2008 Page 250

Page 264: Excel tips 2008

Formula Tips

In providing an answer, there are several assumptions that must be made. First, assume that the values 1-18 (for each golf hole) are in cells A2 through A19. Second, assume that the low-score winner will be noted in column B. Third, assume that there are four golfers playing, and that their names are in cells C1 through F1. This range (C1:F1) is named “GolferNames”. Finally, the golf scores for each golfer are entered in cells C2 through F19.

With this structure used, there are any number of ways that the formula could be structured. I particularly like this formula, which should be placed in cell B2:

=IF(MIN(C2:F2)=SMALL(C2:F2,2),"There is a " & TEXT(COUNTIF(C2:F2, MIN(C2:F2)),"0") & "-way tie", INDEX(GolferNames,MATCH(MIN(C2:F2),C2:F2,0)))

This is a very long formula, and you should make sure that it is entered all on a single line. You can then copy the formula from B2 and paste it in B3 through B19.

If there is a tie (determined by comparing the results of the MIN function with the second lowest score, as returned by the SMALL function), then the formula returns “There is a 2-way tie”, or whatever number is actually involved in a tie. If there is not a tie, then the INDEX function is used to retrieve the name of the golfer that had the lowest score for the hole.

This example used, of course, only four golfers. If there are more golfers involved, the only alterations to make involve changing the range covered by the GolferNames range and expanding all instances of C2:F2 in the formula to represent the actual range of golfer scores.

If you prefer to simply not list anything if there was a tie on a hole (i.e., don’t say “There is a 2-way tie”), you can do so with this simplified version of the formula:

=IF(MIN(C2:F2)=SMALL(C2:F2,2),"", INDEX(GolferNames,MATCH(MIN(C2:F2), C2:F2,0)))

DETERMINING WINNERS, BY CATEGORY

Applies to Excel 97, 2000, 2002, 2003, and 2007

Suppose that your company sponsors a benefit car show, and you are charged with keeping track of scores and coming up with the winners. Each column in the worksheet represents a different category of car, and each row represents a different entrant in the contest. Each cell in the table contains a score for that contestant in the appropriate categories. Your job, after tracking the scores, is to calculate the top three winners in each category: first, second, and third place.

ExcelTips 2008 Page 251

Page 265: Excel tips 2008

Formula Tips

If each category will contain a unique score for each person (there are no ties), then calculating the top three scores in each category is relatively easy. Let’s assume that the first three rows of the worksheet are used to show the top three winners in each category. Cell A1 contains 1 (for first place), cell A2 contains 2 (for second place), and cell A3 contains 3 (for you know which place).

The actual scoring table begins in cell A5, with column labels. Cell A5 contains the word “Names,” and then cells B5:AA5 have the names of each car category. Cells A6:A100 contain the names of each contestant, and B6:AA100 contains the scores for those contestants, by category.

Enter the following formula into cell B1:

=INDEX($A$6:$A$100,MATCH(LARGE(B$6:B$100,$A1),B$6:B$100,0))

Copy the formula to the rest of the results range, B1:AA3. The formula looks at the ranking in column A (1 through 3) and then uses that to pick the first, second, and third largest values in each column. Rather than return the value, however, the value is used to pick the name of the person with that value; it is this name that is returned.

This approach, as mentioned, assumes there are no ties in the scoring table. If it is possible to have ties, then the scoring becomes much more complex and, perhaps, the best solution is to create a user-defined function in a macro. (The reason that ties make it more difficult is that the judges need to come up with a set of rules by which to break ties. These rules can vary, which means that the formulas—and user-defined functions—can vary.)

Another suggestion is to modify the way in which your scoring table is maintained. Instead of creating a large matrix (26 columns and however many contestants there are), create a small database that only has three columns: name, category, and score. You would then enter the data for each person into the database, and sort the database to get the desired winners. Simply sort first by category and then by score, and you can easily see who the top three contestants are in each category.

REPLACING DASHES WITH PERIODS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a need to normalize the appearance of your data, you might want to replace any dashes in a text string with periods. For instance, if you have a phone number such as “123-555-1212” you might want to change it to “123.555.1212”. This is easy to do using the SUBSTITUTE function:

=SUBSTITUTE(A7,"-",".")

ExcelTips 2008 Page 252

Page 266: Excel tips 2008

Formula Tips

The result is that any dashes appearing in the string in cell A7 are replaced with periods.

INCREMENTING NUMERIC PORTIONS OF SERIAL NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Ted has a range of serial numbers in the format A12345678B. He would like to find a formula that will increment the numeric portion of the serial numbers by 1. Thus, the next number in sequence would be A12345679B, then A12345680B.

There are actually a couple of ways you can go about this, and the first doesn’t really involve a formula at all. Instead you can create a custom format that displays your serial number. How you go about creating custom formats has been described in other ExcelTips; the format should look like this:

“A”#”B”

Then, in a cell that has this format applied, you only need to include the numeric portion of the serial number (12345678). You can then use regular AutoFill techniques to fill out as many cells as necessary with the serial number.

If you have your heart set on using a formula, then the following should work just fine as long as the pattern for the serial number is a single letter, eight numeric digits, and a single terminating letter:

=LEFT(A1,1) & MID(A1,2,8)+1 & RIGHT(A1,1)

This assumes that cell A1 contains the beginning serial number. If you put the formula in cell A2, it could be copied down as many times as necessary for the desired number of serial numbers.

If the numeric portion of the serial number could start with leading zeroes, then you need to use a different formula to provide the proper zero padding:

=LEFT(A1,1) & TEXT(VALUE(MID(A1,2,8))+1,"00000000") & RIGHT(A1,1)

(Thanks to Alana Glewis, Kirk Mays, Steve Aprahamian, Maarten Daams, Benazir Ibrahim, Diane Hoag, Nick Bafaloukos, Theo Claas, Barry Dysert, Charlie O’Neill, Yakub Lokhandwala, Rob Tillotson, Bill Garland, Roger Mason, Henric Bladh, Joe Edmiston, John Cross, Brian Erberich, Bob Purosky, Samuel Radcliffe, Dave Latham, Vic Bloomfield, Shaun Endersby, Subodh Bohra, Cheryl Potter, Mark Mace, Sarah Faust, Curtis Izen, Chris Purtill, and David Prout for contributing to this tip.)

ExcelTips 2008 Page 253

Page 267: Excel tips 2008

Formula Tips

COUNTING NON-BLANK CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

You may already know that you can use the COUNTBLANK function to return the number of blank cells in a range. What if you want to count the number of non-blank cells in the same range? One way is to use the COUNTA function, as shown here:

=COUNTA(B1:B13)

The only problem with this formula is that it doesn’t return the complementary value to what COUNTBLANK returns. In other words, the result of COUNTA added to the result of COUNTBLANK doesn’t equal the total number of cells in the original range. The reason for this is that both COUNTBLANK and COUNTA treat formulas different. COUNTBLANK includes, as blank, formulas that return a blank value. COUNTA does not consider such cells blank (even though a blank is returned), so it includes them in its count.

If you consider non-blank cells to be those that are not returned by COUNTBLANK, then you will need to use a longer formula:

=(ROWS(B1:B13)*COLUMNS(B1:B13))-COUNTBLANK(B1:B13)

This formula subtracts the COUNTBLANK result from the total number of cells in the same range.

COUNTING UNIQUE VALUES Applies to Excel 97, 2000, 2002, 2003, and 2007

David has a worksheet in which there is a list of countries. This list, in cells A1:A100, can contain duplicates. David wants to determine the number of unique countries in the list.

There are several ways you can go about deriving a count, without resorting to using a macro. The method you should use depends on the characteristics of the data in the list. A good place to start, however, is to define a named range that represents the list of countries. In the following examples, it is assumed that the range is named Countries. (Catchy name, huh?)

If the list contains only text entries, and does not contain any blank cells, then the following will provide a count:

=SUM(1/COUNTIF(Countries,Countries))

ExcelTips 2008 Page 254

Page 268: Excel tips 2008

Formula Tips

This should be entered as an array formula, by pressing CTRL+SHIFT+ENTER. If the list contains blank cells, then the formula becomes a bit more complex. The following long array formula will work if there are blanks:

=SUM(IF(FREQUENCY(IF(LEN(Countries)>0,MATCH (Countries,Countries,0),""), IF(LEN(Countries) >0,MATCH(Countries,Countries,0),""))>0,1))

This approach—using the FREQUENCY function—is fully recounted in the Microsoft Knowledge Base:

http://support.microsoft.com/?kbid=100122

If you prefer to not use array formulas (for whatever reason), you can utilize a blank column to the right of your list. This column will contain regular formulas that indicate if the value to its left is unique in the list or not. The first time a value appears, the formula returns the number 1. On each subsequent appearance of the same value, the formula returns a 0. Start by sorting your list, then place the following formula in cell B1:

=IF(ISNA(VLOOKUP(A2,$A$1:A1,1,)),1,0)

Just copy the formula from B1 to the range B2:B100. With these results in place, you can easily sum column B and have a count of the unique values in the list.

COUNTING CONSECUTIVE NEGATIVE NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Lori has a series of numbers, in adjacent cells, that can be either positive or negative. She would like a way to determine the largest sequence of negative numbers in the range. Thus, if there were seven negative numbers in a row in this sequence, she would like a formula that would return the value 7.

We’ve looked high and low and can’t find a single formula that will do what is wanted. You can, however, do it with an intermediate column. For instance, if you have your numbers in column A (beginning in A1), then you could put the following formula in cell B1:

=IF(A1<0,1,0)

Then, in cell B2 enter the following:

=IF(A2<0,B1+1,0)

ExcelTips 2008 Page 255

Page 269: Excel tips 2008

Formula Tips

Copy this down to all the other cells in column B for which there is a value in column A. Then, in a different cell (perhaps cell C1) you can put the following formula:

=MAX(B:B)

This value will represent the largest number of consecutive negative values in column A.

If you don’t want to create an intermediate column to get the answer, you could create a user-defined function that will return the value.

Function MaxNegSequence(rng As Range) ' search for the largest sequence ' of negative numbers in the range Dim c As Range Dim lCounter As Long Dim lMaxCount As Long Application.Volatile lCounter = 0 lMaxCount = 0 On Error Resume Next For Each c In rng.Cells If c.Value < 0 Then lCounter = lCounter + 1 If lCounter > lMaxCount Then lMaxCount = lCounter End If Else lCounter = 0 End If Next c MaxNegSequence = lMaxCount End Function

To use the function, just place a formula similar to the following in your worksheet:

= MaxNegSequence(A1:A512)

(Thanks to Theo Claas, Andrija Vrcan, Steve Aprahamian, Marcel Spruit, John Brown, Carolyn Gorup, Adrian Fielden, and Eric Gillen for contributing to this tip.)

ExcelTips 2008 Page 256

Page 270: Excel tips 2008

Formula Tips

COUNTING WINS AND LOSSES Applies to Excel 97, 2000, 2002, 2003, and 2007

Graham has, in Excel, created a matrix of player names for his league. Cells B2:H2 contain the names of the players, as do cells A3:A9. At each intersection in the matrix, Graham places a “W” or “L” to indicate whether the match-up resulted in a win or loss for the player in each row. If a player plays another person more than once, then a cell contains a “W” or “L” for each game. Graham was wondering what formula could be used, starting in column I, to indicate the number or wins and losses for each player.

There are a number of ways you can get the desired information. One is to use this type of formula:

=LEN(SUBSTITUTE(B3&C3&D3&E3&F3&G3&H3,"L",""))

This formula calculates the number of non-L characters in row 3—in other words, the number of wins. It does this by concatenating the contents of B3:H3, and then using the SUBSTITUTE function to remove all the Ls. This leaves the Ws, which are counted by the LEN function. You could also use the CONCATENATE function, in the following manner, for the same result:

=LEN(SUBSTITUTE(CONCATENATE(B3,C3,D3,E3,F3,G3,H3),"L",""))

To calculate the number of losses, simply replace “L” in each formula with “W”.

You can also use an array formula, which allows you to specify a range of cells to examine, rather than needing to specify every single cell:

=SUM(LEN(SUBSTITUTE(B3:H3, "L","")))

This array formula, entered by pressing SHIFT+CTRL+ENTER, returns the number of wins (W characters) in the range B3:H3.

Finally, you can use a user-defined function to return the occurrences of a specific character within a given range. The following macro will do the trick:

Function CharNums(r, chr) As Integer Dim c As Range Dim strX As String Dim J As Integer Application.Volatile CharNums = 0 For Each c In r.Cells strX = c.Value For J = 1 To Len(strX) If Mid(strX, J, 1) = chr Then CharNums = CharNums + 1

ExcelTips 2008 Page 257

Page 271: Excel tips 2008

Formula Tips

Next J Next c End Function

To use the function, you would us a formula like this in your worksheet:

=CharNums(B3:H3;"W")

The function returns the number of uppercase W characters in the range. All other characters (including lowercase w characters) are ignored. To count losses, simply substitute L for W in the formula.

COUNTING ONLY MONEY WINNERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Chuck has a worksheet with prize monies to be awarded to the eighty players in his golf league. Each row represents a player, and each column represents the winners of each of the five tournaments held in the season. The sixth column contains a simple formula summing the winnings shown on each row. At the bottom of this sixth column Chuck wants to enter a function that would count the number of players actually receiving monetary awards.

There are several ways you can put together such a formula. You might be tempted to use the COUNTA function, but it won’t work. The purpose of COUNTA is to count all the cells that are not empty. This means it will also count cells containing a zero value; they are not empty either.

You could use the SUMPRODUCT function in the following manner:

=SUMPRODUCT((G1:G80>0)*1)

This formula just checks if a cell is greater than zero. If it is, then the True value is multiplied by 1 resulting in a value of 1. If it is False, then the False value multiplied by 1 is 0. The sum of all these values (1 and 0) is then calculated, resulting in a count as desired.

Perhaps the easiest approach, however, is to use the COUNTIF function. This function performs a count only if a particular criteria is met:

=COUNTIF(G1:G80,">0")

In this case, the count only occurs if a cell is greater than zero.

ExcelTips 2008 Page 258

Page 272: Excel tips 2008

Formula Tips

LAST NON-ZERO VALUE IN A ROW

Applies to Excel 97, 2000, 2002, 2003, and 2007

Brian has a row of numbers with 240 cells. In this row, the numbers are steadily declining and will eventually, at some point in those 240 cells, become 0. The zeroes will continue to fill the remaining cells in the row. Brian needs to write an equation that will return the last non-zero value in the row.

There are a variety of ways that the desired value can be returned. (Doesn’t that always seem to be the case with Excel? You can come up with lots of ways to get a result.) In general, you could use a regular formula or an array formula.

If you want to use a regular formula, here’s one you can try:

=OFFSET(A6,0,(COUNT(A6:IF6)-COUNTIF(A6:IF6,0))-1)

The COUNTIF function counts the number of zero values and the COUNT function determines the number of cells in the range. Subtracting one from the other and adjusting by 1 gives the OFFSET value into the “array” of cells where the last non-zero value lies. This formula assumes that the values begin in column A; if they begin in a different column then you’ll need to adjust the value provided by the COUNT/COUNTIF portion of the formula to represent the offset from the first column.

Here’s a shorter variation of the formula, based on doing an offset from the right side of the range rather than the left side:

=OFFSET(IF6,0,-COUNTIF(A6:IF6,0))

In this instance it is important that IF6 be the actual right end of the range. The formula works by counting the number of zero values in the range (all at the right side of the range) and then computing the cell address of the last cell (IF6) minus the number of zeros.

Here is a version that uses the INDEX function, instead:

=INDEX(A6:IF6,,MATCH(0,A6:IF6,0)-1)

This version is even shorter, using the LOOKUP function:

=LOOKUP(1,1/(6:6>0),6:6)

Array formulas can also be used. (Array formulas are entered by pressing CTRL+SHIFT+ENTER.) This one uses the INDIRECT function:

ExcelTips 2008 Page 259

Page 273: Excel tips 2008

Formula Tips

=INDIRECT("R6C" & MAX((A6:IF6>0)*COLUMN(A6:IF6)),FALSE)

This array formula uses an interesting implementation of the LOOKUP function to find the correct result:

=LOOKUP(9.99999999999999E+307,IF(A6:IF6<>0,A6:IF6))

Here’s another array formula that can be used, this time using the OFFSET function to find the last non-zero value in row 6:

=OFFSET(A6,0,MIN(IF(6:6=0,COLUMN(6:6),300))-2)

Here’s an even shorter variation:

=MIN(IF(A6:IF6>0,A6:IF6))

All of these formulas presented so far depend on the fact that the numbers in the row actually do decline—they go from whatever the beginning number is and steadily go toward zero. If the numbers don’t decline, then you can use a different type of array formula to determine the last non-zero value in the row:

=INDEX(6:6,MAX(IF(A6:IF6<>0,COLUMN(A6:IF6))))

The formula first determines the maximum column in the row (in this case row 6) that has a value not equal to zero, then it uses the INDEX function to get the value from that column in that row.

As you can tell, there are quite a few ways to find the last non-zero value in a row. Pick the one that strikes your fancy; there is no right or wrong in this instance.

(Thanks to Andrija Vrcan, Abhay Jain, Nick Curnick-Orrin, Kirk Mays, Cecil Rhoades, Nick Bafaloukos, Steve Aprahamian, Barry Dysert, Rick Dicks, Armando Montes, Stephe Ellis, Peter Smith, Ray Kanner, Charlie O’Neill, Scott Huish, Peter Cloutier, Darrel Danielson, Roger Mason, Dale Anderson, Kevin Fried, Fred Pettersen, Benazir Ibrahim, Samuel Radcliffe, Allan Spencer, Andrew Coombe, Michelle Unger, Danny Whittaker, and Russell Hendel for contributing to this tip.)

GETTING THE NAME OF THE WORKSHEET INTO A CELL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Kevin has a workbook containing 36 worksheets. He needs a way, in each of the worksheets, to have the worksheet name (from the worksheet's tab) in a cell of that worksheet. He has created a

ExcelTips 2008 Page 260

Page 274: Excel tips 2008

Formula Tips

user-defined function that returns the worksheet name, but it returns the same name on all 36 worksheets—the name of whatever worksheet is displayed when the user-defined function is executed. He wonders if there is a macro, in user-defined function (UDF) form, that he can use that will always return the name of the sheet on which the function is used. In other words, in his 36-worksheet workbook, it should return 36 different results, depending on the worksheet in which it is used.

The short answer is yes, there is a way. In fact there are a couple of ways. And, interestingly enough, you don’t have to use a macro or function if you don’t want to. For instance, here is a regular worksheet formula that will work in any cell on the worksheet:

=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255)

The instance of the CELL function in this formula returns the full name of the worksheet, including the filename and file path. The use of the FIND function results in the stripping out of everything except the worksheet name.

Note the use of a cell reference (A1) in each instance of the CELL function. This forces the CELL function to return the name of the worksheet that contains the cell reference; without it, you will get the same result (the first worksheet) for each instance of the formula.

You should also know that the formula will not return valid results if you use it in a new workbook—one that hasn’t been saved. You need to save the workbook so it actually has a name that can be returned by the CELL function successfully. It also will not work properly if the workbook or worksheet name contains a right bracket character (“]”). In that case, you’ll want to use one of the other solutions discussed in this tip.

If you prefer to use a user-defined function, you can try something simple, like this function:

Function TabName1() As String Application.Volatile TabName1 = ActiveSheet.Name End Function

This function won’t provide the desired outcome, however, because it always returns the name of the active worksheet. That means that if you have the function called on each of the sheets in your workbook, it will always return the name of the active sheet on each of those worksheets, instead of the name of the sheet on which the function is used. The following function provides better results:

Function TabName2() As String Application.Volatile TabName2 = Application.Caller.Parent.Name End Function

If you think you’ll want to use the function to refer to a worksheet name elsewhere in the workbook, then this function will work better for you:

ExcelTips 2008 Page 261

Page 275: Excel tips 2008

Formula Tips

Function TabName3(cell As Range) TabName3 = cell.Worksheet.Name End Function

This version of the function requires that you provide a cell reference—any cell reference—to a cell on the worksheet whose name you want to use.

Of course, if you would rather not use a user-defined function, you could simply create a macro that would stuff the name of each worksheet tab into the same cell in each worksheet. For instance, the following macro steps through each of the worksheets in the workbook and places the name of each worksheet into cell A1.

Sub TabName4() For J = 1 To ActiveWorkbook.Sheets.Count Sheets(J).Cells(1, 1).Value = Sheets(J).Name Next End Sub

You should note that this approach is not dynamic (it needs to be rerun each time you change worksheet names or add new worksheets). It also overwrites anything that is in cell A1. (If you want the worksheet names placed in a different cell on each worksheet, change the values used in the Cells collection.)

(Thanks to Winston Snyder, Andrija Vrcan, Kirk Mays, Steve Aprahamian, Scott Huish, Russell Hendel, Becca Wemhoff, Nick Bafaloukos, Daniel Houle, Mark Farrell, Tore Softing, Mark Rotchell, Graeme Wiltsher, Anita Bouman-Eijs, Jean Michel Soupe, Jim Autrey, Trevor Bundy, Michael Cutler, Bill Foust, Aidan Heritage, Lydia North, Matt Sullivan, Dave Unger, Eddie Looby, and Nick Stafford for contributing to this tip.)

DETERMINING IF A VALUE IS OUT OF LIMITS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jennifer has two numbers that she needs to compare in a formula. If the second number is within 5% (plus or minus) of the first number, it is considered within limits. If the second number is outside of this range, then she needs the formula to return something such as "out of limits."

There are a number of different ways you could approach your formula. Let’s assume that your first number is in cell A1 and that the number you want to compare to it is in cell B1. One method is to use the IF function to do your testing:

=IF((A1-B1)>(A1*0.05),"out of limits", IF((B1-A1)>(A1*0.05),"out of limits", "within limits"))

ExcelTips 2008 Page 262

Page 276: Excel tips 2008

Formula Tips

This works fine, but the formula is a bit long. You can add the OR function to your formula to make it quite a bit shorter:

=IF(OR(B1<A1*0.95,B1>A1*1.05),"out of limits","within limits")

You could make the formula shorter still by skipping the OR function and simply doing a comparison on the absolute difference between the values:

=IF(ABS((B1-A1)/A1)<=0.05,"within limits","out of limits")

Since there is division happening in this formula, it is possible that you could get an error if the value in A1 is 0. To avoid this potential problem, the formula should be modified slightly:

=IF(A1=0,"unknown",IF(ABS((B1-A1)/A1)<=0.05, "within limits","out of limits"))

If the requirement is for the values to be “within 5% of each other,” the calculation is slightly more complex:

=IF(ABS(B1-A1)/MAX(ABS(B1),ABS(A1))>0.05, "out of limits","within limits")

In this case, the MAX function is used to determine the larger of the two values in A1 and B1. It must test the absolute values of A1 and B1 because the MAX function returns the value nearest to zero if both numbers are negative.

(Thanks to Andrew Gray, Abhay Jain, Jim Clark, John Nolan, Andrija Vrcan, Kirk Mays, Barry Dysert, Steve Aprahamian, James Snader, Attila Molnar, Scott Huish, Charlie O’Neill, Bobby Saxon, Steven Basford, Benazir Ibrahim, Russell Hendel, Peter Smith, John Cross, Adrian Fielden, John Rose, Henric Bladh, Joe Edmiston, Nick Bafaloukos, Andrew Coombe, James Cruise, Bert Neuenschwander, Mark Mace, Dave Richardson, Jason Friedman, Dave Boggess, Paul Podbielski, Bryan Schulze, Dan Parker, Hans Lindberg, Anita Bouman-Eijs, Jan Talmon, Shaun Endersby, Nick Stafford, Karel Geesteranus, and Jerrold Dolins for contributing to this tip.)

SEARCHING FOR A VALUE USING A FUNCTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Thor wonders if there is a way to perform a lookup without having to specify a specific column or row and having the result be the address of the cell at which the value is found. For instance, he wants to look up a value (such as 345 or "my text") and have the function search all the cells in all the worksheets in the workbook and return the full address of the cell in which the value was found.

ExcelTips 2008 Page 263

Page 277: Excel tips 2008

Formula Tips

The approach you use will be dictated by the range you want to search. If you want to search on the same worksheet on which you want the answer displayed, then you can use a formula, such as the following:

=ADDRESS(MAX(ROW(1:5)*(A1:E5="my text")), MAX(COLUMN(A1:E1)*(A1:E5="my text")),4)

This should be entered as an array formula (press CTRL+SHIFT+ENTER), and it only searches in the range A1:E5. You can, if desired, change the range by adjusting the formula appropriately.

A larger search area would be to look at an entire worksheet. This can still be done using a array formula, such as the following:

=ADDRESS(MAX(ROW(Sheet1!1:65000)*(IF(Sheet1!1:65000=$A$1,1,0))), MAX(COLUMN(Sheet1!$1:$65000)*IF(Sheet1!1:65000=$A$1,1,0)))

The formula assumes that what you are looking for is stored in cell A1. You should change the Sheet1 designation to the name of whatever worksheet you want searched.

If you want to search a wider range, such as all the worksheets in a workbook, then the best solution is to use a macro that calls upon the Find function within Excel.

Function FindAddr(vValue As Variant) Dim wks As Worksheet Dim rCell As Range Dim bFound As Boolean bFound = False For Each wks In ActiveWorkbook.Worksheets With wks Set rCell = .Cells.Find _ (What:=vValue, After:=.Cells(1), _ LookIn:=xlValues, LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not rCell Is Nothing Then bFound = True Exit For End If End With Next If bFound Then FindAddr = wks.Name & "!" & _ rCell.Address(False, False) Else FindAddr = "Not Found" End If Set wks = Nothing Set rCell = Nothing

ExcelTips 2008 Page 264

Page 278: Excel tips 2008

Formula Tips

End Function

This function is designed to be called from another macro, which passes it whatever should be searched for in the vValue parameter. The function returns either the full address (including worksheet name) of the first match, or it returns “Not Found” if there was no match.

(Thanks to Andrija Vrcan Andre Croteau, Steve Aprahamian, Benazir Ibrahim, and Tim Cantley for contributing to this tip.)

CALCULATING FUTURE WORKDAYS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Using Excel to calculate a date in the future is rather easy. If you have a cell (such as C3) that contains a starting date, you can simply use a formula such as the following in a different cell:

=C3 + 3

If you format the cell with the formula as a date, it will be three days in the future.

When you want to calculate workdays, the task gets trickier. For instance, you only want to return a date that is between Monday and Friday. If the starting date was a Thursday, this means the return date should be Monday, even though Sunday is the real day that is three days hence.

One quick way to figure a date three workdays in the future is to use the CHOOSE worksheet function. For instance, let’s say you have the issue date for a document, and you store that date in cell B5. If you want cell B6 to show a date three workdays later, then you would place the following formula in cell B6 and make sure it is formatted as a date:

=B5 + CHOOSE(WEEKDAY(B5), 3, 3, 3, 5, 5, 5, 4)

This formula assumes that workdays are Monday through Friday. You can tinker with it to pick a different five-day workweek, if desired.

If you also want your formula to take holidays into account, then you must get a bit more creative. For these instances you can use the WORKDAY function, which is included as part of the Analysis ToolPak add-in. This means that you must make sure the Analysis ToolPak add-in is loaded before you can use WORKDAY. You can check if it is loaded by choosing Add-Ins from the Tools menu. Once the add-in is loaded, you could use the following formula in cell B6 to calculate the target date:

=WORKDAY(B5,3)

ExcelTips 2008 Page 265

Page 279: Excel tips 2008

Formula Tips

After you format the cell as a date, it will show the date three workdays in the future. To include holidays, the simplest way is to set up your holidays in the worksheet. For instance, you might put your company holidays in the worksheet in cells K4 through K10. Then, select the cells and give them a name, such as Holidays. You can now use your holiday rante in the WORKDAY function. Change the formula in cell B6 so it looks like this:

=WORKDAY(B5,3,Holidays)

Now the function will always take your holidays into account when returning a date three workdays in the future.

REVERSING NAMES IN PLACE Applies to Excel 97, 2000, 2002, 2003, and 2007

George often has to work with data provided by other people. In working with this data he may need to convert a name, say Joe Bloggs, so that the last name is first, as in Bloggs, Joe. George understands that he can use a formula to do the name reversal, but he needs to do it in the same cell in which the name resides. He wonders if there is a built-in command that will perform this task.

No, there isn’t a built-in command to do it. You can, however, create a macro that will do the switching for you. This macro could then be assigned to a shortcut key or placed on a toolbar so it can be easily accessed. Here’s a simple macro that will do the switching:

Sub ReverseNames() Dim x As Integer Dim sCell As String Dim sLast As String Dim sFirst As String Dim rCell As Range For Each rCell In Selection sCell = rCell.Value x = InStr(sCell, " ") If x > 0 Then sFirst = Left(sCell, x - 1) sLast = Mid(sCell, x + 1) rCell.Value = sLast & ", " & sFirst End If Next Set rCell = Nothing End Sub

To use the macro, just select the range of cells you want to affect and then run it. The macro searches for a space within the cell and considers everything in front of the space to be the first

ExcelTips 2008 Page 266

Page 280: Excel tips 2008

Formula Tips

name and everything after the space to be the last name. These two elements are reversed, a comma put between them, and stuffed back into the cell.

(Thanks to Pranav Lunavat, Steve Aprahamian, Hong Maa, Russell Hendel, and Adrian Fielden for contributing to this tip.)

CELL ADDRESS OF A MAXIMUM VALUE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Barry has a worksheet with 65,000 rows. They are unsorted and must remain unsorted. He can use the MAX function on the column and get the maximum value in that column. However, he also wants to know the address of the first cell in the column that contains this maximum value.

There are a number of ways that you can determine the address of the maximum value. One way is to use the ADDRESS function in conjunction with the MAX function, in the following manner:

=ADDRESS(MATCH(MAX(A:A),A:A,0),1,4)

The MATCH function is used to find where in the range (column A) the maximum value resides, and then the ADDRESS function returns the address of that location. A shorter version of the macro leaves off the ADDRESS function, instead being “hardwired” to return an address in column A:

="A"&MATCH(MAX(A:A),A:A,0)

Still another way to get the desired address is with a formula such as this:

=CELL("ADDRESS",INDEX(A:A,MATCH(MAX(A:A),A:A,0)))

This formula uses the CELL function, in conjunction with INDEX, to return the address of the cell that matches the maximum value in the column.

(Thanks to Wikus Heyman, Malcolm MacKillop, Andrija Vrcan, Steve Aprahamian, Somanath Viswan, Josephine Earl, Theo Claas, Chris Yu, Gordon Smith, Eric Oliveira, Bhavik Khatri, Pranav C Lunavat, Nick Stafford, Benazir Ibrahim, Becca Wemhoff, Rogerio Bras, Tore Softing, Nisha Kumari, Scott Huish, Roger Mason, Michael Platt, Adrian Fielden, John Vander Linden, John Hubbard, Dwaine Charbonneau, Russell Hendel, Stewart Kramp, Peter Atherton, Anita Duvall, Barry Kruse, and Trevor Bundy for contributing to this tip.)

ExcelTips 2008 Page 267

Page 281: Excel tips 2008

Formula Tips

FINDING COLUMNS OF A CERTAIN WIDTH

Applies to Excel 97, 2000, 2002, 2003, and 2007

Howard has a need to discover all the columns in a worksheet that are a given width. For instance, he needs to know which columns have a width of 3.6.

This can be done by using a macro. One of the properties your macro can access is the width of each column. This means that you can step through the columns and check those widths against the desired width (3.6) in the following manner:

Sub ListColumns() Dim dColWidth As Double Dim sMsg As String Dim x As Integer dColWidth = 3.6 sMsg = "" For x = 1 To ActiveSheet.Columns.Count If Columns(x).ColumnWidth = dColWidth Then sMsg = sMsg & vbCrLf & x End If Next If sMsg = "" Then sMsg = "There are no columns with" & _ vbCrLf & "a width of " & dColWidth Else sMsg = "The following columns have" & _ vbCrLf & "a width of " & dColWidth & _ ":" & vbCrLf & sMsg End If MsgBox sMsg End Sub

This macro displays a message box that lists the columns that match the desired width. The macro can be made more robust with some simple changes. For instance, the following example prompts the user for a column width, counts the number of matches, and even compensates if the worksheet is using R1C1 referencing mode.

Sub Find_ColumnWidth() Dim Col As Integer ' Column (loop variable) Dim ColsFound As Integer ' Columns Found Count Dim Desired_Width As Double ' Column Width To Find Dim OutStr As String ' Output String Dim Title As String ' Msgbox Title Dim I As Integer Dim S As String

ExcelTips 2008 Page 268

Page 282: Excel tips 2008

Formula Tips

' Find out column width wanted S = InputBox("Enter ColumnWidth to find ?", _ " Find ColumnWidth on " & ActiveSheet.Name) Desired_Width = Val(S) If Desired_Width = 0 Then Exit Sub ' Initialize Columns Found Count and Output String ColsFound = 0 OutStr = "" For Col = 1 To ActiveSheet.Columns.Count If Columns(Col).ColumnWidth = Desired_Width Then ColsFound = ColsFound + 1 If Application.ReferenceStyle = 1 Then ' Using "A1" format S = Cells(1, Col).Address(ReferenceStyle:=xlA1) S = Mid(S, 2, Len(S) - 3) Else ' Using "R1C1" format S = Trim(Str(Col)) End If OutStr = OutStr & S & vbCrLf End If Next ' Construct MsgBox Title string Title = "Width=" & Desired_Width _ & " on " & ColsFound & " column" _ & Left("s", - (ColsFound > 1)) & " " If ColsFound = 0 Then OutStr = "No matches found" End If MsgBox OutStr, vbOKOnly, Title End Sub

(Thanks to Steve Aprahamian, Dave Latham, Pranav Lunavat, Richard Raciborski, Trevor Bundy, and Russell Hendel for contributing to this tip.)

DETERMINING COMBINATIONS TO MAKE A TOTAL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Suppose you have a worksheet with three columns of data. The first column has in sequential order each letter of the alphabet, A through Z. The second column contains a number of

ExcelTips 2008 Page 269

Page 283: Excel tips 2008

Formula Tips

occurrences that correlates with the letter in the alphabet. The third column contains a number of hours that correlates with the letter in the alphabet.

What if you want to distribute, as evenly as possible, a combination of the alphabet letters into four groups based on the third column (hours)? For example, if the sum of all the hours for each letter of the alphabet is 4,000 hours, you want to come up with a combination that would segregate the alphabet so that each one of the four groups would have around 1,000 hours per group.

This is actually a well-known problem in the field of discrete mathematics. A variety of algorithms have been developed to provide solutions, and there are certain programming languages (such as LISP) that greatly facilitate creating tree structures that can “search” for optimal solutions.

In this case, however, a simple approach is best, and that involves using a macro. Let’s assume that you have your data in columns A through C. The following macro will analyze the range you specify and return a combination of values that fulfill your requirements.

Function DoDist(sRaw As Range, _ iTCol As Integer, _ iBuckets As Integer, _ iWanted As Integer, _ iRetCol As Integer) As String Dim lGTotal As Long Dim lPerBucket As Long Dim lCells() As Long Dim sRet() As String Dim lBk() As Long Dim sBk() As String Dim lTemp As Long Dim sTemp As String Dim J As Integer Dim K As Integer Dim L As Integer Application.Volatile ReDim lCells(sRaw.Rows.Count) ReDim sRet(sRaw.Rows.Count) ReDim lBk(iBuckets) ReDim sBk(iBuckets) lGTotal = 0 For J = 1 To sRaw.Rows.Count lCells(J) = sRaw(J, iTCol) lGTotal = lGTotal + lCells(J) sRet(J) = sRaw(J, iRetCol) Next J For J = 1 To sRaw.Rows.Count - 1 For K = J + 1 To sRaw.Rows.Count

ExcelTips 2008 Page 270

Page 284: Excel tips 2008

Formula Tips

If lCells(J) < lCells(K) Then lTemp = lCells(J) lCells(J) = lCells(K) lCells(K) = lTemp sTemp = sRet(J) sRet(J) = sRet(K) sRet(K) = sTemp End If Next K Next J lPerBucket = lGTotal / iBuckets For J = 1 To sRaw.Rows.Count L = iBuckets For K = iBuckets To 1 Step -1 If lBk(K) <= lBk(L) Then L = K Next K lBk(L) = lBk(L) + lCells(J) sBk(L) = sBk(L) & sRet(J) & ", " Next J For J = 1 To iBuckets If Right(sBk(J), 2) = ", " Then sBk(J) = Left(sBk(J), Len(sBk(J)) - 2) End If sBk(J) = sBk(J) & " (" & lBk(J) & ")" Next J DoDist = sBk(iWanted) End Function

Notice that this function is passed five parameters. The first is the range that you want evaluated, the second is the offset of the column within that range that should be totaled, the third is the number of “buckets” you want to use in the evaluation, the fourth is the number of the bucket that you want to return, and the fifth is the offset of the column (in the specified range) that contains the values you want returned.

What the macro does is to grab all the values in the column you want totaled, and then sort them in descending order. These values, from largest to smallest, are then distributed among however many “buckets” you specified that there should be. The number is always added to the bucket that contains the smallest total. The string that is returned by the function represents the return values (whatever is in each cell of the column specified by the fifth parameter) and the total of the bucket.

For instance, if you wanted to evaluate the range A1:C:26, you wanted the distribution to be based on the values in the third column of the range (column C), you wanted there to be four buckets in the analysis, you wanted the third bucket returned, and you wanted to have the function return whatever is in column A of the range, then you would use the following to call the function:

ExcelTips 2008 Page 271

Page 285: Excel tips 2008

Formula Tips

=DoDist(A1:C26,3,4,3,1)

CONDENSING SEQUENTIAL VALUES TO A SINGLE ROW

Applies to Excel 97, 2000, 2002, 2003, and 2007

Rusty has a list of ZIP Codes in a column of a worksheet. He would like a way to "compress" the codes so that sequential ranges of values are on a single row. So, for instance, instead of 35013, 35014, and 35015 taking up three rows, they would appear on a single row as 35013-35015.

There are a couple of ways to go about this—with or without macros. On the “without macros” side of the fence, there are a number of different approaches, and all of them involve the use of additional columns to hold intermediate results.

For example, let’s assume that you have your data in column A, starting in cell A2, and that cell A1 is empty (it doesn’t even have header text in it). In this case you could enter the following formula in cell B2:

=IF(NOT(A2-A1=1),A2,IF(A3-A2=1,B1,A2))

Then, in cell C2, enter the following long formula:

=IF(NOT(A3-A2=1),IF(A2-A1=1,TEXT(B1,"00000") &" - "&TEXT(B2,"00000"),TEXT(A2,"00000")),"")

Now you can copy the formulas in cells B2:C2 down their respective columns. What you end up with in column C is the condensed series of ZIP Codes. You can copy these values, using Paste Special to ignore blank cells, to anyplace else you want.

If you want to use a macro approach, then there are no intermediate columns necessary. A macro can be written that essentially collapses the list of ZIP Codes in place. The following macro loops through whatever range of cells you selected and creates the condensed list:

Sub CombineValues() Dim rng As Range Dim rCell As Range Dim sNewArray() As String Dim x As Long Dim y As Long Dim sStart As String Dim sEnd As String Set rng = Selection sStart = rng.Cells(1)

ExcelTips 2008 Page 272

Page 286: Excel tips 2008

Formula Tips

sEnd = sStart y = 1 For x = 1 To rng.Count - 1 If rng.Cells(x + 1) - _ rng.Cells(x) > 1 Then 'End ReDim Preserve sNewArray(1 To y) If sStart = sEnd Then sNewArray(y) = sStart Else sNewArray(y) = sStart & "-" & sEnd End If sStart = rng.Cells(x + 1) y = y + 1 End If sEnd = rng.Cells(x + 1) ReDim Preserve sNewArray(1 To y) If sStart = sEnd Then sNewArray(y) = sStart Else sNewArray(y) = sStart & "-" & sEnd End If Next rng.ClearContents For x = 1 To y rng.Cells(x) = "'" & sNewArray(x) Next Set rng = Nothing Set rCell = Nothing End Sub

(Thanks to Steve Aprahamian, André Croteau, Benazir Ibrahim, Richard Raciborski, and Andrew Coombe for contributing to this tip.)

SUMMING DIGITS IN A VALUE Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a cell that contains a value, you may want to devise a way to add together all the digits in the value. For instance, if a cell contains the value 554, you might want to determine the sum of 5+5+4, which is 14.

There are several ways you can approach this task. (Doesn’t that always seem the way in Excel?) The first is to use a formula that relies on several functions:

=SUMPRODUCT(--MID(A1,ROW(INDIRECT("1:" & LEN(A1))),1))

ExcelTips 2008 Page 273

Page 287: Excel tips 2008

Formula Tips

This regular formula will sum the digits in any integer value (in cell A1) in a simple, elegant manner. This is not the only possible formula, however. The following is an array formula (terminated by pressing Ctrl+Shift+Enter) version of the same formula:

=SUM(1*MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1))

Either of these formulas work fine if the value in A1 is a positive whole number. If there are any non-digit characters in the number (such as a negative sign or a decimal point), then the formulas return a #VALUE! error.

These are not the only formulas possible for this type of calculation. You can find some other examples of formulas in the Microsoft Knowledge Base:

http://support.microsoft.com/?kbid=214053

You can also use a user-defined function to return the desired sum. The following macro steps through each digit in the referenced cell and calculates a total. This value is then returned to the user:

Function AddDigits(Number As Long) As Integer Dim i As Integer Dim Sum As Integer Dim sNumber As String sNumber = CStr(Number) For i = 1 To Len(sNumber) Sum = Sum + Mid(sNumber, i, 1) Next AddDigits = Sum End Function

To use this function, just use a formula such as =AddDigits(A1) in a cell. An even more compact user-defined function (invoked in the same manner) is the following:

Function AddDigits(ByVal N As Long) As Integer Do While N >= 1 AddDigits = AddDigits + N Mod 10 N = Int(N / 10) Loop End Function

Unlike the earlier macro, this version doesn’t convert the cell contents to a string in order to process it. Instead, it steps through each digit of the value, stripping off the last digit and adding it to the total.

ExcelTips 2008 Page 274

Page 288: Excel tips 2008

Formula Tips

GENERATING RANDOM STRINGS OF CHARACTERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Nancy is trying to get Excel to pick 50 "numbers" that each contain eight random characters. The characters can be either digits or letters (uppercase or lowercase).

If your random numbers were to really be numbers (digits only), then generating them would be easy. All you would need to do is use the RANDBETWEEN function (in the Analysis ToolPak) in this manner:

=RANDBETWEEN(10000000,99999999)

This is not what Nancy wants, however. Her random “numbers” can contain upper- and lowercase letters, as well. This becomes a bit stickier. There are, however, several approaches you can use.

One approach is to put all your possible characters into an individual cell, such as B7:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

Name this cell something snazzy, such as MySource. You could then use a formula such as the following to return the random string of characters:

=MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1) & MID(MySource,RANDBETWEEN(1,LEN(MySource)),1)

The formula is long; it has been broken into individual lines for clarity, but it is still a single formula. It concatenates eight characters pulled from the source you entered into cell B7.

Another approach is to create a table that contains all the characters you would want in your random text string. Start by placing the numbers 1 through 62 in a column, one number in each row. To the left of these numbers place your characters—A, B, C, D, etc. (This should be the same characters you placed in cell B7 in the previous technique.) Select both columns of the 62 rows and give it a name, such as MyTable. You can then use the following formula to generate the random characters:

=VLOOKUP(RANDBETWEEN(1,62),MyTable,2) & VLOOKUP(RANDBETWEEN(1,62),MyTable,2) & VLOOKUP(RANDBETWEEN(1,62),MyTable,2)

ExcelTips 2008 Page 275

Page 289: Excel tips 2008

Formula Tips

& VLOOKUP(RANDBETWEEN(1,62),MyTable,2) & VLOOKUP(RANDBETWEEN(1,62),MyTable,2) & VLOOKUP(RANDBETWEEN(1,62),MyTable,2) & VLOOKUP(RANDBETWEEN(1,62),MyTable,2) & VLOOKUP(RANDBETWEEN(1,62),MyTable,2)

Again, remember that this is a single formula, although it is a bit shorter than the previous formula.

Each of the approaches presented so far has one drawback: they are regenerated each time your worksheet is recalculated. Thus, it is hard to have a single generated random string that won’t change on a regular basis. The best way around this is to use a macro, but you don’t necessarily want to use a user-defined function. Why? Because it, too, would change its result every time the worksheet was recalculated. Instead, you need a macro that will put the random strings into your workbook starting a a specific cell location. The following is an example of such a macro:

Sub MakeRandom() Dim J As Integer Dim K As Integer Dim iTemp As Integer Dim sNumber As String Dim bOK As Boolean Range("D4").Activate Randomize For J = 1 To 50 sNumber = "" For K = 1 To 8 Do iTemp = Int((122 - 48 + 1) * Rnd + 48) Select Case iTemp Case 48 To 57, 65 To 90, 97 To 122 bOK = True Case Else bOK = False End Select Loop Until bOK bOK = False sNumber = sNumber & Chr(iTemp) Next K ActiveCell.Value = sNumber ActiveCell.Offset(1, 0).Select Next J End Sub

Run the macro, and whatever is in cells D4:D53 is overwritten by the random values. If you want the values written into a different location, change the Range statement near the beginning of the macro.

ExcelTips 2008 Page 276

Page 290: Excel tips 2008

Formula Tips

ExcelTips 2008 Page 277

(Thanks to Andrija Vrcan, Kirk Mays, Sandesh Badkas, Steve Aprahamian, Cian Cunningham, Dave Pettit, Dave Latham, Charlie O’Neill, Russell Hendel, Richard Raciborski, Stephen Barrett, Roger Mason, Adrian Fielden, Stafford Sims-Handcock, Misha Novakovic, Andrew Coombe, Frank Hixon, Vinay Pagaria, Michelle Unger, Benazir Ibrahim, and Jerrold Dolins for contributing to this tip.)

DEALING WITH CIRCULAR REFERENCES

Applies to Excel 97, 2000, 2002, 2003, and 2007

A circular reference is caused by including within a formula a reference to the cell storing the formula. It often occurs when the user selects the range for a function and inadvertently includes the formula location itself. For instance, if you stored the following formula in cell A3, the result is a circular reference:

= A1 + A2 + A3

If you try to enter a circular reference, Excel alerts you to the problem by displaying a dialog box. This dialog box requests you to click OK if the circular reference was a mistake or click Cancel if it was intentional. Unfortunately many users react without carefully reading the dialog box and press Cancel or press ESC just to get rid of the dialog box. Oops! The formula returns zero and the circular reference remains in your worksheet.

In the status bar, at the bottom of the screen, Excel displays Circular: (or Circular References:) and the address of the offending formula. Every help text I have seen indicates that the address of the circular reference is listed in the status bar. This is true only if the circular reference is on the current worksheet. The Circular notation is displayed any time a circular reference is present in any open workbook.

If you notice the Circular notation without an accompanying address, you can spend a lot of time working through every sheet of every open workbook until you see the address. There is a faster way to find circular references, regardless of where they are. When a circular reference is in existence, there is a circular reference toolbar available! Simply display the toolbar (using the same steps you use to display any toolbar) and use the drop-down list it contains to find a list of circular references. Click on one of them, and the cell with the reference is selected and displayed immediately.

The Circular Reference toolbar works great if you are using a version of Excel prior to Excel 2007, but there is no such toolbar in this version of the program. Instead, display the Formulats tab of the ribbon, click the down-arrow next to the Error Checking tool (in the Formula Auditing group), choose Circular References, and you will see a list of the circular references that Excel has detected. Click the one you want, and the cell that contains the circular reference is displayed.

Page 291: Excel tips 2008

PivotTable Tips

TEXT TRUNCATED IN PIVOTTABLE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Anil complained that when he created a PivotTable, some of the text in some of the source cells was truncated when it was placed in the PivotTable. He wondered if there were a way around this.

The first thing to do is make sure that the text is actually being truncated. When text is transferred to a cell in a PivotTable, it works much the same as text in the original worksheet. This means that the text is “cut off” when there is data in the cell to the right of the text cell. The full text is still there, but it cannot be displayed because there is not enough room to do so within the cell.

Testing has shown, however, that PivotTables will only transfer up to 255 characters from a source cell. Anything after that is truncated. This limit seems to be hard-coded into Excel, and there is no way around it that I could discover. The limit of 255 characters may seem arbitrary, and it is, indeed. I can only surmise that Microsoft needed to establish a length limit on text, and figured that 255 characters should be sufficient for most purposes.

SUPPRESSING ZERO VALUES IN PIVOTTABLES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Many people use the PivotTable feature of Excel to help analyze their data. One such person is Chris, who explained how he has approximately 40,000 lines of data which boil down to about 8,200 lines in a PivotTable. The problem is that only about 230 of those lines have non-zero values in them. Chris was looking for a way to suppress the PivotTable rows that contain zero balances.

ExcelTips 2008 Page 278

Page 292: Excel tips 2008

PivotTable Tips

ExcelTips 2008 Page 279

There are various ways that a solution can be approached. For instance, you could work with the original data and deleting zero balance rows before creating the PivotTable. If that is not possible, you can use AutoFilter on the data, before creating the PivotTable, that would show only rows that are not equal to zero. In other words, create a PivotTable using filtered data.

Another option is to use AutoFilter after the PivotTable is created. All you need to do is select the column to the immediate right of the PivotTable and then create the AutoFilter. Excel is smart enough to know that the AutoFilter should not apply to the blank column, but instead does its work on the rows that make up the PivotTable.

BOGGING DOWN WITH CALCULATED ITEMS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Torben wrote about a problem he was having with PivotTables in Excel. It seems that whenever he adds calculated items to the PivotTable, Excel takes a performance hit. If his dataset contains even a few thousand records, Excel even hangs.

PivotTables put a huge strain on Excel, as it slices, dices, and analyzes the data to create the table. The amount of strain experienced depends on many different factors, such as size of the dataset, the data in the PivotTable, etc. These factors can seemingly conspire against you, leaving you with a system that is sluggish at best.

There are ways, however, to change how Excel works with data to create the PivotTable. If you modify the settings that control this process, you may notice an improvement in Excel’s responsiveness. There is no guarantee that these changes will cure all PivotTable problems, but they offer a good place to start. The changes you can make are covered in a Knowledge Base article, located here:

http://support.microsoft.com/?kbid=273583

Read through the article and try some of the suggestions—you never know; it could make your PivotTables easier and faster to work with. (Even though the article specifically says it is applicable to Excel 2000, the concepts it suggests can be easily used with other versions of Excel.)

Page 293: Excel tips 2008

Sorting and Filtering Tips

SORTING A RANGE OF CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

Peter asked if it is possible to sort a range of cells, and just that range. In other words, not to sort entire rows or entire columns. The answer is a resounding “yes,” Excel allows you to do the sorting rather easily.

As an example, let’s assume you want to sort the cells in the range of C10:F40, based on the values in column D. To do this, follow these steps:

1. Select the range of cells. 2. Choose Sort from the Data menu. Excel displays the Sort dialog box. (To display this

dialog box in Excel 2007, display the Data tab of the ribbon and then click Sort.)

The Sort dialog box.

3. Using the Sort By drop down list, choose Column D. 4. Make sure the No Header Row radio button is selected. (In Excel 2007, make sure the

My Data Has Headers check box is cleared.) 5. Click on OK.

ExcelTips 2008 Page 280

Page 294: Excel tips 2008

Sorting and Filtering Tips

You can also sort by using the Sort Ascending or Sort Descending tools on the toolbar or, in Excel 2007, on the Data tab of the ribbon. The steps you follow are just a bit different:

1. Select the range of cells. 2. Press the Tab key to make sure that column D is selected. You can tell when it is

selected because one of the cells in column D will appear in white, rather than being shaded.

3. Click on Sort Ascending or Sort Descending.

Regardless of the technique you use,. only the range of selected cells are sorted. All other information in the data table remains unaffected.

SORTING DECIMAL VALUES Applies to Excel 97, 2000, 2002, 2003, and 2007

Bob often needs to construct tables that are keyed to titles in government regulations. The numbering of the regulations is in decimal form and this creates problems when he tries to sort them in order. Examples are 820.20, 820.25, 820.200, 820.250. Bob enters these as text, but they still come out sorted in a manner that he does not want. In all cases, Excel drops off the trailing zeros and sees “820.20” and “820.200” as the same thing; Bob is wondering what he can do.

First of all, it should be pointed out that if Excel is dropping the trailing zeroes, then the cells are not formatted as text. You’ll need to format the cells as text before you put anything in them, or else you’ll need to precede the entry with an apostrophe. In either case, the trailing zeroes should remain in place.

Another way to force the entries to text is to modify them in some way. For instance, you could enter “Reg 820.200” instead of “820.200.” Or you could replace the period after the 820 with a space or a dash. Any of these methods, and many more, would force the entry to be treated as text.

Even if you force the entry of information to text, that still won’t solve the sorting problem, however. Sort a bunch of these cells, and they will still come out in an order you don’t want:

820.190 820.2 820.20 820.200 820.201 820.25 820.27

The reason is because the sorting is done from left to right, and in this scheme “.20” will always come before “.200” which always comes before “.25.” The only way around this is to modify the

ExcelTips 2008 Page 281

Page 295: Excel tips 2008

Sorting and Filtering Tips

structure of the numbers so that (in this case) there are always three digits after the decimal point:

820.002 820.020 820.025 820.027 820.190 820.200 820.201

While this gives the proper sorting order, it does havoc to the original intent: to match the numbering used in the governmental numbering system. If you want to be true to that numbering scheme, the only solution is to use three columns for your numbering. The first column would be the government numbers, entered as text. The second column would be the part those numbers to the left of the decimal point, derived with a formula:

=LEFT(A1,FIND(".",A1)-1)

The third column would be the portion to the right of the decimal point, derived with this formula:

=RIGHT(A1,LEN(A1)-FIND(".",A1))

With the three columns in place, you can then do your sorting based on the contents of the second and third columns. After the numbers are sorted, you can hide the second and third columns, as desired.

(Thanks to Kirk Mays, Laura Dinsmoor, Ray Austin, Peter Quarrell, Steve Aprahamian, Ira Artman, Dave Pettit, Richard Raciborski, Paul McCulloch, Henk Berendsen, Nick Bafaloukos, Howard Strunk, Brian Bowling, Dave Boggess, Andrew Coombe, and Hector Polla for contributing to this tip.)

SORTING BY FILL COLOR Applies to Excel 97, 2000, 2002, 2003, and 2007

Chuck wrote about a need he has to sort records in a worksheet based on the fill color used in a cell. Excel provides no intrinsic function to perform such an action, but it is possible to create a user-defined function that will help with any sorting that needs to be done. Consider the following macro:

Function GetFillColor(rng As Range) As Long GetFillColor = rng.Interior.ColorIndex End Function

ExcelTips 2008 Page 282

Page 296: Excel tips 2008

Sorting and Filtering Tips

Assuming the fill colors are in the cells of column A, all you need to do is make sure there is an empty column B. Then place the following formula in cell B2 and copy it down for each record:

=GetFillColor(A2)

When you are done, column B will contain the index values of each fill color used in column A. You can then sort by column B, which has the result of grouping all the like fill colors together.

If you need to get more elaborate, for instance, if you need to sort in a particular order (yellow first, red second, green third, etc.), then you cannot rely solely on the fill color's index value. In such an instance you must rely on a different method of returning a color. Consider the following macro:

Function GetColor(rngIndex As Range, rngSource As Range) As Long Dim lngColor As Long Dim J As Integer Application.Volatile lngColor = rngSource.Interior.ColorIndex GetColor = 99 'Set to default color For J = 1 To rngIndex.Count If rngIndex(J).Interior.ColorIndex = lngColor Then GetColor = J End If Next J End Function

This macro works differently than the last one. It requires two ranges to work properly. The first range is basically a color table which indicates the order in which you want colors sorted. For instance, cells E1 through E9 could contain the nine colors you want to use for sorting, in the order that you want them sorted. You would then place the following formula in cell B2 and copy it down for each record:

=GetColor($E$1:$E$9,A2)

The result is that column B will contain the values 1 through 9, representing the colors in your color table. If the color in a cell does not have a corresponding color in the color table, then the function returns the value of 99. When you sort the records in your table, you end up with them sorted as you want.

ExcelTips 2008 Page 283

Page 297: Excel tips 2008

Sorting and Filtering Tips

FIXING ODD SORTING BEHAVIOR Applies to Excel 97, 2000, 2002, 2003, and 2007

Michael runs a karaoke company and uses Excel to create his song books. The worksheet contains three columns for song number, song title, and artist. Michael runs into odd behavior when sorting the song book by either artist or title.

For instance, when he sorts by artist the group 311 will come up in two different spots—four of their songs are placed right after the band 112 and before 702, and then it sorts the rest right after 3 of Hearts and before 38 Special. Then, when sorting by song, George Strait’s song "True" always ends up as the last song in the list.

This obviously isn’t want Michael wants to see happen when sorting. The reason it is happening, however, is due to the way that Excel interprets the information in each cell. When you enter information in a cell, Excel tries to parse that information and determine if it is a number, a date, or text. It just so happens that Excel is “guessing wrong” when it comes to some group and song titles.

When you enter the group 311, Excel considers that a number, so it treats it as a number. Similarly, when you enter the song title “True,” Excel considers that a Boolean value—a number. (It would do the same thing if you had a song named “False.”)

When performing a sorting, Excel first sorts by the data type and then within the data type. 112 and 702 are numbers. 3 of Hearts and 38 Special are text because they don’t consist of only digits. When sorting by artist, the group 311 shows up in two different places because the group name was parsed by Excel in some instances as a number and in other instances as text.

To understand how to correct the odd behavior, it is important to understand that the behavior isn’t really odd; it is the logic Excel uses. If you want different results, you have to work with your data to make sure it is not parsed incorrectly by Excel.

First, if you sort in ascending order, the values in your cells will be sorted in these data types:

• Numbers in increasing value (1, 2, 3, etc.) • Text in alphabetic order (a, b, c, etc.). If the text begins with a number (as in 38

Special), then the 3, as text, appears before the ABCs. • Logical values (False, True) • Error values (#DIV/0!, #N/A, etc.) • Blanks

If you sort in descending order, then the order is the reverse of what is shown here, except that blanks still appear as the last data type sorted.

ExcelTips 2008 Page 284

Page 298: Excel tips 2008

Sorting and Filtering Tips

You can better see the data types that Excel assigns to various cells by removing any explicit alignment in the cells. By default the text values will be left-justified, numbers right-justified, and Boolean and error values centered.

To get things to sort the way you want, you just need to make sure that all the cells in a column contain the same type of data. In the case of both artist and song title, this would be text. In the cells being sorted as numbers (like 311), edit the cell to place an apostrophe before the first digit in the number. This tells Excel you want the cell’s value treated as text. You can also do the same thing with “True.”

DETERMINING SORTING CRITERIA Applies to Excel 97, 2000, 2002, 2003, and 2007

Suppose that a co-worker gives you have a worksheet that has several hundred rows of data in 27 columns. Before you start working with the data, you might want to know if it has previously been sorted. Knowing the information may not only remove the need to resort the data, but will also give you an idea as to what your co-worker felt was the most important way to look at the data.

Unfortunately, Excel doesn’t have a built-in way to determine the sorting criteria used for a range of data. You could theoretically write a macro that would check each column and see if it were in ascending or descending order. This will tell you if that single column was sorted, but that doesn’t necessarily mean that the entire data table was sorted by that column—it could just be coincidence that the column is in sorted order, and the sort was done by some other column. The task of checking gets even trickier when you start considering secondary and tertiary sorts.

There is one thing you can try, however, to determine if a particular column is sorted and whether it is sorted in ascending or descending order. (Remember: this won’t tell you if the particular column was the primary column used for sorting, it will only tell you if the column is sorted.)

The idea behind the macro is to copy the contents of the column to a temporary worksheet, two times. For instance, if you want to check out column F, the macro copies column F to columns A and B on the temporary worksheet. The macro then sorts column B in ascending order and compares it to column A. If the sorted and unsorted columns are the same, then the original column was in ascending order. Then column B is sorted in descending order and the comparison done again. Again, if the columns are equal then the column is in descending order.

Sub TestIfSorted(i) Dim CColumn as Number Dim CSheet as String Dim FlagSort as String 'Identify Current Column and Current Sheet

ExcelTips 2008 Page 285

Page 299: Excel tips 2008

Sorting and Filtering Tips

CColumn = i CSheet = ActiveSheet.Name FlagSort = "" 'Add a temporary sheet to test for sorting Sheets.Add ActiveSheet.Name = "TempSort" 'Copy CURRENT column to Columns A,B in Current Sheet Sheets(CSheet).Select Columns(CColumn).Select Selection.Copy Sheets("TempSort").Select Range("A1").Select ActiveSheet.Paste Range("B1").Select ActiveSheet.Paste Application.CutCopyMode = False 'In Column C test for equality of Columns A/B 'If Sum in C1=0 then OK otherwise Col A<>Col B Range("B2").Select Selection.End(xlDown).Select Bottom = ActiveCell.Row Range(Cells(2, 3), Cells(Bottom, 3)).Select Selection.FormulaArray = "=IF(RC[-2]=RC[-1],0,1)" Range("C1").Select ActiveCell.FormulaR1C1 = "=SUM(R[1]C:R[6535]C)" 'Sort Column B--Ascending - See if c1=0 Columns("B:B").Select Selection.Sort Key1:=Range("B2"), Order1:=xlDescending, _ Header:=xlYes, OrderCustom:=1, MatchCase:=False, _ Orientation:=xlTopToBottom, DataOption1:=xlSortNormal If Cells(1, 3).Value = 0 Then FlagSort = "Ascending" 'Sort Column B--Descending - See if c1=0 Columns("B:B").Select Selection.Sort Key1:=Range("B2"), Order1:=xlAscending, _ Header:=xlYes, OrderCustom:=1, MatchCase:=False, _ Orientation:=xlTopToBottom, DataOption1:=xlSortNormal If Cells(1, 3).Value = 0 Then FlagSort = "Descending" If FlagSort = "Ascending" Then 'Color Header on original sheet yellow Sheets(CSheet).Cells(1, CColumn).Interior.ColorIndex = 36 End If If FlagSort = "Descending" Then 'Color Header on original sheet orange Sheets(CSheet).Cells(1, CColumn).Interior.ColorIndex = 44 End If

ExcelTips 2008 Page 286

Page 300: Excel tips 2008

Sorting and Filtering Tips

'Delete temporary sheet Sheets("TempSort").Select ActiveWindow.SelectedSheets.Delete End Sub

Once it is determined whether the original column was in ascending or descending order, then the first cell of the column in the original worksheet is set to yellow or orange, respectively. Finally, the temporary worksheet is deleted.

This macro could be modified so that it was called once for each column in a data table. Running the macro for an entire table wouldn’t take that long, but would provide a colorful representation as to whether individual columns are sorted in ascending or descending order.

Of course, any macro like this is not trivial, so it may just be easier for you to figure out how you want to sort the data, and then sort it that way from the get-go.

FILTERING TO A DATE RANGE IN THE PAST

Applies to Excel 97, 2000, 2002, 2003, and 2007

Bill has a data table with fifty columns and many, many records. One of the columns contain a record date, with dates that range over the past three years. Bill asked if there was a way to create a filter criteria to display only those records with dates between 91 and 98 days ago.

One solution is to add a new column to your data table that indicates if the record date is in the desired timeframe. Assuming the record date is in column A, the following would work:

=AND(TODAY()-A2>=91,TODAY()-A2<=98)

The result is either a True or False value, depending on the record date. You could then set up the filtering based on the value of the new column. (You can use AutoFilter for this purpose.) Only those records with a True in the column (those between 91 and 98 days old) would be displayed.

ExcelTips 2008 Page 287

Page 301: Excel tips 2008

Sorting and Filtering Tips

FILTERING FOR COMMENTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Robert has a worksheet that has comments included in various places. He wonders if it is possible to filter the rows in a data table so that only those rows that include comments in a particular column will be displayed.

The filtering capabilities of Excel don’t provide a way that you can automatically check for the presence of comments, but there are a couple of ways you can approach a solution. One possible solution is to follow these general steps:

1. Make a copy of the column that contains comments to be filtered. 2. Select the duplicate column. 3. Press F5 to display the Go To tab of the Find and Replace dialog box. 4. Click Special. Excel displays the Go To Special dialog box. 5. Click the Comments radio button and then press ENTER. Only those cells containing

comments are selected. 6. Type any number, character, or phrase not already present in the column. 7. Press CTRL+ENTER. All the selected cells (those with comments) should now contain

what you typed in step 6. 8. Use AutoFilter to display only those rows that contain whatever you typed in step 6.

If you prefer, you can create a user-defined function that will let you know if a particular cell has a comment associated with it. The following is a simple way to make such a determination:

Function CellHasComment(c As Range) Application.Volatile True CellHasComment = Not c.Comment Is Nothing End Function

Now you can use a formula such as the following within a worksheet:

=CellHasComment(B2)

When the formula is executed, it returns either True or False, depending on whether cell B2 has a comment or not. You can then use Excel’s filtering capabilities to display only those rows that have a True returned by the formula.

(Thanks to Andrija Vrcan, Steve Aprahamian, and Benazir Ibrahim for contributing to this tip.)

ExcelTips 2008 Page 288

Page 302: Excel tips 2008

Sorting and Filtering Tips

COUNTING FILTERED ROWS Applies to Excel 97, 2000, 2002, 2003, and 2007

John has applied a filter to the contents of one of his worksheets. He wants to determine the count of rows visible in the filtered data, but when he tries to count them using the COUNT function, Excel returns the overall number of rows, including those not displayed in the filtered list.

This is actually normal behavior—the COUNT function returns all the rows in a range, whether they are visible or not. If you want to determine the number of rows that meet the criteria of your filter, there are a variety of techniques you can use.

If you don’t need to get your count in a cell, then you can simply rely upon Excel to inform you of the count. When you apply a filter, the Excel status bar contains a count of how many rows are displayed by the filter. This count disappears as soon as you start editing other information in your worksheet, but it will reappear if you reapply the filter.

You could also select all the visible cells in a particular column and just look in the “totals” area of the status bar. By default Excel displays the sum of whatever cells you’ve selected, but you can right-click on this sum and instead instruct Excel to display a count of the selected cells.

If you want to use a formula to determine the row count, you could use the COUNTIF function. All you would need to do is make sure that the criteria specified in the function is the same criteria that you used in your filter. The drawback to this, of course, is that if you change your filter criteria you will also need to change the COUNTIF criteria to get an accurate count.

You can also use the SUBTOTAL function to determine the count of rows. For instance, if your filtered information was in A2:A500, you could use this formula to display a count of the rows displayed by the filter:

=SUBTOTAL(2,A2:A500)

The first parameter, 2, indicates that you want Excel to use the COUNT function to determine the formula result. If you change this parameter to 3 then SUBTOTAL will use COUNTA instead. Either way, SUBTOTAL only counts those rows displayed by the filter.

(Thanks to Steve Aprahamian, Kristen Toblesky, Jerrold Dolins, Gerard O’Brien, Julian Garcia, Alana Glewis, David Baty, Peter Smith, Peter Mackin, Martha Doukas, Beverly Bruce, Dave Theron, Bhavik Khatri, Glenn White, Carolyn Gaither, Richard Raciborski, Rob Land, Michelle McLean, Joe Edmiston, Valerie Robbins, Mark Brandon, Adam Matlock, Trish Ives, Dwaine Charbonneau, Barry Kruse, Christian Ritter, Chris Van Guyt, Nick Stafford, Luke Hannath, Justin Hughes, Hector Polla, Kishore Muktinutalapati, Laura Cutmore, Sarah Faust, and Benazir Ibrahim for contributing to this tip.)

ExcelTips 2008 Page 289

Page 303: Excel tips 2008

Sorting and Filtering Tips

ExcelTips 2008 Page 290

PERFORMING CALCULATIONS WHILE FILTERING

Applies to Excel 97, 2000, 2002, 2003, and 2007

Filtering a list means displaying only a part of it. You provide the criteria you want used, and then Excel displays only those list records that match the criteria. Filtering is especially useful if you have a large list and you want to work with only a subset of the records in the list. Other ExcelTips have described different ways you can create and apply filters to your worksheets.

When you are using the advanced filtering capabilities of Excel you can perform calculations during the filtering process. For instance, let’s assume you have a large inventory list in a worksheet, and you want to filter the list to show only those records that were in a particular department and that have a higher-than-average profit. This is easy to do by entering the following formulas at the indicated cells:

Cell Formula A2 ="W2*" B2 =I7>AVERAGE($I$7:$I$42)

This example provides for a text comparison related to the department number (in cell A2) and a comparison of the profit for the item (I7, which is a relative cell reference and therefore changes for each comparison) to the average profit for the entire inventory ($I$7:$I$42, which is an absolute reference and therefore does not change for each comparison). If an absolute reference had not been used for the AVERAGE function, the wrong results would have been generated by the filtering.

The result of the filtering, using the above criteria, is that only those records that had a profit greater than the average (the average in I7:I42) were displayed.

Page 304: Excel tips 2008

Comment Tips

EDITING COMMENTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Once a comment has been added to a cell in a worksheet, it is easy to edit the comment. All you need to do is right-click on a cell to which a comment is attached, then you can choose Edit Comment from the resulting Context menu. If you prefer, you can simply select the cell that has a comment attached and choose Edit Comment from the Insert menu or, in Excel 2007, click Edit Comment on the Review tab of the ribbon. Either method results in the insertion point appearing inside of the comment text box. You can then add more text or delete text, as desired.

Another way to edit comments is available if you have all the comments displayed on-screen, instead of just comment indicators. In this instance, you can edit a comment simply by positioning the insertion point within the text box and clicking on the mouse button. The comment’s text box becomes active and you can edit to your heart’s content.

ADDING A COMMENT TO MULTIPLE CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Keith notes that adding a comment to a cell is easy. He wonders if there is a way to insert the same comment into multiple cells at the same time.

The short answer is that there is no way to insert multiple comments at the same time. You can, however, copy a comment to multiple cells. Follow these steps:

1. Insert your comment in the first cell, as you normally would. 2. Select the commented cell and press CTRL+C. This copies the cell to the Clipboard. 3. Select the range of cells that you want to have the same comment.

ExcelTips 2008 Page 291

Page 305: Excel tips 2008

Comment Tips

4. Display the Paste Special dialog box. (Select Edit | Paste Special or, in Excel 2007, display the Home tab of the ribbon and click the down-arrow under the Paste tool at the left side of the ribbon. Select Paste Special from the resulting menu.)

5. Click the Comments radio button. 6. Click OK.

The result is that only the comment from the cell in step 2 is pasted to the cells you selected in step 3. If any of those cells already had comments, those comments are replaced with the one you are pasting.

If you really want to add the comment to all the cells at the same time, then the only way to do it is through a macro. The following example will prompt you for a comment and then add the comment to all the cells you’ve selected.

Sub InsertCommentsSelection() Dim sCmt As String Dim rCell As Range sCmt = InputBox( _ Prompt:="Enter Comment to Add" & vbCrLf & _ "Comment will be added to all cells in Selection", _ Title:="Comment to Add") If sCmt = "" Then MsgBox "No comment added" Else For Each rCell In Selection With rCell .ClearComments .AddComment .Comment.Text Text:=sCmt End With Next End If Set rCell = Nothing End Sub

(Thanks to Teresa Scanlon, Steve Aprahamian, Benazir Ibrahim, Richard Smolik, Dale Anderson, Curtis Izen, Shaun Endersby, and Chris Purtill for contributing to this tip.)

PASTING A COMMENT INTO YOUR WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to add comments to individual cells in a worksheet. I often use comments to included explanatory concepts, or to store alternative information to what is in the worksheet.

ExcelTips 2008 Page 292

Page 306: Excel tips 2008

Comment Tips

There have often been times when I’ve wanted to copy something from a comment and place it into a cell on the worksheet. These steps are helpful in this regard:

1. Right-click the cell whose comment you want to copy and paste into a cell. You’ll see a Context menu for the cell.

2. Choose Edit Comment from the Context menu. Excel displays the comment, with the insertion point in the comment balloon.

3. Select the text in the comment that you want to paste into a cell. Make sure you do not select the author text at the beginning of the comment or the paragraph mark at the end.

4. Use CTRL+X to cut the text or CTRL+C to copy the text to the Clipboard. 5. Select the cell into which you want to paste the comment. 6. If you want to paste the comment text as a formula, press the equal sign. 7. Press CTRL+V to paste the information to the cell.

If you performed step 6 to indicate you were creating a formula, press ENTER to finish the paste. Excel pastes your comment text into the cell. You can now delete the comment from the source cell (if desired) by right-clicking the cell and choosing Delete Comment.

COPYING COMMENTS TO CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

Hector has a large worksheet containing approximately 600 rows and 70 columns. Spread throughout these 43,000 cells are about 200 cells with comments. Hector wants to extract the comments and place them into cells to the right of the main body of the data table. If a comment, for instance, is attached to cell C43, then he’d like the text from that comment to end up in cell CC43 and the original comment to be deleted.

You might think that you could use Paste Special to perform the task, but that doesn’t work. If you copy the original cells and then use Edit | Paste Special | Comments, then only the comments are pasted to the target cells. They are still comments, and not text in cells, which goes against Hector’s goal.

The only way to handle this type of extraction is to use a macro. The following, when run on a selection of cells, will extract the comments, move the comment text, and then delete the original comment.

Sub CommentsToCells() Dim rCell As Excel.Range Dim rData As Excel.Range Dim sComment As String ' Horizontal displacement

ExcelTips 2008 Page 293

Page 307: Excel tips 2008

Comment Tips

Const iColOffset As Integer = 78 ' extract comments from selected range If TypeName(Selection) = "Range" Then Set rData = Intersect(Selection, ActiveSheet.UsedRange) For Each rCell In rData.Cells On Error Resume Next sComment = rCell.Comment.Text If Len(sComment) > 0 Then rCell.Offset(, iColOffset).Value = sComment rCell.Comment.Delete End If sComment = "" On Error GoTo 0 Next End If End Sub

The macro uses the iColOffset constant to specify how many cells to the right a comment’s text should be moved. In this case, the offset (78) is equal to three “alphabets” (26 * 3), so the text of a comment originally in column C will end up in column CC.

PLACING FORMULA ANSWERS IN A COMMENT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Bob asked if it is possible to write a formula and get the answer in a comment, instead of in a cell. The short answer is that no, you can’t do it with a formula. You can, however, do it with a macro. For instance, the following macro adds the contents of two cells (A1 and B1) and then sticks the result in a comment attached to cell C1:

Sub MakeComment() With Worksheets(1).Range("C1").AddComment .Visible = True .Text "Total of cell A1 plus cell B1 is equal to " & _ ([A1].Value) + ([B1].Value) End With End Sub

If you’d rather run the macro on a range of cells, then a different approach is necessary. The following macro loops thru all the cells in a selection. If the cell contains a formula, the macro puts the value (the formula’s result) in a comment attached to that cell.

Sub ValueToComment() Dim rCell As Range

ExcelTips 2008 Page 294

Page 308: Excel tips 2008

Comment Tips

For Each rCell In Selection With rCell If .HasFormula Then On Error Resume Next .Comment.Delete On Error GoTo 0 .AddComment .Comment.Text Text:=CStr(rCell.Value) End If End With Next Set rCell = Nothing End Sub

While looping through the cells in the selection, if one of the cells has a formula and an existing comment, then the comment is deleted and replaced with the new comment that contains the formula result. Afterwards the cell's value will display as well as a comment with the same number. Instead of CStr you could also use Format function to display the value in any way you might want.

You can also create a macro that will modify a comment whenever you update the contents of a particular cell. For instance, let’s say that every time someone made a change in cell C11, you wanted the result of whatever is in that cell to be placed into a comment attached to cell F15. The following macro does just that:

Private Sub Worksheet_Change(ByVal Target As Range) Dim sResult As String If Union(Target, Range("C11")).Address = Target.Address Then Application.EnableEvents = False Application.ScreenUpdating = False sResult = Target.Value Target.ClearContents With Range("F15") .ClearComments .AddComment .Comment.Text Text:=sResult End With Application.EnableEvents = True Application.ScreenUpdating = True End If End Sub

When someone enters a formula (or a value) into cell C11, the results of that formula (or the value itself) is placed into a comment that is attached to cell F15. Since this is an event-triggered macro, it needs to be entered in the code window for the worksheet on which it will function.

ExcelTips 2008 Page 295

Page 309: Excel tips 2008

Comment Tips

Finally, you may want to have your macro monitor an entire column. The following macro uses the Change event of a worksheet, just like the previous macro. It, however, only kicks into action if the change was made in column F, and only if a single cell in that column was changed.

Private Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub If Target.Column <> 6 Then Exit Sub Dim x As String Application.EnableEvents = False If Target.HasFormula Then x = Evaluate(Target.Formula) Else x = Target.Text End If Target.ClearComments If Target.Text = "" Then Application.EnableEvents = True Exit Sub End If Target.AddComment x Target = "" Application.EnableEvents = True End Sub

If the user makes a change to a single cell in column F, the macro grabs the result of what was entered and places it in a comment attached to that cell. The contents of the cell are then deleted.

LINKING COMMENTS TO MULTIPLE CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you insert a comment into a worksheet, that comment is associated with a single cell. There may be times when you want to have a single comment associated with two or more cells. Unfortunately, Excel doesn’t provide this capability—there is a strict one-to-one correspondence between comments and cells.

You can, however, use a workaround—create your own comments. You can do this using a text box to contain your comment, and then draw lines between the text box and whatever cells the comment applies to. If you normally want your comments hidden, then you will need to use a macro that takes care of making the text box and lines visible or invisible.

ExcelTips 2008 Page 296

Page 310: Excel tips 2008

Comment Tips

For instance, assume that you create a comment in a text box named Text Box 1. Further, assume that you have two lines leading from the text box to the cells to which the comment applies. The first line, named Line 1, leads to cell C15. The second line, named Line 2, leads to cell F7. You could add the following macro to the worksheet’s object:

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) Shapes("Text Box 1").Visible = False Shapes("Line 1").Visible = False Shapes("Line 2").Visible = False If Target.Address = "$C$15" Then Shapes("Text Box 1").Visible = True Shapes("Line 1").Visible = True End If If Target.Address = "$F$7" Then Shapes("Text Box 1").Visible = True Shapes("Line 2").Visible = True End If End Sub

Anytime a selection is made on the worksheet, the three objects are hidden. If cell C15 is selected, the textbox and the line appropriate line are made visible. Similarly, if cell F7 is selected, the textbox and its line are made visible.

FINDING AND REPLACING TEXT IN COMMENTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Gerry has a workbook containing 22 worksheets. Each worksheet has about 20 comments. Some of the comments make reference to a company division. He would like to do a mass search and replace of the comments to find each reference (for example, "ABC Division") and replace it with something else (for example, "XYZ subsidiary").

There is no way to do this without using a macro. The regular find and replace capabilities in Excel don’t allow you to find text within comments, but you can use macro commands. The following is a simple macro to do the replacing:

Sub ReplaceComments() Dim cmt As Comment Dim wks As Worksheet Dim sFind As String Dim sReplace As String Dim sCmt As String sFind = "ABC Division"

ExcelTips 2008 Page 297

Page 311: Excel tips 2008

Comment Tips

ExcelTips 2008 Page 298

sReplace = "XYZ subidiary" For Each wks In ActiveWorkbook.Worksheets For Each cmt In wks.Comments sCmt = cmt.Text If InStr(sCmt, sFind) <> 0 Then sCmt = Application.WorksheetFunction. _ Substitute(sCmt, sFind, sReplace) cmt.Text Text:=sCmt End If Next Next Set wks = Nothing Set cmt = Nothing End Sub

The key lines here are those that set the sFind and sReplace variables. You should set those to reflect what you are searching for and what you want it replaced with, respectively. The macro steps through each comment in each worksheet of the current workbook and makes the changes anywhere they are located.

(Thanks to Andrija Vrcan, Steve Aprahamian, and Mary Padilla for contributing to this tip.)

Page 312: Excel tips 2008

Date and Time Tips

HOW EXCEL STORES DATES AND TIMES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Internally, Excel stores a date or time as a number. The whole part of the number (the part to the left of the decimal point) represents the number of days since an arbitrary starting point (typically January 1, 1900). The decimal portion (the part to the right of the decimal point) represents the time for that date. These internal representations of dates and times are often referred to as serial numbers.

To see how this works, enter the number 23 in a cell. If you have not previously formatted the cell, Excel uses the General format, displaying the number simply as 23. If you later format this cell using a date format—m/d/yy, for instance—Excel changes the display to 1/23/00, or January 23, 1900.

The portion to the right of the decimal point represents a fractional portion of a day. Thus, a single second would be equal to approximately 0.00001157407, since that is equal to 1 (a day) divided by 86,400 (the number of seconds in a day).

Since Excel stores dates and times as serial numbers, you can do math on them. For instance, if you wanted to determine the number of days between two dates, or the amount of time between two times, simply subtract them from each other. The result is the number of days and fractions of days between the two.

CONVERTING TIME NOTATION TO DECIMAL NOTATION

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel internally stores date and time values as floating-point numbers. The portion of the number to the left of the decimal point represents days elapsed since either January 1, 1900 or 1904

ExcelTips 2008 Page 299

Page 313: Excel tips 2008

Date and Time Tips

(depending on how your copy of Excel is configured). The portion of the number to the right of the decimal point represents the portion of a full day represented by the date and time.

Knowing this, you can easily convert a number from its time notation to its decimal equivalent. For instance, if you have an elapsed time value that represents 8:30, you can easily convert it to 8.5 (eight and a half hours) by multiplying the time value by 24.

To give another example, let’s say that you have a beginning time in cell A3 and an ending time in cell B3. In cell C3 you place the following formula:

=B3 - A3

The result in cell C3 is the elapsed time, which is the difference between the beginning and ending times. In cell D3 you could then place the following formula:

= C3 * 24

The result in D3 is a decimal representation of the number of hours in cell C3. You can format the cell as you would any other number value so that it displays the number of decimal places desired. If you prefer to limit the number of decimal places in the result, right off the bat, you could instead use the following formula in cell D3:

=ROUNDUP(C3 * 24, 1)

This formula multiples C3 by 24 to convert to a decimal value, but then rounds the result to a single decimal place.

CHANGING EXCEL’S STARTING DATE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to choose which arbitrary date you use as the beginning point for serial numbers. In the PC world, this date is January 1, 1900. If you are working with Excel workbooks imported from the Macintosh environment, however, you will want to set the starting date to January 2, 1904—the date used on the Mac.

To set which of these two dates is used, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Calculation tab is selected.

ExcelTips 2008 Page 300

Page 314: Excel tips 2008

Date and Time Tips

The Calculation tab of the Options dialog box.

3. The 1904 Date System check box controls which dating system is used. If the check box is not selected, then the January 1, 1900 starting date is used; if it is selected, then January 2, 1904 is used.

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left of the dialog box. 3. Scroll through the available options until you see the section titled When Calculating

this Workbook.

ExcelTips 2008 Page 301

Page 315: Excel tips 2008

Date and Time Tips

The advanced options of the Excel Options dialog box.

4. The Use 1904 Date System check box controls which dating system is used. If the check box is not selected, then the January 1, 1900 starting date is used; if it is selected, then January 2, 1904 is used.

INSERTING THE CURRENT TIME WITH SECONDS

Applies to Excel 97, 2000, 2002, 2003, and 2007

As you have learned in other ExcelTips, you can use CTRL+: (that’s a colon) to enter the current time into a cell. The resulting cell value is equal to the hours and minutes of the current time. In other words, the seconds will always be zero.

If you want to insert the current time and have it include the seconds, the best way is to use a macro. You can then assign the macro to a keyboard shortcut or a toolbar button (or both) so it can be immediately popped into place. The following macro will do the trick nicely:

Sub TimeStamp() ActiveCell.Value = Time ActiveCell.NumberFormat = "h:mm:ss AM/PM" End Sub

Notice that the time is placed in the cell, and then the cell is formatted to show hours, minutes, and seconds.

ExcelTips 2008 Page 302

Page 316: Excel tips 2008

Date and Time Tips

ENTERING LARGE TIME VALUES Applies to Excel 97, 2000, 2002, 2003, and 2007

If you format a cell for elapsed time (using a custom display format of [h]:mm:ss), then Excel allows you to enter hours, minutes and seconds into that cell. For instance, you could simply enter 129:14:30 to signify 129 hours, 14 minutes, and 30 seconds. You run into a problem, however, if you try to enter very large time values into the cell. When you try to enter time values in excess of 10000 hours, as in 12721:52:45, then Excel won’t parse the entry as a time, but treats it as text.

The interesting thing is that when a cell is formatted for elapsed time using [h]:mm:ss, the cell can easily display elapsed times that have more than 10000 hours. Thus, you can sum a range of cells to result in a value more than 10000 hours, but you cannot enter a larger value.

Unfortunately, there seems to be no way around this in Excel. The best solution, however, might be to rethink how the data is entered. After all, 10000 hours is equal to 416 days and 16 hours—well over a year. You could easily create a column for entering days, and use another for partial days. A third column could then use a formula to return the elapsed hours based on the other two columns.

Another solution is to simply not rely on Excel to do the parsing of your input. If you have a huge number of hours to enter (such as 32315), then you could enter the following in the cell:

=32315/24

Excel maintains what you enter as a formula, but displays the proper number of hours, minutes, and seconds. If you want to get more precise, you can enter a fractional amount that represents the portion of an hour represented by your time. For instance, 37 minutes and 15 seconds is 0.620833 of an hour. Thus, you could enter the hours as follows:

=32315.620833/24

Of course, entering times in this manner can get tedious, particularly when you have calculate the fractional portion of an hour represented by minutes and seconds. To overcome this, you could create a custom function that allows you to enter hours, minutes, and seconds, and returns a value that is easily formatted using the elapsed time format. The following function will do the trick:

Public Function RealBigTime(hr As Double, _ min As Double, sec As Double) As Double Dim hr1 As Double Dim min1 As Double Dim sec1 As Double Application.Volatile hr1 = hr / 24

ExcelTips 2008 Page 303

Page 317: Excel tips 2008

Date and Time Tips

min1 = min / 24 / 60 sec1 = sec / 24 / 60 / 60 RealBigTime = hr1 + min1 + sec1 End Function

After creating the function, enter something like =RealBigTime(32341,30,45) in a cell. The result is a value that can be formatted with the elapsed time format to 32341:30:45.

USING EARLY DATES Applies to Excel 97, 2000, 2002, 2003, and 2007

There are three basic types of information that can be stored in a cell: numeric values, strings (text), and dates. In reality, dates are nothing more than numeric values, with the number being stored representing the number of days (and partial days for the time portion of a date) since January 1, 1900. This is a quick, handy way for Excel to store dates.

What happens, however, if you are doing genealogy or historical work and you need to keep track of dates that are earlier than 1/1/1900? There are essentially three ways you can approach this problem.

First, you can split up your dates. You could, for instance, include three columns for each date: one for day, one for month, and one for year. This, of course, will not allow you to change display formats for different date notations, but it will allow you to sort (using the column contents) as you desire, and to do rudimentary math on the dates. This approach to early dates can be the easiest to implement.

Another option is to use your own date notation for entering dates. For instance, if you wanted to enter the date for April 25, 1885, you could enter it as 18850425. This would be treated as a numeric value by Excel, which means you could do math based on the numbers. Because the notation has the year first, you could easily sort dates according to need. The only drawback to this method is that you cannot use Excel’s date formatting, and you must get used to the notational syntax.

Finally, you can either create your own macros to work with out-of-range dates, or you can use a third-party solution. One such solution is found at John Walkenbach’s site:

http://j-walk.com/ss/excel/files/xdate.htm

ExcelTips 2008 Page 304

Page 318: Excel tips 2008

Date and Time Tips

ROUNDING TIME Applies to Excel 97, 2000, 2002, 2003, and 2007

There may be instances when you need to round a time value. For instance, you may need to round some time to the nearest quarter-hour. One way to do this is to use the MROUND worksheet function, which is part of the Analysis ToolPak provided with Excel.

For example, let’s assume the unrounded time was in cell B7. You could then use the following formula to perform the rounding:

=MROUND(B7, TIME(0,15,0))

This formula relies, as well, on the use of the TIME worksheet function, which returns a time value (in this case, for 15 minutes).

If you don’t want to use the MROUND function (perhaps you don’t want to use the Analysis ToolPak), there is another way you can round to the nearest 15 minutes. The clue is to remember that 15 minutes is 1/96th of a day. So to round to the nearest 15 minutes, take the time value, multiply it by 96, round it, and then divide it by 96.

For example, if the time value you wish to round is in cell E5, the following formula does the rounding very nicely:

=ROUND(E5*96,0)/96

Notice that this formula uses the ROUND worksheet function, which is intrinsic to Excel and doesn’t require an add-in.

DATES WITH PERIODS Applies to Excel 97, 2000, 2002, 2003, and 2007

Lee prefers a date format that uses periods, such as 5.24.08. He wonders if there is a way to create such a format and if that format can be set as the default date format used by Excel.

Defining the date format in Excel is easy. Just follow these steps:

1. Select the range of cells you want to format. 2. Right-click the range to display a Context menu, from which you should choose Format

Cells. Excel displays the Format Cells dialog box. 3. Make sure the Number tab is displayed.

ExcelTips 2008 Page 305

Page 319: Excel tips 2008

Date and Time Tips

The Number tab of the Format Cells dialog box.

4. In the Category list, choose Custom. 5. In the Type box enter “m.d.yy” (without the quote marks). 6. Click OK.

That’s it; you now have a format set to display dates you want. If you want the format to be the default for all dates, then you are going to have to make a change in the Regional Settings of Windows itself. (Excel draws its default from these settings.) The exact way you do this varies depending on the version of Windows you are using, but in general there is a choice in the Windows Control Panel that allows you to specify regional settings. All you need to do is modify those settings to reflect the date format you want to use. The change will affect not only the display of numbers in Excel, but in other Windows-compliant programs, as well.

(Thanks to Shirley Simcock, Steve Aprahamian, Barry Dysert, Abhay Jain, Chris Purtill, Richard Raciborski, Saskia Jacobsen, Tom Hamilton, Sasha Frugone, Darrel Danielson, Joe Edmiston, Ira Artman, and Anil Malhotra for contributing to this tip.)

ExcelTips 2008 Page 306

Page 320: Excel tips 2008

Date and Time Tips

USING EXCEL FOR TIMING Applies to Excel 97, 2000, 2002, 2003, and 2007

You may want to use Excel to record the elapsed time for different events. There are two ways that this can be approached: either native, within Excel, or with a macro.

If you don’t want to use a macro, you can easily set up three columns for your timing. The first column can be used to record the start time, the second column the end time, and then the third column the elapsed time (calculated by using a formula that subtracts the start time from the end time). In order to record times, you select a cell in either the start time or end time columns and press CTRL+: (the colon). Excel enters the current time in that cell.

If you want to use a macro that simply returns the elapsed time, then you can use the following:

Public Sub TimeIt() Dim vStartTime As Date vStartTime = Time MsgBox Prompt:="Press the button to end the timing" & vbCrLf _ & "Timing started at " & Format(vStartTime, "hh:mm:ss"), _ Buttons:=vbOKOnly, _ Title:="Time Recording Macro" ActiveCell.Value = Time - vStartTime End Sub

This macro records a start time (in vStartTime), and then displays a message box. When you click on the message box button, the difference between the current time and the start time is stored in the current cell. (You need to make sure the current cell is formatted with one of the time formats.)

The above macro works very well for recording short events during which you don’t need to use Excel for other tasks. If you need to record longer events, then a different approach is in order. The following macros work in tandem. The first one records a start time; that is all it does. The second one uses that recorded time to calculate an elapsed time which is placed in the currently selected cell.

Global vStTime Sub StartTiming() vStTime = Time End Sub Sub EndTiming() ActiveCell.Value = Time - vStTime End Sub

ExcelTips 2008 Page 307

Page 321: Excel tips 2008

Date and Time Tips

You could easily assign these two macros to the Quick Access toolbar or to different toolbar buttons that would, respectively, start and stop the timing process.

WORKING WITH ELAPSED TIME Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to enter many things into a cell, including times. This leads some people to use Excel to help calculate elapsed times. For instance, you may have a column that contains a starting time, another that contains an ending time, and then use a third column to calculate the time between the beginning and ending time.

In such situations, you may be tempted to simply put the following as your formula in the cells of the third column:

=B2-A2

This will work fine, provided the time shown in B2 is always later than the time shown in A2. However, you will get erroneous results if the times do not fit this rigid stricture. What do you do if you are running operations around the clock, and it is just as likely that the value at A2 will be just before midnight and the value in B2 will be after midnight?

One solution is to make sure that you always enter dates with your times. If you do this, then B2 will always be later than A2. For many people, however, this is a bother. If you find yourself simply entering the time, then you are still up the creek.

If you enter your times without an AM/PM designation using a 12-hour clock, then you should use the following formula in the cells of the third column:

=IF(A2>B2,(B2+0.5)-A2,B2-A2)

This formula uses the IF function to determine if the beginning time is later than the ending time. If it is, then .5 (which is half a day, or 12 hours) is added to the ending time before the subtraction is done. If the beginning time is earlier then the ending time, then a normal subtraction operation is done.

If you use an AM/PM designation in your times, or you enter information using a 24-hour clock, then the formula must change just a bit. Now it should appear as follows:

=IF(A2>B2,(B2+1)-A2,B2-A2)

Now, instead of adding only half a day, you are adding a whole day (24 hours) to the ending time. This, again, provides the proper result.

ExcelTips 2008 Page 308

Page 322: Excel tips 2008

Date and Time Tips

It is interesting to note that in both of these instances, Excel allows you to add hours and minutes, if desired. While the above example is clean and simple, the following could also have been used:

=IF(A19>B19,(B19+"24:00")-A19,B19-A19)

Regardless of the formula you use, once it is entered you need to make sure the cell with the formula is formatted to properly show elapsed time. You do this by following these steps:

1. Display the Format Cells dialog box. (In versions of Excel prior to Excel 2007, choose Cells from the Format menu. In Excel 2007 press CTRL+1.)

The Format Cells dialog box.

2. In the Category list (left side) choose Time. 3. In the Type box, choose 37:30:55 as the type. 4. Click on OK.

Your cell now shows the correct elapsed hours, minutes, and seconds.

ExcelTips 2008 Page 309

Page 323: Excel tips 2008

Date and Time Tips

DISPLAYING NEGATIVE TIMES Applies to Excel 97, 2000, 2002, 2003, and 2007

Mike has a worksheet that contains some times. If he subtracts 6:33 from 6:21 he noticed that he doesn’t get a negative elapsed time, as in -:12. Instead he gets ############# in the cell. Mike is wondering how he can display the negative time difference properly?

The easiest way to solve this problem is to just change the date system used by the workbook. This may sound goofy, but if you use a 1900 date system (which is the default for Windows versions of Excel), then you get the ############# in the cell. If, instead, you change to the 1904 date system (which is the default for Mac versions of Excel) then you’ll see the correct negative elapsed time in your formula.

To change the date system in versions of Excel prior to Excel 2007, follow these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Calculation tab is selected.

The Calculation tab of the Options dialog box.

3. The 1904 Date System check box controls which dating system is used. If the check box is not selected, then the 1900 dating system is used; if it is selected, then the 1904 system is used.

ExcelTips 2008 Page 310

Page 324: Excel tips 2008

Date and Time Tips

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left side of the dialog box. 3. Scroll through the options until you see the section called When Calculating This

Workbook.

The Advanced options of the Excel Options dialog box.

4. The Use 1904 Date System check box controls which dating system is used, just as in earlier version of Excel.

If you prefer to not change the dating system used in the workbook (perhaps it may mess up some other date formulas you have in the worksheet), then the only thing you can do is to create a text-based version of the time differential using a formula such as the following:

=IF(B2-A2<0, "-" & TEXT(ABS(B2-A2),"hh:mm"), B2-A2)

If the difference between the two time values (in A2 and B2) is negative, then the formula concatenates a text value consisting of the minus sign and the absolute value of the difference between the times.

(Thanks to Andrija Vrcan, Steve Aprahamian, Venkat Annapareddy, Anita Duvall, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 311

Page 325: Excel tips 2008

Date and Time Tips

ENTERING DATES WITHOUT SEPARATORS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Different people enter data in different ways. When you enter information into a cell, Excel tries to figure out what type of information you are entering. If you enter a number such as 08242008, Excel assumes you are entering a numeric value, and treats it accordingly. What if the number you enter actually is a date, without any separators? Can Excel understand what you are entering?

Unfortunately Excel cannot. Why? Because you have given it no indication that this should be a date. (Excel keys on separators, not on numeric values.) If you or your data entry people cannot change their input habits so that separators are also entered, then you will need some sort of a workaround to convert the entered information to an actual date value.

Your first thought might be that you could use a custom format to display the information. Consider the following custom format:

##"/"##"/"####

This format would display the number 08152008 as 8/15/2008. The only problem is that it only changes the display of the number—if you want to use the date as a real Excel date, you cannot do so because you haven’t converted the value into something that Excel recognizes as a date.

If the values input were very consistent in their format, and if they were input as text instead of as numeric values, then there is an easy way you can convert them to dates. By very consistent, I mean that the input always used two digits for the month, two for the day, and four for the year. In addition, the cells containing the values must be formatted as text. In this instance, you can follow these steps:

1. Select the column of dates. 2. Make sure there is nothing in the column just to the right of the dates. 3. Choose Text to Columns from the Data menu. (In Excel 2007, select Text to Columns

from the Data tab of the ribbon.) Excel displays the Convert Text to Columns Wizard.

ExcelTips 2008 Page 312

Page 326: Excel tips 2008

Date and Time Tips

The Convert Text to Columns Wizard.

4. Select the Fixed Width option, then click on Next. 5. Click on Next again. 6. In the Column Data Format area, choose Date. 7. Select the range in the Destination box, then in the worksheet click the cell just to the

right of the first value you selected in step 1. 8. Click on Finish.

If all went well, Excel should have parsed the text values as dates, and you can delete the original column. If this did not work, then it means that either the original values were not formatted as text, or eight digits were not used to enter all the dates.

Another possible solution is to use a formula to convert the entered values into actual dates. The following is one such formula:

=DATE(RIGHT(A1,4),LEFT(A1,IF(LEN(A1) = 8,2,1)),LEFT(RIGHT(A1,6),2))

This formula assumes that the entered date (the one without separators) is in cell A1. The formula will work with either seven- or eight-digit dates.

If you prefer custom functions, you can create one in VBA that examines the data being passed, converts it to a date/time format, and then returns the result. The following function is very versatile in this regard; it will work with both American and European date formats:

ExcelTips 2008 Page 313

Page 327: Excel tips 2008

Date and Time Tips

Function DateTime(dblDateTime As Double, _ Optional bAmerican As Boolean = True) 'Converts Date and time "number" without 'delimiters into an excel serialdate (which 'can then be formatted with the Excel 'date/time formats) 'If optional argument is TRUE (or missing), 'function assumes value is of form: ' [m]mddyyyy.hhmm (leading "0" not required) 'If optional argument is FALSE, function 'assumes value is of form: ' [d]dmmyyyy.hhmm (leading "0" not required) Dim iYear As Integer Dim iMonth As Integer Dim iDay As Integer Dim iHour As Integer Dim iMin As Integer iYear = Int((dblDateTime / 10000 - _ Int(dblDateTime / 10000)) * 10000) iDay = Int((dblDateTime / 1000000 - _ Int(dblDateTime / 1000000)) * 100) iMonth = Int((dblDateTime / 1000000)) iHour = Int((dblDateTime - Int(dblDateTime)) * 100) iMin = Int((dblDateTime * 100 - _ Int(dblDateTime * 100)) * 100 + 0.5) If bAmerican Then DateTime = DateSerial(iYear, iMonth, iDay) Else DateTime = DateSerial(iYear, iDay, iMonth) End If DateTime = DateTime + (iHour + iMin / 60) / 24 End Function

This macro function assumes that the data being passed to it is a numeric value, as would normally happen when inputting dates without separators. (Refer back to the logic on this at the beginning of the tip.)

As you can tell, there are a number of workarounds, but none of them is as simple as just entering separators when entering the dates. If training yourself or your data input people to do this is difficult, you might consider setting up some data validation rules for the input cells. These rules can check to make sure that you are entering information using a specific format (such as a date with separators), and stop you if you are not. (How you create data validation rules has been covered in other issues of ExcelTips.)

ExcelTips 2008 Page 314

Page 328: Excel tips 2008

Date and Time Tips

ENTERING OR IMPORTING TIMES WITHOUT COLONS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you enter a time into a cell, Excel keys on the presence of the colon between the hour and minute portions of the time. Because of the position of the colon on the keyboard, however, entering a colon for each time value that you enter can slow you down—particularly if you have quite a few time values to enter.

For this reason, you may wonder if there is a way to skip entering the colon and either have them entered automatically or entered all at once. Entering them automatically takes a bit more doing, requiring the use of a macro, and will be covered shortly. Entering the colons all at once can be done with a formula, as in the following:

=TIMEVALUE(REPLACE(A1,3,0,":"))

This formula assumes that the time value (without a colon) is in cell A1, and that it is comprised of four digits. Thus, if cell A1 contains a value such as 1422, then the formula returns 14:22 as an actual time value. (You may need to format the cell as a time value.)

If your original entry cell might contain a time that uses only three digits, such as 813 instead of 0813, then you need to use a slightly different formula:

=TIME(LEFT(A1,LEN(A1)-2),RIGHT(A1,2),0)

If you prefer for the insertion of the colons to happen automatically, you can use a macro. You can create a macro that will examine a range of cells where you plan on adding dates to the worksheet, and then insert the colon in the entry. This is done by creating a macro that is triggered by the SheetChange event. The following macro is one such:

Private Sub Workbook_SheetChange(ByVal Sh As Object, _ ByVal Target As Excel.Range) Dim TimeStr As String On Error GoTo EndMacro If Application.Intersect(Target, Range("C7:D15")) Is Nothing Then Exit Sub End If If Target.Cells.Count > 1 Then Exit Sub End If If Target.Value = "" Then Exit Sub End If Application.EnableEvents = False With Target

ExcelTips 2008 Page 315

Page 329: Excel tips 2008

Date and Time Tips

If .HasFormula = False Then Select Case Len(.Value) Case 1 ' e.g., 1 = 00:01 AM TimeStr = "00:0" & .Value Case 2 ' e.g., 12 = 00:12 AM TimeStr = "00:" & .Value Case 3 ' e.g., 735 = 7:35 AM TimeStr = Left(.Value, 1) & ":" & _ Right(.Value, 2) Case 4 ' e.g., 1234 = 12:34 TimeStr = Left(.Value, 2) & ":" & _ Right(.Value, 2) Case Else Err.Raise 0 End Select .Value = TimeValue(TimeStr) End If End With Application.EnableEvents = True Exit Sub EndMacro: MsgBox "You did not enter a valid time" Application.EnableEvents = True ActiveCell.Offset(-1, 0).Select End Sub

The first thing the macro does is to check to see if the data that was just entered was in the range C7:D15. If it wasn’t, then the macro exits. It also checks to make sure that there is only a single cell selected and that the cell isn’t empty. If all these criteria are met,, then the macro checks the length of the value in the cell and pads it out with leading zeroes, as necessary. This macro is based on a macro found at Chip Pearson’s site, here:

http://cpearson.com/excel/DateTimeEntry.htm

MODIFYING DEFAULT YEAR FOR DATES

Applies to Excel 97, 2000, 2002, 2003, and 2007

When entering dates into a worksheet, Excel provides quite a bit of latitude for how you enter them. One area where latitude is granted is when it comes to including a year. If you include a year (such as 3/2/08), that is great. If you don’t include a year (such as 3/2), then Excel helpfully adds the current year to what you are entering.

ExcelTips 2008 Page 316

Page 330: Excel tips 2008

Date and Time Tips

Most of the time this isn’t a problem. It can be a problem, however, for those entering dates that “wrap around” to last year. For instance, many people enter dates for the previous month or two in their worksheets. In most months this isn’t a problem, because the past month or two is in the same year as the current month. It can be a problem during January and February, however, when you may be entering dates from November and December of the previous year.

One solution is to always enter the year when entering a date. It is unarguably faster to leave the year off during data entry and allow Excel to add it to your entry. Thus, it would be nice to come up with a way to enter dates during the first two months of the year and have the previous year’s year appended to them.

One way to handle this is to change the system date on your computer. Within Windows, decrement the system date by one year. Then, all dates that you enter will change to last year. This has ramifications in other programs, however, unless you remember to change the system date back. It also can mess up your data entry if, during the latter part of January and early February, you start entering dates from this year, and Excel automatically appends last year’s year to them.

Doing anything more complex necessarily involves the use of a macro. Consider the following example, which should be added to the code window for a worksheet:

Private Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub If Target = "" Then Exit Sub If Target.Column <> 1 Then Exit Sub If DateValue(Target) > Date Then Application.EnableEvents = False Target = DateAdd("yyyy", -1, Target) Application.EnableEvents = True End If End Sub

This macro automatically runs whenever there is a change in the worksheet. If the change being made is to a single cell in column A, and what is being entered is a date that is greater than today’s date, then a year is subtracted from what is being entered.

This works great, provided you are routinely entering dates that are within either the last year or the months so far in the current year. If you specifically add a far-future date (such as entering 6/11/09 on 3/2/08), then the year is still incremented by one. The macro could, of course, be modified to check to see if the date being entered is in the last two months of a year, and that the date is actually being entered during the first two months of a year, before doing the decrement of the year.

ExcelTips 2008 Page 317

Page 331: Excel tips 2008

Date and Time Tips

COUNTING DATES IN A RANGE Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a range of cells that are filled with random, non-sorted dates, you may want to figure out how many of those dates fall between a start date and an end date. For instance, if B1:B101 contains the random dates, cell E1 contains the start date, and cell E2 contains the end date, you may want to know what type of formula you can use in cell E4 to return the number of dates in B1:B101 that fall between E1 and E2.

There are actually several different ways you can arrive at a solution. The first, of course, would be to simply add a formula in each cell to the right of the dates in column B, and have that formula return a 1 if the date is between E1 and E2, or a 0 if not. You could then sum the column to get the desired count. You would use the following formula in each cell to the right of the dates:

=IF(AND(B1>=E$1,B1<=E$2),1,0)

This particular formula goes into cell C1, and can then be copied down to cells C2 through C101. Then, in cell E4, all you would need to do is use the following formula:

=SUM(C1:C101)

The drawback to this, of course, is that the additional values in C1:C101 can play havoc with the appearance of a carefully crafted worksheet. Fortunately there are ways to find the proper result without the need to use an intermediate value.

One way is to use an array formula. The following formula, placed in cell E4, will do the trick. All you need to do is remember to enter the formula using SHIFT+CTRL+ENTER. (This signifies to Excel that you are entering an array formula.)

=COUNT(IF((B1:B101>$E$1)*(B1:B101<$E$2),B1:B101))

If you prefer to not use an array formula, you can use the following standard COUNTIF-based formula in E4:

=-COUNT(B1:B101)+COUNTIF(B1:B101,">"&E1)+COUNTIF(B1:B101,"<"&E2)

When you enter this formula, Excel will assume that you are returning a date value, and will therefore helpfully format the cell as a date. All you need to do to correct this is to use Format | Cell to format the cell using something besides a date format, such as General.

The formula works by counting all dates that are after the early date plus all dates that are before the late date. This essentially counts all dates once and double-counts the desired selection. By subtracting the number of dates in the range (at the beginning of the formula), the formula effectively eliminates all but the desired result.

ExcelTips 2008 Page 318

Page 332: Excel tips 2008

Date and Time Tips

If you prefer, you can also use the DCOUNT function to return the desired count. This, however, is just a bit more involved. Unlike the earlier solutions, DCOUNT relies on the use of named ranges. Follow these steps:

1. Place a blank row at the top of your data, which pushes everything down by one cell. 2. With your dates now in cells B2:B102, select cell B1 and place a label, such as

MyDates, in the cell. 3. Format cell B1 as desired. 4. Select the entire range, including the label (cells B1:B102). 5. Using the Name Box (just above the row headers and to the left of the column headers)

define a name for the range. The name should be the same as the name you used in step 2 (MyDates).

6. In cells D1 and E1, place your label name (MyDates). 7. In cell D2 enter a greater-than sign and the lower date for your range of dates, as in

“>4/1/2002” (without the quote marks). 8. In cell E2 enter a less-than sign and the upper date for your range of dates, as in

“<6/1/2002” (without the quote marks). 9. In cell E4, enter the following formula:

=DCOUNT(MyDates,1,D1:E2)

The DCOUNT function uses the criteria you specified in D1:E2 to examine the data range defined as MyDates and return the count of cells that meets those criteria.

DAYS LEFT IN THE YEAR Applies to Excel 97, 2000, 2002, 2003, and 2007

Do you ever need to figure out how many days are left in the current year? Since Excel stores dates as serial numbers (making them easy to subtract), it is easy to put together a formula that will return the number of days left in the year:

=DATE(YEAR(C12),12,31)-C12

This formula assumes that the date you want to analyze is in cell C12. It uses the DATE function to calculate the serial number for the last day of the year (December 31), and then subtracts the serial number for the actual date. The result is the difference—the number of days—between the two dates.

This formula returns a value that is formatted as a date. You will need to use Format | Cells to format the cell to a regular numeric value instead of a date.

ExcelTips 2008 Page 319

Page 333: Excel tips 2008

Date and Time Tips

FORCING DATES FORWARD Applies to Excel 97, 2000, 2002, 2003, and 2007

Roger is keeping track of invoices in an Excel worksheet. All of the invoices need to be submitted with a due date of the 28th of the month, and Roger wondered if there was a way to force a date to always “jump forward” to the next instance of the 28th.

The cleanest way to force dates forward is to create a formula that will examine a date in a cell, and then force that date to the next desired date, such as the 28th. The following formula is a good one to start with:

=IF(DAY(A1)>28,DATE(YEAR(A1),MONTH(A1)+1,28),DATE(YEAR(A1),MONTH(A1),28))

This formula examines the date in cell A1. If the DAY value of the date is greater than 28, then the formula constructs and returns a date that is equal to the 28th of the next month. If it is less than or equal to 28, then the 28th of the current month is returned.

There is an even shorter way to render an acceptable formula, however—one that entirely gets rid of the IF function:

=DATE(YEAR(A1),MONTH(A1)+(DAY(A1)>28),28)

This uses the current year as the year, and the day is always 28. The month uses a Boolean calculation. If the day is greater than 28 then (Day(A1)>28) will be TRUE and will calculate as a 1, thereby adding 1 to the current month. If it is less than or equal to 28 it will be FALSE and calculate as a 0, just calculating the current month.

If you don't want to be "strict" giving some people only a day (9/27/2005 will give a due date of 9/28/2005), you could plan on giving them at least a week with the formula:

=DATE(YEAR(A1),MONTH(A1)+(DAY(A1)>21),28)

This would give the 28th of the current month for the 1st thru 21st, but for later dates it will jump to the 28th of the following month.

AUTOMATICALLY ADVANCING BY A MONTH

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jim has a need to advance the date in a particular cell by one month at midnight on the 14/15 of each month (00:00:00 on the 15th), and he wondered how it could be done.

ExcelTips 2008 Page 320

Page 334: Excel tips 2008

Date and Time Tips

As with many problems in Excel, the answer depends on the nature of the data involved and exactly what you want to do. If the date in the cell is today’s date, and you simply want to have the cell display the current month up through the 14th, and then next month after that, then you can use a formula such as the following:

=CHOOSE(IF(DAY(NOW())>14,MONTH(NOW())+1,MONTH(NOW())), "January","February","March","April","May","June", "July","August","September","October","November", "December","January")

This formula returns the name of a month, not a date. If you prefer to have a date returned, you can use this formula:

=IF(DAY(NOW())>14,DATEVALUE(IF(MONTH(NOW())=12,1, MONTH(NOW())+1) & "/" & DAY(NOW()) & "/" & IF(MONTH( NOW())=12,YEAR(NOW())+1,YEAR(NOW()))),NOW())

Both of these formulas account for the “end of year wrap-around” when you advance from December to January. A shorter version of this last formula can be created if you use the DATE function instead of the DATEVALUE function:

=DATE(YEAR(NOW()),MONTH(NOW())+((DAY(NOW())>14)*1),1)

This formula, unlike the DATEVALUE example, always returns a date that is the first day of any given month.

If you really want to advance the value of a particular date in a cell, then you must use a macro to do the task. Further, you must make sure that the macro only runs once a month, at a particular time on a particular day. For instance, if you wanted the macro to run at 00:00:00 on the 15th of each month, you would need to set up the macro so that it checked the date and time, and then ran at that particular date and time. You would also need to make sure that the workbook containing the macro was open over that date and time.

The following macro will fetch the date from a cell and increase it by a month. The macro assumes that you have a named range, DateCell, which refers to the cell to be updated.

Sub IncreaseMonth() Dim dDate As Date dDate = Range("DateCell").Value Range("DateCell").Value = _ DateSerial(Year(dDate), _ Month(dDate) + 1, Day(dDate)) End Sub

To make sure that the macro runs at the appropriate time, you would need another macro. The following macro is designed to be run whenever the workbook is opened:

Private Sub Workbook_Open()

ExcelTips 2008 Page 321

Page 335: Excel tips 2008

Date and Time Tips

If Day(Now) = 14 Then Application.OnTime ("23:59:59"), "IncreaseMonth" End If End Sub

Notice that this particular macro sets the OnTime method so that it runs the IncreaseMonth macro at 23:59:59 on the 14th. This date and time was chosen because it is easier to catch than is 00:00:00 on the 15th.

Remember that the IncreaseMonth macro will only run if you open the workbook on the 14th, and then leave the workbook open until the 15th.

EVERY SECOND TUESDAY Applies to Excel 97, 2000, 2002, 2003, and 2007

Roland is looking for a way to create a list of every second Tuesday through an entire year. Fortunately, there are many ways you can come up with every other Tuesday. The first is to simply use a formula to do the dates for you, as is done in these steps:

1. In cell A2, enter the date of the starting Tuesday. 2. In cell A3, enter the formula =A2+14. 2. Copy cell A3 down to as many cells as desired.

That’s it; the dates are all Tuesdays—every second Tuesday—because you’ve added 14 (the number of days in two weeks) to the previous Tuesday’s date. This approach has a benefit, as well: If you change the date in cell A2, then all the other dates change, as well. This allows you to have a dynamic set of dates, each date two weeks later than the previous date.

If you don’t need the list to be dynamic, then you can create a list of second-Tuesday dates in this manner:

1. In cell A2, enter the date of the starting Tuesday. 2. Select the range A2:A30. (You can actually pick any range you want; just make sure

you pick the range you want filled with dates, and cell A2 must be the first cell in the range.)

3. Choose Edit | Fill | Series. Excel displays the Series dialog box. (To display this dialog box in Excel 2007, display the Home tab of the ribbon and click the Fill tool in the Editing group.)

ExcelTips 2008 Page 322

Page 336: Excel tips 2008

Date and Time Tips

The Series dialog box.

4. Change the step value to 14. 5. Click OK.

The result is that Excel fills all the selected cells with dates that are 14 days apart from each other. Another way to display the same Series dialog box is to perform step 1 and then right-click on the Fill handle and drag it downward. When you release the mouse button, a Context menu appears. Choose Series, and the Series dialog box appears. You can then continue with steps 4 and 5.

If you’d rather not mess with the Series dialog box, there is a shortcut way of accomplishing the same task using the Fill handle:

1. In cell A2, enter the date of the starting Tuesday. 2. In cell A3, enter the date of the second Tuesday following (14 days later). 3. Select cells A2:A3. 4. Drag the Fill handle downward for as many cells as desired.

When you release the Fill handle, Excel fills those cells with dates that are patterned after the two dates in cells A2:A3. Since those dates are two weeks apart, the filled dates will also be two weeks apart.

IS DAYLIGHT SAVINGS TIME IN EFFECT?

Applies to Excel 97, 2000, 2002, 2003, and 2007

PJ wondered if there is a way, in a macro, to determine whether the system time on a machine is daylight savings time or not. The answer is that you can find it out, but it is not a trivial task.

ExcelTips 2008 Page 323

Page 337: Excel tips 2008

Date and Time Tips

If you are interested in an approach that is based on your local machine, then you need to make calls to the Windows API. Rather than re-invent the wheel, information on how to do this can be found in the detailed explanation by Chip Pearson at this site:

http://www.cpearson.com/excel/timezone.htm

If you are sure that your machine will have access to the Internet at the time that you need to know about Daylight Savings Time, you could also do some comparisons with information you get from the National Institutes of Standards and Technology (NIST) concerning the current time.

You can, over the Web, go to an NIST site that will return information about the current time. The URL to use is similar to this one:

http://nist.time.gov/timezone.cgi?Eastern/d/-5

In this case, the time returned will be in the Eastern time zone, which is five hours before the standard universal time. Using Excel’s Web Query capabilities, you can access the information returned by the URL and then compare it to the time on the local machine.

Public Sub DSTorST() Dim myWksht As Worksheet Dim sTime As Date, nTime As Date Dim sST As String, sDST As String, answer As String Dim absDif As Variant Dim myT As Integer Dim sURL As String Set myWksht = ActiveSheet sURL = "http://nist.time.gov/timezone.cgi?Eastern/d/-5" myT = 5 With myWksht.QueryTables.Add("URL;";sURL, myWksht.Range("A1")) .Refresh End With On Error Resume Next Application.ScreenUpdating = False sST = "Your computer system displays Standard Time" sDST = "Your computer system displays Daylight Savings Time" sTime = Now() sTime = TimeValue(sTime) nTime = Range("B3").Value absDif = Abs(sTime - nTime) If (absDif > (myT * 0.000694444) And _ WorksheetFunction.IsNumber(WorksheetFunction.Find _ ("Not Daylight", D11)) = True) Or (absDif <= _ (myT * 0.000694444) And WorksheetFunction.IsNumber _ (WorksheetFunction.Find("Not Daylight", D11)) = False) _ Then

ExcelTips 2008 Page 324

Page 338: Excel tips 2008

Date and Time Tips

answer = sST Else answer = sDST End If myWksht.UsedRange.Select Selection.Delete Application.ScreenUpdating = True MsgBox answer, , "System Time On Your Machine" End Sub

The macro compares the official time gathered by the query to the system time on the local machine. A tolerance of +/-5 minutes is assumed, as specified in the myT variable.

If the absolute difference between the two values is <= 5 min and NIST time is not DST or, if the difference is > 5 min and NIST time is DST, then the system time = Standard Time. Otherwise the system time = Daylight Savings Time.

(Thanks to Steve Aprahamian, Richard Raciborski, and Russell Hendel for contributing to this tip.)

CONVERTING EUROPEAN DATES TO US DATES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Linda asked if there is a formula that will convert a date shown in the European fashion of day/month/year to the US version of month/date/year. Truth be told, this may not be necessary. You see, Excel maintains dates, internally, as numeric values and then simply displays them using various formats. If the dates are truly dates—numeric values—in the worksheet, then you can simply change the format and the dates will be displayed in the way common to the US.

Of course, the date you see in a worksheet could be a text value, instead of a date value. You can test whether the date is really an Excel date or a text value by changing the format of the cell (or cells) to General. (Do this using the Number tab of the Format Cells dialog box.) If it is text, you’ll see no change in the display. If it is a date value, the date should change to a number that represents the number of days since whatever base date your system is using (typically January 1, 1900).

If your dates are truly date values, then simply change the format of the cell (or cells) to whatever date format you want to use. Again, this is done using the Number tab of the Format Cells dialog box.

If your dates are text values, then you will need to convert them to true date values (non-text) so that they can be formatted as just described. You can do this by using a formula to do the

ExcelTips 2008 Page 325

Page 339: Excel tips 2008

Date and Time Tips

conversion. If you have a text date in cell A1 in the format dd/mm/yyyy, then you can use the following formula:

=DATE(VALUE(RIGHT(A1,4)), VALUE(MID(A1,4,2)), VALUE(LEFT(A1,2)))

The result of this formula is a date serial number that is recognized and can be formatted by Excel.

Of course, it is possible that you have a bunch of mixed dates in your worksheet. Consider the following list of dates:

1/1/08 2/1/08 3/1/08 4/1/08 5/1/08 6/1/08 7/1/08 8/1/08 9/1/08 10/1/08 11/1/08 12/1/08 13/1/08 14/1/08 15/1/08 16/1/08 17/1/08

If these are entered into a worksheet, the first twelve dates (1/1/08 through 12/1/08) are parsed by Excel as January 1, 2008, through December 1, 2008. The next five dates are parsed as text since Excel doesn’t, by default, recognize that the dates are in d/m/y format. If you have a bunch of dates like this, you can quickly convert them to real dates without the use of any formulas. Just follow these steps:

1. Select all the cells containing the dates—both the date values and the text values. 2. Start the Text to Columns wizard. (In pre-Excel 2007, choose Text to Columns from the

Data menu. In Excel 2007, select Text to Columns from the Data tab of the ribbon.)

ExcelTips 2008 Page 326

Page 340: Excel tips 2008

Date and Time Tips

The first screen of the Text to Columns wizard.

3. Choose Fixed Width and click Next to proceed to step 2 of the wizard. 4. If you see any column break indicators in the dialog box, get rid of them by double-

clicking on them. You don’t want any such indicators because you don’t want Excel to think you have static breaking places for your data.

5. When all the column break indictors are gone, click Next to proceed to step 3 of the wizard.

6. In the Column Data Format section of the dialog, click the Date radio button. 7. Using the date format drop-down list, choose DMY. 8. Click Finish.

That’s it; your data is converted, in place, to the date values that Excel can work with.

(Thanks to Steve Aprahamian, Gavin Tameris, David Latham, Stephen Pike, Bert Neuenschwander, Roger Mason, Dan Parker, Bob Stoltz, and Chris Purtill for contributing to this tip.)

ExcelTips 2008 Page 327

Page 341: Excel tips 2008

Date and Time Tips

CONVERTING UNIX DATE/TIME STAMPS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you import information created by other computer programs, you may run into a situation where your data includes a date/time stamp created by UNIX. Once imported, you are then faced with the challenge of converting the date/time stamp to an Excel date/time format. Doing the conversion is rather easy, once you understand how both systems save their time.

Time stamps in UNIX are stored as an integer value representing the number of seconds since 1 January 1970. Further, time stamps are stored in GMT time, meaning there has been no adjustment to the stamp to reflect time zones or time-zone variations (such as Daylight Savings Time).

Excel, on the other hand, stores time stamps as a real number representing the number of days since 1 January 1900 (the default setting). The integer portion of the time stamp represents the number of full days, while the portion of the time stamp to the right of the decimal point represents the fractional portion of a day, which can be converted to hours, minutes, and seconds.

To do a straight conversion of a UNIX time stamp to the Excel system, all you need to do is use this formula:

=UnixTime / 86400 + 25569

In this example, UnixTime can be either a named cell containing the integer UNIX time stamp value, or it can be replaced with the actual integer value. Since the UNIX time stamp is stored as seconds, the division by 86400 is necessary to convert to days, which is used by Excel. (86400 is the number of seconds in a day.) You then add 25569, which is the number of days between 1 January 1900 and 1 January 1970. (It is the value returned if you use the =DATE(1970,1,1) function.)

Remember, that this does a straight conversion. You may still need to adjust for time zones. If the UNIX system recorded something occurring at 5:00 pm local time, you need to determine how many hours difference there is between you and GMT. If there happens to be four hours, then you need to adjust your conversion formula accordingly, as shown here:

=UnixTime / 86400 + 25569 - 4 / 24

If you are unsure of how your time zone relates to GMT, you can find the needed information here:

http://tycho.usno.navy.mil/zones.html

ExcelTips 2008 Page 328

Page 342: Excel tips 2008

Date and Time Tips

ExcelTips 2008 Page 329

CONVERTING UTC TIMES TO LOCAL TIMES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Brian lives in Australia and needs to convert a UTC time into his local time. Problem is, he doesn’t know how to go about doing it.

UTC is an abbreviation for Coordinated Universal Time. (Yes, I know it looks like the abbreviation letters are out of order. They are; this is why it isn’t an acronym. The abbreviation is—believe it or not—based on a political compromise.) UTC is equivalent to International Atomic Time with leap seconds added at irregular intervals to compensate for the Earth's slowing rotation. UTC is never out of synch with GMT (Greenwich Meridian Time) by more than nine tenths of a second, so the two (UTC and GMT) are virtually equivalent in common usage.

Because of this, all you need to do to convert from UTC to a local time is to figure out how many hours your time varies from GMT. There are any number of Websites you can visit to determine such information; the following is an example of one you can use. (Just click a city near you that you know is on the same time zone as you, then look at the resulting time to see how many hours different you are from GMT.)

http://www.timeanddate.com/worldclock/

If you are near Sydney, Australia, you can see that your local time is ten hours ahead of GMT. This means that to determine the local time if you know UTC, all you need to do is add ten hours to that time. If the UTC is in cell B3 in Excel’s date and time format, then you could use either of these formulas:

=B3+TIME(10,0,0) =B3+(10/24)

You should understand that these formulas don’t account of Daylight Savings Time. If you live in an area that implements some sort of time adjustment scheme (such as DST), then you will need to adjust your formulas accordingly. This means that if you are near Sydney you need to figure out when DST starts and ends, and if you are currently affected by DST you will need to add eleven hours to your UTC value.

You can find more information about adjusting local times to GMT (or, if you will, UTC) by visiting this tip:

http://excel.tips.net/T002185

(Thanks to Steve Aprahamian, Dave Pettit, Richard Taylor, and David A Coop for contributing to this tip.)

Page 343: Excel tips 2008

Graphics Tips

RESIZE GRAPHICS OUTSIDE OF EXCEL

Applies to Excel 97, 2000, 2002, 2003, and 2007

As has been mentioned in other issues of ExcelTips, after inserting a graphic in your worksheet you can easily resize it to almost any size you want. While this can be easy to do, resizing graphics in this manner may not be the best approach to working with your graphics.

I’ve heard reports of people who have problems printing worksheets that have lots of graphics in them. Invariably, the root of the problem is graphics that are resized in Excel. Even if the graphic is only resized a few percentage points, it can still cause problems. Solving these types of problems can take quite a bit of trial and error and therefore a lot of time.

When you insert a graphic in Excel and then resize it, the full, large-scale graphic is still embedded within your worksheet. This adds to the overall size of your workbook and means it may be slower or more difficult for Excel to process.

Excel is not a graphics program. (Duh!) It makes sense that specialized graphics programs would be more adept at resizing and cropping graphics than what you can get when you use Excel. Therefore, you should consider resizing your graphics in a graphics program before placing them in a worksheet. Doing so may result in a higher-quality graphic in your worksheet, and it certainly will result in a lesser processing burden on Excel (not to mention a smaller workbook size).

If you are having problems printing graphics within Excel, consider resizing and processing the graphics outside of Excel completely using a program such as Paint Shop Pro or PhotoShop. Chances are good that you can solve your problems sooner than you think.

ExcelTips 2008 Page 330

Page 344: Excel tips 2008

Graphics Tips

PUTTING A GRAPHIC IN A HEADER OR FOOTER

Applies to Excel 2002, 2003, and 2007

Excel users have, for years, asked if there is a way to place graphics in headers or footers. Various methods have been devised to do just that, as discussed in other ExcelTips. Users of Excel 2002 and Excel 2003 may be glad to know that it is even easier to add graphics to headers or footers. In fact, Microsoft added a direct capability to place graphics in headers or footers. Just follow these steps:

1. Choose Page Setup from the File menu. Excel displays the Page Setup dialog box. 2. Make sure the Header/Footer tab is selected.

The Header/Footer tab of the Page Setup dialog box.

3. Click on the Custom Header or Custom Footer button, depending on which one you want to change. Excel displays either the Header or Footer dialog box.

ExcelTips 2008 Page 331

Page 345: Excel tips 2008

Graphics Tips

The Footer dialog box.

4. Select the section of the header or footer (left, center, or right) in which you want your graphic to appear.

5. Click on the Insert Picture button. It is the second button from the right. Excel displays the Insert Picture dialog box.

6. Use the controls in the dialog box to locate and select the graphic you want in the header or footer.

7. Click on Insert. Excel places the graphic at the designated spot in the header or footer, displaying the code &[Picture] where the graphic will appear.

8. Make other changes to the header or footer, as desired. 9. Click on the OK button to close the Header or Footer dialog box. 10. Click on OK to close the Page Setup dialog box.

Excel 2007 still allows you to place graphics in headers or footers; the only thing different is the steps by which you display the Header or Footer dialog box: Display the Insert tab of the ribbon and then click either Header or Footer within the Header & Footer group. At this point you can continue to actually locate and insert the graphic, as indicated earlier in steps 4 through 10.

SPECIFYING AN ORDER FOR DRAWING OBJECTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you create drawing objects in Excel, each object is drawn on its own layer. This means all objects are independent and can be moved on top of other objects. This means that once you have drawn a number of different objects you can reorder them so that they appear in the order

ExcelTips 2008 Page 332

Page 346: Excel tips 2008

Graphics Tips

that you desire. You can do this by following these steps if you are using a version of Excel prior to Excel 2007:

1. Select the pointer tool (the arrow) from the Drawing toolbar. 2. Using the mouse, point to the shape whose order you want to change. Small square

boxes called handles appear at each corner in the shape. 3. Choose Order from the Draw menu on the toolbar. Excel displays a set of ordering

commands. 4. Choose the ordering command that represents what you want to do.

If you are using Excel 2007, then you need to follow these steps, instead:

1. Click on the shape whose order you want to change. Small square boxes called handles appear around the perimeter of the shape.

2. Display the Format tab of the ribbon. 3. In the Arrange group, choose the ordering command that represents what you want to

do.

You can also access the ordering commands by right-clicking on a drawing object and choosing Order from the resulting Context menu. In Excel 2007 you don’t need to select Order; the ordering commands are directly accessible from the Context menu. There are four different ordering commands:

• Bring to Front. This option places the selected object on top of the layer stack, so it appears in front of any other objects.

• Send to Back. This option moves the selected object behind any other drawing objects. • Bring Forward. This option simply moves the drawing object one step closer to the top

of the layer stack. • Send Backward. This option moves the drawing object one layer toward the bottom of

the layer stack.

INSERTING A WATERMARK BEHIND MERGED CELLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Tony asked if it was possible to insert a “watermark” type of permanent comment into a group of merged cells. The idea is for the comment to stay behind any entered text.

The short answer is that there is no way of doing this. Excel allows you to use a graphic as a background, but only for the worksheet as a whole, not for a range of cells. Even then, the

ExcelTips 2008 Page 333

Page 347: Excel tips 2008

Graphics Tips

background won’t print—which is why Excel calls it a “background” and not a “watermark.” (True watermarks are on physical paper, not on-screen.)

One possible solution—if you want your “comment” to be text instead of a graphic—is to use a text box. Create a text box that is the same size as your merged cells, and position it over those cells. Then, add your comment to the text box, as desired. Format the text box so the font is a light gray, the text box has no border, and the background is transparent.

The background being transparent is important, since you cannot position the text box “behind” the worksheet. The text box is on the drawing layer, which is always over the worksheet. You can arrange objects on the drawing layer, but you cannot move the drawing layer itself.

Now, if people use the Tab key to move into the merged cells, they can type things and it will appear in the cells. You may have to play with colors and appearance, because the gray text in the text box doesn’t go away when you enter text in the underlying cells.

You should know that if someone uses the mouse to click on the merged cells, they will, instead, select the text box. You can get around this by selecting the merged cells, making sure they aren’t protected, and then protecting the worksheet as a whole. By default, text boxes are protected, so they can’t be selected in a protected worksheet. Now, when someone clicks on the merged cell, it is the cell that is selected, not the text box—it cannot be selected in a protected worksheet.

SETTING DEFAULT ATTRIBUTES FOR LINES AND ARROWS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Glenn adds lines and arrows regularly to flowcharts that he creates in Excel. He is wondering if there is a way to set a default line weight, color, and arrowhead, as it gets tedious to change the attributes all the time.

Setting defaults for AutoShapes (such as lines and arrows) is quite easy in Excel. Just follow these steps:

1. Draw your line or arrow as you normally would. 2. Format the line or arrow so that it appears just as you want it to. 3. Right-click on the line or arrow. Excel displays a Context menu. 4. From the Context menu select the option that sets the shape settings as default.

Depending on your version of Excel, this option will be named something like Set AutoShape Defaults or Set Default Line.

That’s it. For the rest of your current Excel session your lines and arrows will be drawn using your desired formats.

ExcelTips 2008 Page 334

Page 348: Excel tips 2008

Graphics Tips

(Thanks to Jonathan Clipston, Richard Raciborski, and Stewart Sargent for contributing to this tip.)

USING WORDART IN EXCEL Applies to Excel 97, 2000, 2002, 2003, and 2007

WordArt is a program that allows you to treat text as a graphic. You can use the program to add special effects and flourishes to text, and then insert the text—as a graphic—in your worksheet. It is useful for creating special text elements such as logos, mastheads, or titles. Don’t confuse the program name (WordArt) with Microsoft Word; these are two entirely different programs, and you can use WordArt with Excel as easily as you can use it with Word.

How you access WordArt depends on the version of Excel you are using. Excel 97 includes WordArt 2.0, although it is not automatically installed when you install Word. You can tell if WordArt is installed by trying to access WordArt. If it is not installed, then you can run the Excel Setup program again and install WordArt on your system.

You access WordArt using either of these methods in Excel 97:

• Double-click on a graphic originally created with WordArt. • Choose Object from the Insert menu. You will see the Object dialog box. Choose

Microsoft WordArt 2.0 from the Object Type list and click on OK. You will see the WordArt dialog box.

When WordArt if running, you see the WordArt dialog box, and most of your Excel 97 menus and toolbars are hidden. When you are through using WordArt, you can exit the program simply by using the mouse to click somewhere else in your worksheet. (You can also press ESC to exit WordArt.)

Excel 2000 and later versions include a more integrated approach to WordArt. If you are using Excel 2000, Excel 2002, or Excel 2003 you should follow these steps:

1. Make sure the Drawing toolbar is displayed. 2. On the Drawing toolbar, click on the Insert WordArt tool. You then see the WordArt

Gallery.

ExcelTips 2008 Page 335

Page 349: Excel tips 2008

Graphics Tips

The WordArt Gallery.

3. Select a general appearance that you want used for your text, and then click on OK. You then see the Edit WordArt Text dialog box.

The Edit WordArt Text dialog box.

4. Enter the text you want used by WordArt, and click on OK.

ExcelTips 2008 Page 336

Page 350: Excel tips 2008

Graphics Tips

At this point, the WordArt graphic is created and added to your worksheet. You should also see the WordArt toolbar, which includes commands specific to working with WordArt objects. To hide the toolbar, simply click a different place in your document, so that the WordArt object isn’t selected.

To add WordArt to an Excel worksheet in Excel 2007, follow these steps:

1. Display the Insert tab of the ribbon.. 2. In the Text group, click the WordArt tool. You then see the WordArt Gallery. 3. Select a general appearance that you want used for your text, and then click on OK. You

then see some default text appear in the worksheet. 4. Enter the text you want used by WordArt, and click on OK.

It should be pointed out that the WordArt in Excel 2007 is markedly different than WordArt in earlier versions of Excel. In Excel 2007 WordArt consists of straight text, with different types of color, fill, and shadow formatting applied. In earlier versions there were actual changes made to the fonts and paths followed by the fonts; not so any more.

PICTURES IN AUTOSHAPES Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to format the appearance of the AutoShapes you place in a worksheet. If you display the Format AutoShape dialog box, you can change all sorts of colors, lines, fills, fonts, and other attributes of the AutoShape. One really nifty formatting feature is to place a picture within an AutoShape. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Create your AutoShape as you normally would. 2. Right-click the AutoShape. Excel displays a Context menu for the AutoShape. 3. Choose Format AutoShape from the Context menu. Excel displays the Format

AutoShape dialog box. (If Format AutoShape was not one of the options from the Context menu, then you didn’t right-click the AutoShape itself in step 2. Make sure that you right-click one of the lines that make up the AutoShape.)

4. Display the Colors and Lines tab.

ExcelTips 2008 Page 337

Page 351: Excel tips 2008

Graphics Tips

The Colors and Lines tab of the Format AutoShape dialog box.

5. Click the drop-down arrow for the Color drop-down list. 6. On the drop-down list, choose Fill Effects. Excel displays the Fill Effects dialog box. 7. Make sure the Picture tab is displayed.

ExcelTips 2008 Page 338

Page 352: Excel tips 2008

Graphics Tips

The Picture tab of the Fill Effects dialog box.

8. Use the controls in the dialog box to select a picture you want in the AutoShape. 9. Click OK as many times as necessary to close all the dialog boxes.

If you are using Excel 2007 you should follow these steps, instead:

1. Create your Shape as you normally would. 2. Right-click the Shape. Excel displays a Context menu for the Shape. 3. Choose Format Shape from the Context menu. Excel displays the Format Shape dialog

box. (If Format Shape was not one of the options from the Context menu, then you didn’t right-click the Shape itself in step 2. Make sure that you right-click one of the lines that make up the Shape.)

4. Make sure Fill is selected at the left of the dialog box. 5. Click the Picture or Texture Fill radio button. The options in the dialog box change to

reflect your choice, and the name of the dialog box changes from Format Shape to Format Picture.

ExcelTips 2008 Page 339

Page 353: Excel tips 2008

Graphics Tips

The Format Picture dialog box.

6. Use the controls in the dialog box to select a picture you want in the Shape. 7. Click Close.

The picture you selected in steps 8 or 6 should now appear in the background of the AutoShape. In most cases the AutoShape looks like a “mask” over the picture, which is a nice effect. You should also use this technique sparingly, as each picture you place in an AutoShape can greatly increase the size of your workbook.

ADDING TEXT TO AN AUTOSHAPE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Most people know that you can add textboxes to your worksheet, but don’t realize that you can actually add text to any AutoShape. Just follow these steps:

1. Add your AutoShape as you normally would.

ExcelTips 2008 Page 340

Page 354: Excel tips 2008

Graphics Tips

2. Right-click the new AutoShape. Excel displays a Context menu. 3. Choose Add Text from the Context menu. (In Excel 2007 choose Edit Text from the

Context menu.) An insertion point appears within the body of the AutoShape. 4. Type your desired text. 5. Click somewhere outside the boundaries of the AutoShape, such as within a cell of the

worksheet.

If you later resize your AutoShape, then the text within it is reformatted to fit the new dimensions of the shape. (This behavior is the same that occurs if you resize a textbox that contains text.)

PLACING TEXTBOX TEXT INTO A WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to place all sorts of graphic objects on your worksheet. One type of graphic object actually contains text—a textbox. If you have quite a few textboxes in a worksheet, you may be wondering if there is a way to extract the text from each textbox and place it in the worksheet itself.

There is no command to do this; you must instead use a macro. The following macro steps through each textbox in a worksheet and makes the desired extraction:

Sub ExtractText() Dim shp As Shape Dim sLoc As String For Each shp In ActiveSheet.Shapes With shp If Left(.Name, 8) = "Text Box" Then sLoc = .TopLeftCell.Address Do Until Range(sLoc) = "" sLoc = Range(sLoc).Offset(1, 0).Address Loop Range(sLoc) =.TextFrame.Characters.Text .Delete End If End With Next End Sub

Since Excel stores all graphic shapes in the Shapes collection, you can step through the collection and make a determination as to which shapes you want to work with. In this case, the

ExcelTips 2008 Page 341

Page 355: Excel tips 2008

Graphics Tips

first eight characters of the shape’s name is checked. Only if the name begins with “Text Box” does the macro consider the shape to be a text box from which text can be extracted.

Rather than check for the “Text Box” wording in the name, the macro could also check to see what type of shape is being considered. If you prefer to do this, then simply replace the test line (If Left…) with the following test line:

If shp.Type = msoTextBox Then

The sLoc variable is used to store the location of the textbox, which is contained in the .TopLeftCell property. A Do loop is then used to make sure that the cell pointed to by the address is empty. (This prevents any existing contents of the cell from being overwritten.) If it is not empty, then the address is “incremented” to the next cell in the column.

With the address of an empty cell determined, the text of the textbox is stored in the cell. The .Delete method is then used to get rid of the actual text box.

TAKING A PICTURE Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel provides a nifty little tool that allows you to create a picture from a range of cells, from a chart, or from another object in your worksheet. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Select the cells or other object you want a picture of. (If you select cells, they must be contiguous.)

2. Hold down the SHIFT key as you click the Edit menu. 3. Choose Copy Picture. Excel displays the Copy Picture dialog box.

The Copy Picture dialog box.

4. In the top part of the dialog box, specify what you want in the picture.

ExcelTips 2008 Page 342

Page 356: Excel tips 2008

Graphics Tips

5. In the bottom part of the dialog box, specify how you want the graphic saved. 6. Click OK.

If you are using Excel 2007, follow these very different steps, instead:

1. Select the cells or other object you want a picture of. (If you select cells, they must be contiguous.)

2. Display the Home tab of the ribbon. 3. Click the down arrow under the Paste tool in the Clipboard group. Excel displays a list

of options. 4. Click As Picture to display a submenu. 5. Click Copy as Picture. Excel displays the Copy Picture dialog box. 6. In the top part of the dialog box, specify what you want in the picture. 7. In the bottom part of the dialog box, specify how you want the graphic saved. 8. Click OK.

The result is that you now have a graphic in the Clipboard—either a metapicture or a bitmap, depending on your choice in the bottom portion of the dialog box—that you can paste anywhere. Paste it in another workbook, paste it in an e-mail, or paste it in a Word document. You can paste it just about anywhere because it is no longer an Excel object, but an actual graphic.

You should know that if you choose “As Shown On Screen” in the Copy Picture dialog box, that doesn’t mean that Excel copies the picture exactly as shown. The copied picture will always be at a 100% zoom magnification, regardless of what zoom setting you are using. Thus, if you are viewing your worksheet at 125% zoom, take a picture of some cells, and then paste the picture back into the workbook, it will look smaller than the rest of your workbook does because of how the picture is capture.

GETTING RID OF FIXED OBJECTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Peter has a filtered worksheet. When he takes all the filters off a message box pops up saying "Fixed objects will move!" There is no option other than clicking OK. Peter wonders what fixed objects are and how he can get rid of them.

“Fixed objects” can refer to a multitude of items, such as comments, graphics, controls, etc. They are considered “fixed” because they are placed in a spot on the worksheet and then Excel tries to keep them in that spot.

ExcelTips 2008 Page 343

Page 357: Excel tips 2008

Graphics Tips

You can select the objects in a worksheet by pressing F5 to display the Go To dialog box, and then clicking Special. In the resulting dialog box click the Objects radio button and click OK. At this point all the objects are selected and you can, if desired, delete them.

If you need to keep the objects, you can try getting rid of the notice by informing Excel that it is OK for the objects to move. This involves a properties change for each of the objects—right-click the object and choose Properties, then check or clear the checkbox that controls whether the object can move.

(Thanks to Steve Aprahamian for contributing to this tip.)

PIXELS IN A TEXT STRING Applies to Excel 97, 2000, 2002, 2003, and 2007

Jerrold knows that the LEN function returns the number of characters in a text string. What he needs to know, however, is the number of pixels (not characters) in a text string. He wonders if there is some way to calculate the value.

The short answer is no, there isn’t. The longer answer is that maybe there is. (Sound confusing? Read on.) The problem is that pixels—short for picture elements—are basically dots on a rendering device, such as a monitor or (more loosely) on a printer. The number of pixels packed into an inch depends on lots of variables, such as the resolution of the output device as well as its size.

For instance, at the same resolution, the number of pixels in an inch on a 19-inch monitor will be different than the number on a 21-inch monitor. Why? Because the screen resolution is spread over a larger display surface, resulting in fewer pixels per inch of that display surface.

Now let’s throw fonts into the mix. Different fonts pack different number of characters into a given linear measurement. You can see this most frequently if you put a bunch of text in a cell, copy the cell down a number of rows, and then apply different fonts to each cell. The contents of the cells will occupy a different horizontal space depending on the font (and point size) selected.

If you are using a monospace font (like Courier) which has a set size for all characters you can calculate the characters per inch for all characters and then, based on the number of characters, determine a rough estimate of the number of pixels. But, you still run into problems because you have to take the output device into consideration.

This will not work with proportionate fonts since the size of the characters vary for each character: Ms are much wider than Is for example. Therefore for each character of each font (and perhaps even each font size) one would need a table of pixel size and one would have to create a function to loop through the string and keep a running total of the sizes from each character. This gets even more complicated if various character attributes, such as bold or italic, or applied to the font.

ExcelTips 2008 Page 344

Page 358: Excel tips 2008

Graphics Tips

(Thanks to Steve Aprahamian for contributing to this tip.)

HIDING GRAPHICS WHEN FILTERING

Applies to Excel 97, 2000, 2002, 2003, and 2007

James has a worksheet that has graphics on top of cells that explain what is in the cells. The graphics sort with the cells just fine, but when he applies filters to the cells, the graphics bunch up at top of cells that are visible. James wonders if there is a way to have graphics hide when filtering data within cells.

The answer has to do with how you have the properties for the graphics set up. You need to make sure that the graphics are set to resize when the row height changes. Here’s what you do:

1. Select the graphic (or graphics) whose properties you want to modify. 2. Right-click the graphic (or graphics). Excel displays a Context menu. 3. Choose either Format Picture or Size and Properties from the Context menu, depending

on your version of Excel. Excel displays either the Format Picture or Size and Properties dialog box.

4. Make sure the Properties tab is displayed.

ExcelTips 2008 Page 345

Page 359: Excel tips 2008

Graphics Tips

The Properties tab of the Size and Properties dialog box.

5. Make sure the Move and Size with Cells check box is selected. 6. Click OK.

It is step 5 that does the trick here. Since your graphics are sorting properly when you sort the worksheet, chances are good that you had the Move but Don’t Size with Cells check box selected. This is what caused the graphics to bunch up—they couldn’t resize when filtering hid the rows with which they were associated.

(Thanks to Steve Aprahamian and Al Grant for contributing to this tip.)

ExcelTips 2008 Page 346

Page 360: Excel tips 2008

Charting Tips

FORMATTING AXIS PATTERNS Applies to Excel 97, 2000, 2002, 2003, and 2007

Most people who create charts with Excel don’t know that you can change just about everything that controls how the chart appears. One of the things you can easily change is the pattern used to denote a chart’s axis. By default Excel normally uses a solid line for an axis. If you want to change the pattern used by Excel, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Right-click on the axis whose pattern you want to change. Excel displays a Context menu for the axis.

2. Choose Format Axis from the Context menu. (If there is no Format Axis choice, then you did not right-click on an axis in step 1.) Excel displays the Format Axis dialog box.

3. Make sure the Patterns tab is selected.

ExcelTips 2008 Page 347

Page 361: Excel tips 2008

Charting Tips

The Patterns tab of the Format Axis dialog box.

4. Use the Style drop-down list to select the pattern that Excel should use for the axis. 5. Use the Color drop-down list to select a color for the axis. 6. Use the Weight drop-down list to specify how dark the pattern should appear. 7. Click on OK.

If you are using Excel 2007, then you should follow these steps:

1. Right-click on the axis whose pattern you want to change. Excel displays a Context menu for the axis.

2. Choose Format Axis from the Context menu. (If there is no Format Axis choice, then you did not right-click on an axis in step 1.) Excel displays the Format Axis dialog box.

ExcelTips 2008 Page 348

Page 362: Excel tips 2008

Charting Tips

The Format Axis dialog box.

3. Use the Line Style selection to specify how the axis line should look. 4. Use the Line Color selection to select a color for the axis. 5. Click on OK.

FORMATTING THE BORDER OF A LEGEND

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you create a chart in Excel, the Wizard that you follow may create a chart legend, depending on the type of chart you are creating. Normally, the appearance of the legend will be

ExcelTips 2008 Page 349

Page 363: Excel tips 2008

Charting Tips

acceptable for the type of chart you are creating. You have complete control, however, over how the legend appears.

One of the elements you can change is the type of border Excel places around the legend. To change the appearance of the legend’s border, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Click once on the legend to select it. Handles should appear around the perimeter of the legend.

2. Choose Selected Legend from the Format menu. Excel displays the Format Legend dialog box.

3. Make sure the Patterns tab is selected.

The Patterns tab of the Format Legend dialog box.

4. Use the Style drop-down list to select a different border style for the legend. 5. Use the Color drop-down list to change the color of the border. 6. Use the Weight drop-down list to specify how heavy the border should appear. 7. Use the Shadow check box to control if Excel adds a drop-shadow to the legend. 8. Click on OK.

If you are using Excel 2007, follow these steps instead:

ExcelTips 2008 Page 350

Page 364: Excel tips 2008

Charting Tips

1. Right-click on the legend to display a Context menu, then select Format Legend. Excel displays the Format Legend dialog box.

2. Use the Border Color option to change the color of the border. 3. Use the Border Styles option to select different border styles and weights for the legend. 4. Use the Shadow option to specify the type of shadow you want applied to the legend. 5. Click on OK.

SELECTING FONTS FOR A CHART Applies to Excel 97, 2000, 2002, 2003, and 2007

When creating a chart in Excel, you can add various elements to the charts, such as titles or data labels. Excel allows you to change the font used to display these elements, if you desire. You can change fonts for these elements individually. To do this, use these steps if you are using a version of Excel prior to Excel 2007:

1. Make sure your chart is visible on the screen and you have selected it. (You do this by clicking on the chart.)

2. Select the text element whose font you wish to change. For instance, if you want to change the chart’s title, click on the title. Excel displays small black squares around the element; this lets you know it is selected.

3. Choose Selected from the Format menu. (The word “Selected” in the menu will be followed by the type of object you selected, as in “Selected Chart Title.”) Excel displays the Format dialog box for the element.

4. Make sure the Font tab is selected.

ExcelTips 2008 Page 351

Page 365: Excel tips 2008

Charting Tips

The Font tab of the Format Chart Title dialog box.

5. Change the font settings, as desired. 6. Click on OK.

If you are using Excel 2007 then you can change fonts even easier. Follow these steps:

1. Make sure your chart is visible on the screen and you have selected it. (You do this by clicking on the chart.)

2. Select the text element whose font you wish to change. For instance, if you want to change the chart’s title, click on the title. Excel displays small black squares around the element; this lets you know it is selected.

3. Display the Home tab of the ribbon. 4. In the Font group, use the available tools to specify the font characteristics for the

element you selected in step 2.

ExcelTips 2008 Page 352

Page 366: Excel tips 2008

Charting Tips

USING GRAPHICS TO REPRESENT DATA SERIES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel is great at creating all sorts of charts from your data. You can even customize the charts to your heart’s content. One of the customizations you can make is to replace the regular bars (in a bar chart) with your own graphics. For instance, you might have a small graphic of a house that you want to use for the bars. This could be great if you wanted to used “stacked” houses to represent, for instance, housing starts in an area.

To use your own graphics in place of Excel’s built-in bars, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Create your bar chart as usual. 2. Right click on one of the data series bars in the chart. Excel displays a Context menu. 3. Choose Format Data Series from the Context menu. Excel displays the Format Data

Series dialog box. 4. Make sure the Patterns tab is selected.

The Patterns tab of the Format Data Series dialog box.

5. Click on Fill Effects. Excel displays the Fill Effects dialog box.

ExcelTips 2008 Page 353

Page 367: Excel tips 2008

Charting Tips

6. Make sure the Picture tab is selected.

The Picture tab of the Fill Effects dialog box.

7. Click on Select Picture. Excel displays the Select Picture dialog box, which is very similar to a standard Open dialog box.

8. Use the controls in the dialog box to locate and select the picture you want to use. 9. Click on Insert. Excel closes the Select Picture dialog box and redisplays the Fill Effects

dialog box. 10. In the Format section of the Picture tab, choose how you want the graphic to be applied

to the bar. (I like to choose Stack And Scale To and then specify how to many units each picture represents.)

11. Click on OK in each open dialog box to close them.

If you are using Excel 2007, then the steps are different:

1. Create your bar chart as usual. 2. Right click on one of the data series bars in the chart. Excel displays a Context menu.

ExcelTips 2008 Page 354

Page 368: Excel tips 2008

Charting Tips

3. Choose Format Data Series from the Context menu. Excel displays the Format Data Series dialog box.

4. Make sure the Fill option is selected at the left of the dialog box.

The Fill options of the Format Data Series dialog box.

5. Click Picture or Texture Fill. The options in the dialog box are expanded to reflect your choice.

6. Under Insert From, click File. Excel displays the Insert Picture dialog box, which is very similar to a standard Open dialog box.

7. Use the controls in the dialog box to locate and select the picture you want to use. 8. Click on Insert. Excel closes the Insert Picture dialog box and redisplays the Format

Data Series dialog box. 9. Choose how you want the graphic to be applied to the bar. (I like to choose Stack And

Scale With and then specify how to many units each picture represents.)

ExcelTips 2008 Page 355

Page 369: Excel tips 2008

Charting Tips

10. Click on OK in each open dialog box to close them.

USING THE MOUSE TO ADJUST YOUR VIEW OF 3-D GRAPHS

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you create a 3-D graph with Excel, you might want to adjust the perspective of the graph just a bit. You can use dialog boxes to make the adjustment, but you don’t need to go to that trouble—you can use the mouse. All you need to do is follow these steps:

1. Create and display your 3-D graph as you normally would. 2. Click on the walls that define the sides of your 3-D graph. Don't click on the objects that

represent the data, but on the walls surrounding the data. A good place to click is on the gray back walls of the graph.

3. Move the mouse pointer over the corners of the graph, where some of the small graphic handles (small black boxes) appear. When you do, a ToolTip should appear that says "Corners."

4. Click on the corner. This selects the corner. 5. Click again on the corner, but don't release the mouse button. Instead, start to drag the

corner in the direction you want.

When you perform step 5, Excel erases the graph and displays an outline of the box that contains the graph. You can drag the corner any direction you want, and Excel adjusts the angle at which you view the box. When you release the mouse button, the graph is redrawn at the current viewing angle.

It is interesting that the above steps (using the mouse) don’t work if you are using Excel 2007. It appears, in fact, that the only way you can adjust the rotation in Excel 2007 is by using the dialog boxes. Fortunately you can pull up the proper dialog box quickly by right-clicking on the graph—again, a good place to right-click is the back wall of the graph—and then choosing 3-D Rotation from the Context menu.

CHANGING AXIS TICK MARKS Applies to Excel 97, 2000, 2002, 2003, and 2007

If you use an Excel chart type that uses axes, you may have noticed the presence of “tick marks” on one or all of the axes. Tick marks are used to indicate a major or minor demarcation along an

ExcelTips 2008 Page 356

Page 370: Excel tips 2008

Charting Tips

axis. For instance, if you have an axis that ranges from 0 to 1000, there may be major tick marks at every 100 in the range, and minor tick marks at every 50.

Excel normally sets up the tick marks for you, but you can change the way they appear by following these steps if you are using a version of Excel prior to Excel 2007:

1. Right-click on the axis whose tick marks you want to change. Excel displays a Context menu for the axis.

2. Choose Format Axis from the Context menu. (If there is no Format Axis choice, then you did not right-click on an axis in step 1.) Excel displays the Format Axis dialog box.

3. Make sure the Scale tab is selected.

The Scale tab of the Format Axis dialog box.

4. Change the value to the right of Major Unit to indicate the multiple at which the major tick marks should appear.

5. Change the value to the right of Minor Unit to indicate the multiple at which the minor tick marks should appear.

6. Use the controls on the Scale tab to indicate where tick marks should appear along the axis.

7. Click on OK.

If you are using Excel 2007 then you should follow these steps:

ExcelTips 2008 Page 357

Page 371: Excel tips 2008

Charting Tips

1. Right-click on the axis whose tick marks you want to change. Excel displays a Context menu for the axis.

2. Choose Format Axis from the Context menu. (If there is no Format Axis choice, then you did not right-click on an axis in step 1.) Excel displays the Format Axis dialog box.

3. Make sure the Axis Options tab is selected.

The Axis Options tab of the Format Axis dialog box.

4. To the right of Major Unit, click Fixed and specify a multiple at which you want the major tick marks to appear.

5. To the right of Minor Unit, click Fixed and specify a multiple at which you want the minor tick marks to appear.

6. Click on OK.

ExcelTips 2008 Page 358

Page 372: Excel tips 2008

Charting Tips

READING VALUES FROM GRAPHS Applies to Excel 97, 2000, 2002, 2003, and 2007

When creating charts from Excel data, you can smooth out the lines between data points by using any number of methods. At some point, you may want to actually figure out how Excel does its calculations to determine where to actually plot points along the line. Rather than visually trying to figure out where a point falls, you can follow these steps:

1. Right-click on the data series in question. Excel displays a Context menu. 2. Choose the Add Trendline option from the Context menu. Excel displays the Add

Trendline dialog box. (In Excel 2007 it is the Format Trendline dialog box.)

The Format Trendline dialog box.

ExcelTips 2008 Page 359

Page 373: Excel tips 2008

Charting Tips

3. Make sure the regression type you want to use is selected. 4. Display the Options tab. (In Excel 2007 it is the Trendline Options tab.) 5. Make sure the Display Equation on Chart check box is selected. 6. Click on OK.

The result is that Excel shows a formula, on the chart, that represents how it calculated each point along the line. You can then use this formula to determine points, as well. No more guessing! Once you know the formula, you can turn off the formula display if you want it off.

If you would like to know the different formulas that Excel uses for different types of trend lines, you can use the online Help system to search for "equations for calculating trendlines."

REORDERING THE DISPLAY OF A DATA SERIES

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you create a chart in Excel, you may have a need to change the order in which the data series are displayed in the chart. One way to do this, of course, is to change the order of the data in the underlying worksheet range. For instance, you can sort the data in the worksheet range, and the change in order should be reflected in the chart based on that data.

Another way is to manually customize the chart to rearrange the data series. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Right-click on one of the data series that you want to move. Excel displays a Context menu.

2. Select the Format Data Series option from the Context menu. Excel displays the Format Data Series dialog box.

3. Make sure the Series Order tab is displayed.

ExcelTips 2008 Page 360

Page 374: Excel tips 2008

Charting Tips

The Series Order tab of the Format Data Series dialog box.

4. Click on Move Up or Move Down to move the data series to a new relative location. 5. If desired, select another data series in the Series Order list and repeat step 4. 6. When finished, click on OK.

If you are using Excel 2007 then the process is different. Follow these steps:

1. Right-click on one of the data series that you want to move. Excel displays a Context menu.

2. Select the Select Data option from the Context menu. Excel displays the Select Data Source dialog box.

ExcelTips 2008 Page 361

Page 375: Excel tips 2008

Charting Tips

The Select Data Source dialog box.

3. In the list of data series at the left of the dialog box, click once on the one you want to move.

4. Use the Up Arrow and Down Arrow buttons to reposition the selected data series. 5. When finished, click OK.

ADDING TEXT BOXES TO CHARTS Applies to Excel 97, 2000, 2002, 2003, and 2007

When you create a chart from your Excel data, you may want to add text boxes to the chart for any number of purposes (copyright statement, explanation, notes, etc.). There are two quick ways you can add a text box.

The first method is to use the Drawing toolbar or, if you are using Excel 2007, the Insert tab of the ribbon. Simply make sure it is displayed, then click the Text Box tool. The mouse pointer changes to crosshairs, and you can click and drag to outline the text box you want created.

The second way to create a text box is to use the Formula bar. Make sure you select any part of your chart except a title or data label. Click in the Formula bar and start typing what you want to appear in the text box. When you press ENTER, the text you typed is placed in a text box in the center of the chart. You can then move and resize the text box, as desired.

ExcelTips 2008 Page 362

Page 376: Excel tips 2008

Charting Tips

MOVING GROUPS OF DATA LABELS AT ONE TIME

Applies to Excel 97, 2000, 2002, 2003, and 2007

Harry is looking for a way to select a group of data labels and move them, all in one operation. The problem is that Excel won’t allow you to select and move a group of data labels, which means you need to adjust them individually.

Until such time as Microsoft decides to make working with chart labels more flexible, the best solution is to get a free Excel add-in called XY Chart Labeler, written by Rob Bovey. You can find the utility here:

http://appspro.com/Utilities/ChartLabeler.htm

LABELING X-Y SCATTER PLOTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Martin has a worksheet containing 50 rows of data, each row describing a single object. Column A contains the name of the object, column B contains its X coordinate, and column C contains its Y coordinate. When he creates an X-Y scatter chart (column B against column C) the result, as desired, is a graph showing an array of points showing the location of the objects. However, Martin can't seem to label the data points with their individual names (from column A). When he tries to label the data points the only available options are to label each point with its X value, Y value, or Series Name. Martin wonders if there is a way he can easily use Column A to label the plotted data points.

This can be done manually, but it is tedious at best. For 50 rows it would quickly be brutal, so it is best to look at a macro-oriented approach. One idea is to use a macro similar to the following, which steps through the data points in the X-Y chart and reads the label values from column A.

Sub DataLabelsFromRange() Dim Cht As Chart Dim i, ptcnt As Integer Set Cht = ActiveSheet.ChartObjects(1).Chart On Error Resume Next Cht.SeriesCollection(1).ApplyDataLabels _ Type:=xlDataLabelsShowValue, _ AutoText:=True, _ LegendKey:=False ptcnt = Cht.SeriesCollection(1).Points.Count For i = 1 To ptcnt

ExcelTips 2008 Page 363

Page 377: Excel tips 2008

Charting Tips

ExcelTips 2008 Page 364

Cht.SeriesCollection(1).Points(i).DataLabel.Text = _ ActiveSheet.Cells(i + 1, 1).Value Next i End Sub

The macro assumes that the first row of the worksheet contains header information and that the actual data begins in row 2. If the data really begins in row 1, then change “i + 1” to simply “i”. (This macro approach is actually a variation of a macro found on pages 570-571 of John Walkenbach's excellent book Excel 2003 Power Programming With VBA.)

One rather unique non-macro approach is to use Excel’s custom formats. All you need to do is set up a bunch of custom formats that contain only the text you want to be displayed. For example, if you have the values Age, 15, and 23 in cells A3 to C3, you can format either cell B3 or C3 to show the word “Age” even though the value will remain 15 or 23, respectively. Just enter “Age” (including the quotation marks) for the Custom format for the cell. Then format the chart to display the label for X or Y value.

When you do this, the X-axis values of the chart will probably all changed to whatever the format name is (i.e., Age). However, after formatting the X-axis to Number (with no digits after the decimal in this case) rather than General, the chart should display correctly.

This approach can obviously still take a bit of time to implement as you set up and apply a bunch of custom formats for each value in your data series. If you don’t want to mess with writing and testing your own macros or creating a bunch of custom formats, you can always turn to add-ins written by others. Microsoft MVP Rob Bovey has created an excellent (free) add-in for Excel which includes an X-Y labeling feature among several others. It can be downloaded at this address:

http://www.appspro.com/Utilities/ChartLabeler.htm

(Thanks to Steve Aprahamian, Andrija Vrcan, Dave Pettit, Tim Winters, Aidan Heritage, and Kathryn James for contributing to this tip.)

Page 378: Excel tips 2008

Printing Tips

SETTING PAGE MARGINS Applies to Excel 97, 2000, 2002, 2003, and 2007

In Excel, page margins are used to specify how much white space (blank area) should be left around the information in your worksheet. This is very similar to how margins are conceived and used in other programs, such as a word processor. Margins are used to provide a visual border for your printed page and an area where the page can be held or bound.

To set margins for a worksheet, choose Page Setup from the File menu or, if you are using excel 2007, display the Page Layout tab of the ribbon and then click the small icon at the lower-right of the Page Setup group. Excel displays the Page Setup dialog box; you should make sure the Margins tab is selected.

ExcelTips 2008 Page 365

Page 379: Excel tips 2008

Printing Tips

The Margins tab of the Page Setup dialog box.

There are four margins you can specify: top, bottom, left, and right. Each margin refers to the distance from the edge of the paper to where the information in your worksheet can be printed. Thus, a one-inch top margin means there will be one inch of white space at the top of each page of your printout.

If you include headers and footers in your page layout, the settings in the Header and Footer boxes allow you to indicate where they should print. Typically, the value in the Header field should be less than the value in the Top field, and the value in the Footer field should be less than the one in the Bottom field. In this way you will ensure that the header and footer appear within the margins specified at the top and bottom of the page.

At the bottom of the dialog box there are some check boxes that control the centering of your information on the page. Clicking your mouse on either the Horizontally or Vertically check boxes will make sure your information is centered in that direction. Notice that as you make changes to the margins or to the information centering, Excel shows you what your layout looks like. This is shown in the Preview area in the center of the dialog box.

ExcelTips 2008 Page 366

Page 380: Excel tips 2008

Printing Tips

SELECTING A PAPER SOURCE Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel supports any printer supported by Windows. This is because Excel uses the features offered by Windows to print documents. Many of the features associated with formatting your document and printing are related to the type of printer you have installed and selected. For instance, some laser printers have different bins for different paper. Windows (and thus Excel) can instruct the printer to select paper from any of the available paper bins.

If your printer supports multiple paper sources, and you want to change the paper source used for your document (for instance, you have a bin that contains legal-sized paper and you want to print on it), you should follow these steps:

1. Choose the Print option from the File menu. Excel displays the Print dialog box. (To display this dialog box in Excel 2007, click the Office button and then click Print.)

The Print dialog box.

2. Make sure the printer listed at the top of the dialog box matches the printer you want to use for your printing.

3. If you want to change the printer, use the drop-down list to select a different printer. 4. Click Cancel to close the Print dialog box. Even though you clicked Cancel, Excel

remembers the change you made to the printer.

ExcelTips 2008 Page 367

Page 381: Excel tips 2008

Printing Tips

5. Choose the Page Setup option from the File menu. Excel displays the Page Setup dialog box. (If you are using Excel 2007, display the Page Layout tab of the ribbon and then click the small icon at the lower-right of the Page Setup group to display this dialog box.)

6. Make sure the Page tab is selected.

The Page tab of the Page Setup dialog box.

7. Click on the Options button. This displays the Properties dialog box for your printer (the one you selected in steps 2 and 3). This dialog box contains the different printing options available for your printer.

8. Look through the tabs in the dialog box until you find controls that specify where paper should come from. Such a control may be named something like Paper Source, or you may see a Paper Source section with individual controls for the first and subsequent pages. Use the controls to specify where your paper should come from.

9. Click on OK. The Properties dialog box closes and the Page Setup dialog box reappears. 10. Click on OK to close the Page Setup dialog box. 11. Print your worksheet as you normally would.

ExcelTips 2008 Page 368

Page 382: Excel tips 2008

Printing Tips

If, in step 8, you don’t see different options for paper sources, then your printer (or printer driver) does not support multiple sources.

SCALING YOUR PRINTING Applies to Excel 97, 2000, 2002, 2003, and 2007

Worksheets can get very big, very fast. Often you want to still print an entire worksheet in a single sheet of paper. Excel makes this easy to do by using scaling. All you need to do is follow these steps if you are using a version of Word prior to Word 2007:

1. Set up your worksheet as desired. 2. Choose Page Setup from the File menu. Excel displays the Page Setup dialog box. 3. Make sure the Page tab is selected. (It is the left-most tab and should be displayed by

default unless you’ve recently viewed a different tab in the Page Setup dialog box.)

The Page tab of the Page Setup dialog box.

4. In the scaling area, specify how you want your output scaled. Excel allows you to set scaling at any value between 10 percent and 400 percent of normal size. (The results of scaling to a certain percentage will depend on the quality and capabilities of your printer.)

5. As an alternative, use Fit To to specify how many pages you want the output to occupy.

ExcelTips 2008 Page 369

Page 383: Excel tips 2008

Printing Tips

6. Click on OK. 7. Print your worksheet as normal.

While the above steps will work in Excel 2007, the ribbon tools actually make it easier to set the scaling. Display the Page Layout tab of the ribbon, and make your scaling adjustments using the settings in the Scale to Fit group.

One of the tricks I often use is to set the Fit To settings to 1 page wide by 99 pages tall. In this way, I am sure the output will fit on one page across. Since my output isn’t over 99 pages in length, no shrinking is done on this dimension. I end up with output that is 1 page wide by how ever many pages long Excel needs to print.

AUTOMATICALLY PRINTING A RANGE

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are automating your office using Excel, you may wonder if there is a way to automatically print the contents of a cell range at a given time each day. For instance, you might have a workbook that is always open, logging input from a different program. At a particular time each day you may want to automatically print a range that contains summary information.

There are a couple of approaches you could use to this problem, including using Windows Scripting to handle the printing. However, since the workbook is always open, you don't have to resort to that. Instead, you can rely on the native macro capabilities of Excel.

The solution considered here requires two macros. The first is one that runs whenever the workbook is first opened. It sets up the correct event handler to trigger the actual macro that does the printing.

Private Sub Workbook_Open() 'Schedule the printing Application.OnTime TimeValue("17:00:00"), "PrintMe" End Sub

This particular marco sets the OnTime method to be triggered whenever 5:00 p.m. is reached. To specify a different time of day, simply change the time (using 24-hour notation) in the macro. When 5:00 p.m. rolls around, Excel will run the PrintMe macro:

Private Sub PrintMe() Sheets(2).PrintOut 'Reschedule the printing Application.OnTime TimeValue("17:00:00"), "PrintMe" End Sub

ExcelTips 2008 Page 370

Page 384: Excel tips 2008

Printing Tips

This macro does nothing but print the second sheet in the workbook (which should contain the summary info you want printed) and then reset the OnTime method to again be triggered at 5:00 p.m. the next day. If you want a different data range to be printed, simply change the object used with the PrintOut method in the first line of the macro.

CHANGING ORIENTATIONS WITHIN A SINGLE PRINTOUT

Applies to Excel 97, 2000, 2002, 2003, and 2007

When Greg prints his workbook, he would like some worksheets to print in portrait orientation and some to print in landscape orientation. Greg knows he can print the worksheets one at a time, but he would like to print the workbook in one go. He wonders if there is some way to do this.

Actually, it is easier than one would think. Excel allows you to set the page parameters independently for each worksheet in a workbook. Thus, you can set some as landscape and some as portrait and later just print the whole workbook. Excel keeps track and orients the printing properly for each worksheet.

Here’s the easy way to set orientation for a group of worksheets:

1. Click the tab of the first worksheet. 2. Hold down the CTRL key as you click tabs of other worksheets you want to have the

same orientation as the first worksheet. Each worksheet tab should appear “highlighted,” indicating you are constructing a set of selected worksheets.

3. Choose the Page Setup option from the File menu. Excel displays the Page Setup dialog box. (To display the dialog box in Excel 2007, click the Page Layout tab of the ribbon and then click the small icon at the bottom-right of the Page Setup group.)

ExcelTips 2008 Page 371

Page 385: Excel tips 2008

Printing Tips

The Page Setup dialog box.

4. Specify the orientation you want to use for the selected worksheets. 5. Click OK. 6. Click on a worksheet tab different than the one that is currently selected. The tabs

should go back to normal, indicating that you are no longer working with a selection set.

When you later want to print your worksheets, simply select the worksheets you want to print before doing the print, or display the Print dialog box and specify that you want to print the entire workbook.

(Thanks to Andrija Vrcan, Steve Aprahamian, Terry Moses, Marco Notarmarco, Johnny Greally, Jim Byrne, Mary Padilla, Michael Cutler, Russell Hendel, and Elizabeth Dooley for contributing to this tip.)

ExcelTips 2008 Page 372

Page 386: Excel tips 2008

Printing Tips

PRINTING WORKBOOKS IN A FOLDER

Applies to Excel 97, 2000, 2002, 2003, and 2007

Have you collected a bunch of workbooks in a folder, and you want to print all of them at once? There are a couple of quick and easy ways you can do this. The first method involves the use of Windows, not Excel. Follow these general steps:

1. Display the folder that contains all the documents you want to print. 2. Create a selection set of the documents you want to print. (Select them all, using CTRL

and SHIFT to help put the selection set together.) 3. Right-click on one of the selected workbooks. Windows displays a Context menu. 4. Choose Print from the Context menu.

Excel is automatically started and each workbook is printed, in turn. You can also apply a variation on this approach:

1. In Excel, display the Open dialog box. (Click on Open or choose Open from the File menu. If you are using Excel 2007, click the Office button and then click Open.)

2. Using the controls in the dialog box, display the folder that contains the workbooks you want to print.

3. Create a selection set of the workbooks you want to print. 4. Right-click the selection set and choose Print from the resulting Context menu.

PREVENTING PRINTING Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are working with a sensitive worksheet, you may wonder if it is possible to prevent a user from actually printing the worksheet. Unfortunately, there is no foolproof way short of making sure the user doesn't have a printer attached to their system.

You can, depending on your version of Excel, customize the program so the print-related commands are removed from the toolbars and menus. You can also replace Excel’s built-in print commands with commands that do nothing. However, that doesn't stop people from actually doing a screen print of what is on the computer screen, thereby ending up with the information on a printout. In addition, people could bypass executing the macros by disabling them when the workbook is loaded. Another way around such customizations is for the user to simply copy text from the print-inhibited worksheet and paste it into a new worksheet that has no such customizations. The worksheet could then easily be printed.

ExcelTips 2008 Page 373

Page 387: Excel tips 2008

Printing Tips

You can also try non-Excel solutions, such as using Adobe Acrobat to create a protected PDF file that cannot be printed. However, even then the user could still do a screen print of what they see.

PRINTING ALL OR NOTHING Applies to Excel 97, 2000, 2002, 2003, and 2007

Karen is looking for a way to print an entire workbook, even if a user chooses to print a single worksheet. In other words, she is looking for a way to print either the entire workbook, or nothing at all—there should be no “in between” options.

The only way to handle this is through the use of a macro. VBA allows you to create macros that are initiated when certain events occur. One of the events that can trigger macros is the “print” event. When someone asks to print, or chooses to see a print preview, the BeforePrint event of the Workbook object is triggered. You can create your own macro that executes when the event is triggered.

Private Sub Workbook_BeforePrint(Cancel As Boolean) Dim sht As Variant Dim bPreview As Boolean Dim iResponse As Integer On Error GoTo ErrHandler iResponse = MsgBox(prompt:="Do you want to Print Preview?", _ Buttons:=vbYesNoCancel, Title:="Preview?") Select Case iResponse Case vbYes bPreview = True Case vbNo bPreview = False Case Else GoTo ExitHandler End Select Application.EnableEvents = False For Each sht In Sheets If sht.Visible Then sht.PrintOut Preview:=bPreview End If Next ExitHandler: Application.EnableEvents = True Cancel = True Exit Sub ErrHandler:

ExcelTips 2008 Page 374

Page 388: Excel tips 2008

Printing Tips

MsgBox Err.Description Resume ExitHandler End Sub

Whenever Excel gets ready to print, or whenever print preview is invoked, the BeforePrint event is triggered and this macro runs. The macro first asks the user if he or she wants to do a print preview. A Select Case structure is used to set the bPreview variable based on the answer to the question. The setting of bPreview then controls what happens.

If the user clicked Cancel when asked about previewing, then the macro is exited and the printing is canceled. Otherwise, each worksheet in the workbook is examined to either print or preview. If the worksheet is visible, it is printed, and the Preview property is set equal to bPreview (True means that the worksheet is previewed; False means it is actually printed).

Notice that the macro sets the EnableEvents property to False. This is done so that no other events can trigger while printing or previewing. If EnableEvents is left “on,” then every time the PrintOut method is used, the entire BeforePrint event is again triggered—the user would end up in an endless loop if event handling were not turned off.

Also, note that one of the last things to occur before exiting the macro is that the Cancel property is set to True. This is done so that the original print or print preview request that generated the BeforePrint event is cancelled. There is, after all, no need to complete that request, and the macro did all the print handling for the user.

There is one caveat, of course, to using this approach to printing: If macros are not enabled, the handler will not run and the user can print as desired. (Holding SHIFT while opening the workbook disables macros and the user most times is asked if they want to enable macros.) Other issues of ExcelTips have discussed this fact.

PRINTING MULTIPLE PAGES ON A PIECE OF PAPER

Applies to Excel 2000, 2002, 2003, and 2007

You may want to print multiple pages of your Excel worksheet on a single piece of paper. You can accomplish this in Excel 2000 or later versions by following these steps:

1. Display the Page Setup dialog box. You do this in Excel 2000 through 2003 by choosing File | Page Setup. If you are using Excel 2007 you display the Page Layout tab of the ruler and then click the small icon at the lower-right corner of the Page Setup group.

2. Click on the Options button. Excel displays the printer’s Document Properties dialog box.

ExcelTips 2008 Page 375

Page 389: Excel tips 2008

Printing Tips

3. Look around through the available tabs to locate one that has a Pages Per Sheet control or a Multiple Page control. On my printer it is the Finishing tab; on yours it may be different.

The Finishing tab of a printer’s Document Properties dialog box.

4. Using the Pages Per Sheet control (or the Multiple Page control), specify how many pages you want printed on each sheet of paper.

5. Click on OK to dismiss the printer’s Document Properties dialog box. 6. Click on OK to dismiss the Page Setup dialog box.

ExcelTips 2008 Page 376

Page 390: Excel tips 2008

Printing Tips

REPEATING ROWS ON A PRINTOUT EXCEPT ON THE LAST PAGE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Nancy knows how to format a worksheet so that rows are repeated at the top of each page of a printout. What she wants to do, however, is to have the rows repeated at the top of each printed page except the last one.

There is no direct way to do this, but you can simulate such a printing by using a macro to do the task. All you need to do is have the macro print all except your last page, then change the page setup so that rows are not repeated, and finally print the final page of the printout. The following macro provides an example of this approach.

Sub PrintWorksheet() Dim lPages As Long Dim sTemp As String lPages = Application.ExecuteExcel4Macro("GET.DOCUMENT(50)") With ActiveSheet.PageSetup ActiveSheet.PrintOut From:=1, To:=lPages - 1 sTemp = .PrintTitleRows .PrintTitleRows = "" ActiveSheet.PrintOut From:=lPages, To:=lPages .PrintTitleRows = sTemp End With End Sub

(Thanks to Steve Aprahamian and Robert Brewer for contributing to this tip.)

SHOWING FILTER CRITERIA ON A PRINTOUT

Applies to Excel 97, 2000, 2002, 2003, and 2007

Microsoft Excel includes some great tools that help you filter large data tables to include only the information you want displayed. In effect, the filters allow you to “slice and dice” your data until you get just what you want.

When printing out filtered data, you might want to know what slicing and dicing was done to the original data. There are several ways you can go about displaying your filtering criteria. One simple way is to use the advanced filtering capabilities of Excel, which require that you set up a

ExcelTips 2008 Page 377

Page 391: Excel tips 2008

Printing Tips

small criteria table for your data. If the criteria table is made part of what you print, then you can see your filtering criteria quite easily.

If you use AutoFilter, then you need to use a different approach. One such approach is detailed at John Walkenbach’s site:

http://j-walk.com/ss/excel/usertips/tip044.htm

This solution uses a user-defined function to return any filtering criteria in use in the current column. The function can be used in a cell, in that column, to display the criteria. If you are using advanced filtering, then the macro approach is a bit more complex. The following macros (there are two of them in the listing) will examine what advanced criteria are in play, and then place the criteria in the left portion of the header.

Sub AddFilterCriteria() Dim strCriteria As String strCriteria = FilterCriteria() If strCriteria = "" Then strCriteria = "No Filtering Criteria" Else strCriteria = "Filter Criteria:" & Chr(10) & strCriteria End If ' add Criteria string to Header/Footer With ActiveSheet.PageSetup .LeftHeader = strCriteria End With End Sub Function FilterCriteria() As String Dim rngCriteria As Range, col As Range, cel As Range Dim strCriteria As String, r As Integer, c As Integer Const strCriteriaRange As String = "Criteria" FilterCriteria = "" On Error Resume Next 'Set Criteria-Range reference Set rngCriteria = Range(strCriteriaRange) If Err <> 0 Then Exit Function On Error GoTo 0 ' Create Criteria String c = 0 For Each col In rngCriteria.Columns c = c + 1 ' CriteriaRange Columns r = 1 ' CriteriaRange Rows For Each cel In col.Cells If r = 1 Then strCriteria = strCriteria & "Criteria" _

ExcelTips 2008 Page 378

Page 392: Excel tips 2008

Printing Tips

& c & " (" & cel.Value & ") = " Else strCriteria = strCriteria & "'" & cel.Value & "'" If IsEmpty(cel.Offset(1, 0)) Then 'Add New row Char if not Last Criteria Column If c < rngCriteria.Columns.Count Then strCriteria = strCriteria & Chr(10) End If Exit For End If strCriteria = strCriteria & " <or> " End If r = r + 1 Next cel ' next criteria row Next col ' next criteria column FilterCriteria = strCriteria End Function

To use the macro, just run the AddFilterCriteria macro, after you have your advanced filtering set up. The macro reads the criteria table and puts together the criteria into a string that is placed in the left header.

PRINTING A NUMBER OF DIFFERENT PAGES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel obviously allows you to print your worksheets to a printer. Sometimes a worksheet will fit on a single page, but other times it will flow to multiple pages. You may be wondering how you can print different pages on your printer, as you can print different pages of a Word document.

If your worksheets each will fit on their own page (a single sheet), then the answer to the question is easy: all you need to do is select the worksheets you want to print before you actually print. For instance, if you want to print worksheets 4, 8, and 10, all you need to do is click on the first worksheet’s tab (worksheet 4 in this scenario), then hold down the CTRL key as you click on the second and third worksheet tabs (worksheets 8 and 10). When you print, only those three worksheets will be printed.

If you want to print specific pages out of a single worksheet that normally prints on multiple pages, then the answer is a bit more difficult. One solution is to temporarily hide the unwanted portions of the worksheet and then print the unhidden areas. An easier solution is as follows, however:

1. Choose Page Break Preview from the View menu. Excel displays your worksheet, showing the various page breaks. (This view is available in Excel 2007 by displaying

ExcelTips 2008 Page 379

Page 393: Excel tips 2008

Printing Tips

the View tab of the ribbon and clicking the Page Break Preview tool in the Workbook Views group.)

2. Select all the cells in the first page you want printed. 3. As you hold down the CTRL key, select all the cells in the second page you want printed. 4. Repeat step 3 for each page you want printed. 5. Choose Print from the File menu. Excel displays the Print dialog box. (To display this

dialog box in Excel 2007 click the Office button and then click Print.)

The Print dialog box.

6. In the Print What area, choose Selection. 7. Click on OK. Excel prints just the selected pages. 8. Close the Page Break Preview display.

PRINTING AN ENTIRE WORKBOOK BY DEFAULT

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you choose to print in Excel, the Print dialog box has controls that allow you to specify many things about the print job. The controls in the Print What area of the dialog box allow you to indicate whether you want to print the selected worksheets, the selection, or the entire

ExcelTips 2008 Page 380

Page 394: Excel tips 2008

Printing Tips

workbook. The option in the Print What area normally defaults to Active Worksheets, but what if you want it to default so the entire workbook is printed?

Unfortunately, Excel does not remember what you select in the Print What area from one print job to the next; it always resets the default. The easiest way to always print the entire workbook, however, it to make a simple little macro like this:

Sub PrintItAll() ActiveWorkbook.PrintOut End Sub

You can then create a button on a toolbar and assign this macro to that button. When you want to print the entire workbook, just click on the button. Easy and quick.

PRINTING JUST THE VISIBLE DATA

Applies to Excel 97, 2000, 2002, 2003, and 2007

It is easy to amass quite a bit of information in an Excel workbook. Fortunately, that information can be easily printed out. What if you only want to print just what you see on the screen, however, instead of an entire worksheet? To make matters worse, what if you are using frozen panes to hold the position of your page headers?

Normally, you could simply choose what you want printed and then just print that selection. Alternately, you could choose what you want printed, define it as the print area, and then choose to print. This simple of an approach won’t work in this instance, however, because of using frozen panes. This feature allows you to “freeze” rows at the top of the screen, columns at the left of the screen, and only scroll the cells in the unfrozen part. Thus, you can’t select everything you want to print because what you want to print consists of three distinct areas of the worksheet.

The solution is to set Excel’s repeating rows and columns, and then choose what you want to print. The following steps will work just fine:

1. Choose the Page Setup option from the File menu. Excel displays the Page Setup dialog box. (To display the dialog box in Excel 2007, display the Page Layout tab of the ribbon and click the small icon at the lower-right of the Page Setup group.)

2. Make sure the Sheet tab is selected.

ExcelTips 2008 Page 381

Page 395: Excel tips 2008

Printing Tips

The Sheet tab of the Page Setup dialog box.

3. Place the insertion point in the Rows to Repeat at Top box. 4. In the worksheet, select the rows you want to appear at the top of each page. The row

names should appear in the dialog box. 5. Place the insertion point in the Columns to Repeat at Left box. 6. In the worksheet, select the columns you want to appear at the left of each page. The

column names should appear in the dialog box. 7. Click on OK to close the Page Setup dialog box. 8. Select the range you want to print, but don’t include any cells in the rows or columns

you specified in steps 4 and 6. 9. Choose Print from the File menu. Excel displays the Print dialog box. (To display the

dialog box in Excel 2007, click the Office button and then click Print.)

ExcelTips 2008 Page 382

Page 396: Excel tips 2008

Printing Tips

The Print dialog box.

10. Choose the Selection radio button. (You are indicating that you want to print only what you have selected.)

11. Click on OK.

The printout contains only the cells you specified, along with the frozen rows and columns. If you selected just the visible cells in step 8, then you effectively printed just the visible data.

HIDING ERRORS ON PRINTOUTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel has a number of different errors that can appear in your worksheet, for any number of reasons. Errors values show up with a pound (hash) symbol followed by the type of error, as in #DIV/0! or #N/A.

When you print your worksheet, Excel prints the error values, by default. If you prefer, you can choose to have Excel not print the error values. Follow these steps:

1. Choose Page Setup from the File menu. Excel displays the Page Setup dialog box. (If you are using Excel 2007, display the Page Layout tab of the ribbon and then click the small icon at the lower-right of the Page Setup group to display this dialog box.)

2. Make sure the Sheet tab is displayed.

ExcelTips 2008 Page 383

Page 397: Excel tips 2008

Printing Tips

The Sheet tab of the Page Setup dialog box.

3. Use the Cell Errors As drop-down list to specify how you want the error values printed. 4. Click OK to close the Page Setup dialog box.

In step 3, you have several options in the drop-down list:

• Displayed. Prints the error values as they show in the worksheet. • <Blank>. Replaces the error value with a blank; effectively hides the error values. • --. Replaces the error value with two dashes. • #N/A. Replaces all error values with #N/A.

ExcelTips 2008 Page 384

Page 398: Excel tips 2008

Printing Tips

PRINTING ONLY NON-BLANK WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Clinton has a workbook with about 210 worksheets which get populated by various people in his company during the month. At the end of the month he needs to print these worksheets. Not all the worksheets contain data and Clinton only wants to print the worksheets that contain data so he doesn't waste paper. Clinton wonders if there is, perhaps, a macro that can be used to print only those worksheets that have a value in cell G41.

The answer is that such a macro could be written rather easily. It would only need to figure out how many worksheets there are, check cell G41 on each of them, and then print only if there is something in that cell. The following macro performs just these operations.

Sub PrintMost() Dim wks As Worksheet For Each wks In ActiveWorkbook.Worksheets If Not IsEmpty(wks.Range("G41")) Then wks.PrintOut End If Next Set wks = Nothing End Sub

The macro could be easily modified to perform other operations, such as asking if any given worksheet should be printed or asking how many copies should be printed.

(Thanks to Andrija Vrcan, Steve Aprahamian, Pranav Lunavat, Khushnood Viccaji, Adrian Fielden, Aidan Heritage, and David Coop for contributing to this tip.)

LOCKING THE PRINT AREA Applies to Excel 97, 2000, 2002, 2003, and 2007

Karolyne shares workbooks with other people. Once in a while those people will, without knowing it, make changes to a worksheet that results in many, many pages being printed. Karolyne is looking for a way to set a print area in such a way that it is "locked" and could not be changed or removed.

There are a couple of things you can try. First, you can set your print area and then apply worksheet protection that allows only some of the cells in the worksheet to be selected. This will preclude those strange changes that result in huge printouts. It won’t, however, stop someone from changing the print area so it includes only those unprotected cells.

ExcelTips 2008 Page 385

Page 399: Excel tips 2008

Printing Tips

The only way to “protect” the print area is to use a macro that will force the desired print area. One natural place to enforce this is just before printing. The following event handler (added to the ThisWorkbook module) will change the print area for worksheet Sheet1 to the range A1:C25:

Private Sub Workbook_BeforePrint(Cancel As Boolean) Worksheets("Sheet1").PageSetup.PrintArea = "A1:C25" End Sub

This approach will only work, obviously, if the user enables macros when the workbook is opened. You can change the specified sheet name and range as desired.

(Thanks to Dan Elgaard, Johnny Greally, Steve Aprahamian, Kirk Mays, Yngve Angelskar, Richard Raciborski, and Sandy Badkas for contributing to this tip.)

PROTECTING PRINT SETTINGS Applies to Excel 97, 2000, 2002, 2003, and 2007

Sharing an Excel workbook with a group also means being involved with different printers, different PCs and different user requirements and expectations. This is nowhere more apparent then when it comes to printing a worksheet. Different users obviously have different PCs and may have different printers, so the printed results can vary from one user to another. In addition, different users may change the print ranges in what is produced from a worksheet.

If you are responsible for a particular worksheet, you may want to somehow protect the various print settings you’ve established so that they aren’t garbled by other users. Perhaps the easiest way to do this is to save your print settings in a macro, and then run that macro every time the workbook is closed. In that way, the settings can be changed back to the “defaults” you specify, without worry that users will mess them all up.

For instance, the following macro shows how you can set all the print settings for a particular print job:

Sub Auto_Close() With ActiveSheet.PageSetup .LeftHeader = "" .CenterHeader = "" .RightHeader = "" .LeftFooter = "" .CenterFooter = "" .RightFooter = "" .LeftMargin = Application.InchesToPoints(1) .RightMargin = Application.InchesToPoints(1) .TopMargin = Application.InchesToPoints(1) .BottomMargin = Application.InchesToPoints(1) .HeaderMargin = Application.InchesToPoints(0.5)

ExcelTips 2008 Page 386

Page 400: Excel tips 2008

Printing Tips

.FooterMargin = Application.InchesToPoints(0.5) .PrintHeadings = False .PrintGridlines = False .PrintComments = xlPrintNoComments .CenterHorizontally = False .CenterVertically = False .Orientation = xlPortrait .Draft = False .PaperSize = xlPaperLetter .FirstPageNumber = xlAutomatic .Order = xlDownThenOver .BlackAndWhite = False .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = 99 .PrintErrors = xlPrintErrorsDisplayed .PrintArea = "MyPrintArea" .PrintTitleRows = "" .PrintTitleColumns = "" End With End Sub

To make the macro work for your particular needs, simply modify the settings to match whatever your requirements are.

Of course, when someone else opens your workbook, they will see a notification that there are macros in it. If they choose to disable the macros, then your default-setting macro won’t run when the workbook is closed. The solution, of course, is for you to open the workbook, enable the macros, and then close the workbook. This runs the macro and your settings are again restored as you want them.

CONDITIONAL PRINTING Applies to Excel 97, 2000, 2002, 2003, and 2007

Kirk asked if there is a way to conditionally control what is printed in Excel. For instance, cell A1 contains a value, and the value controls exactly what is printed. Perhaps if A1 contains 1, then Sheet1 is printed; if it contains 2, then Sheet1 and Sheet2 are printed.

The only way to do this is with a macro, and there are several approaches you can use. Consider the following very simple macro, which simply uses a Select Case structure to control the printing.

Sub PrintStuff() Dim vShts As Variant vShts = Sheets(1).Range("A1")

ExcelTips 2008 Page 387

Page 401: Excel tips 2008

Printing Tips

If Not IsNumeric(vShts) Then Exit Sub Else Select Case vShts Case 1 Sheets("Sheet1").PrintOut Case 2 Sheets("Sheet2").PrintOut Case 3 Sheets("Sheet1").PrintOut Sheets("Sheet2").PrintOut End Select End If End Sub

Run this macro with the value 1, 2, or 3 in cell A1 of the first sheet, and the macro prints different things based on the value. If the value is 1, then Sheet1 is printed; if it is 2, then Sheet2 is printed; and if it is 3, then both Sheet1 and Sheet2 are printed. If you want different values to print different things, just modify the Select Case structure to reflect the possible values and what should be printed for each value.

A more comprehensive approach can be created, as well. Consider adding a “control sheet” to your workbook. This sheet would have the name of each worksheet in the workbook listed in the first column. If you put a value to the right of a worksheet name, in the second column, then a macro will print the corresponding worksheet.

The following macro can be used to create the “control sheet.”

Sub CreateControlSheet() Dim i as integer On Error Resume Next 'Delete this sheet if it already exists Sheets("Control Sheet").Delete On Error GoTo 0 Sheets.Add 'Add the WhatToPrint Sheet ActiveSheet.Name = "Control Sheet" Range("A1").Select 'Label the columns ActiveCell.FormulaR1C1 = "Sheet Name" Range("B1").Select ActiveCell.FormulaR1C1 = "Print?" Cells.Select Selection.Columns.AutoFit For i = 1 To ActiveWorkbook.Sheets.Count Cells(i + 1, 1).Value = Sheets(i).Name Next End Sub

ExcelTips 2008 Page 388

Page 402: Excel tips 2008

Printing Tips

The macro first deletes any old control sheet, if it exists. It then adds a new worksheet named Control Sheet, and puts headers labels in columns A and B. It then lists all the worksheets in the workbook in column A.

With the control sheet created, you can then place an “X” or some other value (such as “Y” or 1) into column B beside each worksheet you want to print. The following macro then examines the control sheet and prints any worksheet that has a mark—any mark—in the cell in column B.

Sub PrintSelectedSheets() Dim i as Integer i = 2 Do Until Sheets("Control Sheet").Cells(i, 1).Value = "" If Trim(Sheets("Control Sheet").Cells(i, 2).Value <> "") Then Sheets(Sheets("Control Sheet").Cells(i, 1).Value).Select ActiveWindow.SelectedSheets.PrintOut Copies:=1 End If i = i + 1 Loop End Sub

Another approach is to create a macro that runs just before printing. (This is one of the events—printing—that Excel allows you to trap.) The following macro, added to the thisWorkbook object, is run every time you try to print or choose Print Preview.

Private Sub Workbook_BeforePrint(Cancel As Boolean) Dim vShts As Variant Dim iResponse As Integer Dim bPreview As Boolean On Error GoTo ErrHandler vShts = Sheets(1).Range("A1") If Not IsNumeric(vShts) Then GoTo InValidEntry ElseIf vShts < 1 Or vShts > Sheets.Count Then GoTo InValidEntry Else iResponse = MsgBox(prompt:="Do you want Print Preview?", _ Buttons:=vbYesNoCancel, Title:="Preview?") Select Case iResponse Case vbYes bPreview = True Case vbNo bPreview = False Case Else Msgbox "Canceled at User request" GoTo ExitHandler End Select Application.EnableEvents = False

ExcelTips 2008 Page 389

Page 403: Excel tips 2008

Printing Tips

Sheets(vShts).PrintOut Preview:=bPreview End If ExitHandler: Application.EnableEvents = True Cancel = True Exit Sub InValidEntry: MsgBox "'" & Sheets(1).Name & "'!A1" _ & vbCrLf & "must have a number between " _ & "1 and " & Sheets.Count & vbCrLf GoTo ExitHandler ErrHandler: MsgBox Err.Description Resume ExitHandler End Sub

The macro checks the value in cell A1 of the first worksheet. It uses this value to determine which worksheets should be printed. In other words, a 1 prints the first worksheet, a 2 prints the second, a 3 prints the third, and so on.

If the value in A1 is not a value or if it is less than 1 or greater than the number of worksheets in the workbook, then the user is informed that the value is incorrect and the macro is exited.

Assuming the value in A1 is within range, the macro asks if you want to using Print Preview. Depending on the user’s response, the macro prints the specified worksheet or displays Print Preview for that worksheet.

PRINTING BASED ON CELL CONTENTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Theresa wonders if there is a way to format a cell so that if the contents of the cell meet certain criteria then a specific worksheet is automatically printed. The short answer is no, there is no way to use formatting to achieve this goal. You can, however, use an event handler macro to do the printing.

For example, one of the event handlers supported by Excel is triggered every time something in the workbook is changed. You can create an event handler that examines which cell was changed. If it is a specific cell, and if that cell contains a particular value, then a worksheet can be printed.

Private Sub Worksheet_Change(ByVal Target As Range)

ExcelTips 2008 Page 390

Page 404: Excel tips 2008

Printing Tips

ExcelTips 2008 Page 391

Dim targCell As Range Set targCell = Worksheets(1).Range("B2") If Not Application.Intersect(Target, targCell) Is Nothing Then If targCell.Value = 1001 Then Worksheets(1).PrintOut End If End If End Sub

This macro examines the contents of cell B2. If the cell contents are changed and if the cell contains the value 1001, then the worksheet is automatically printed.

Of course, you may want the contents of a particular cell to control what is printed when someone actually chooses to print. For instance, if the user chooses to print, you may want to examine the contents of a cell (such as E2) and, based on the contents of that cell, automatically modify what is printed. The following macro takes this approach:

Private Sub Workbook_BeforePrint(Cancel As Boolean) Application.EnableEvents = False Select Case Worksheets("Sheet1").Range("E1") Case 1 Worksheets("Sheet1").PrintOut Case 2 Worksheets("Sheet2").PrintOut Case 3 Worksheets("Sheet3").PrintOut Case 4 Worksheets("Sheet4").PrintOut Case Else ActiveSheet.PrintOut End Select Cancel = True Application.EnableEvents = True End Sub

The macro prints Sheet1, Sheet2, Sheet3, or Sheet4 depending on whether cell E2 contains 1, 2, 3, or 4.

(Thanks to Steve Aprahamian, Richard Raciborski, Valerie Robbins, and Russell Hendel for contributing to this tip.)

Page 405: Excel tips 2008

Workbook and File Tips

INCREASING THE NUMBER OF MRU FILES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Peter asked a common question for Excel users: Is it possible to increase the number of Most Recently Used files beyond the nine available in Excel. In versions of Excel prior to Excel 2007 the answer was an emphatic no—the maximum limit of nine is hard-coded into the program.

Excel 2007 made a change, however. You can change the number of MRU files by following these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left side of the dialog box. 3. Scroll through the available options until you see the Display section.

ExcelTips 2008 Page 392

Page 406: Excel tips 2008

Workbook and File Tips

The Advanced options of the Excel Options dialog box.

4. Use the control labeled Show this Number of Recent Documents to indicate how many files you want to appear in the MRU list. (You can set a value up to 50.)

5. Click OK.

(Thanks to Steve Aprahamian, Venkat Annapareddy, and Mark Haeg for contributing to this tip.)

SAVING ALL OPEN WORKBOOKS Applies to Excel 97, 2000, 2002, 2003, and 2007

Users familiar with Word may remember that prior to Word 2007 the program contained a nifty shortcut that allowed you to save all your open documents at once—just hold down the SHIFT key as you click on the File menu, and the Save option becomes Save All.

In Excel there doesn’t seem to be a similar shortcut. The closest native solution is to hold down the SHIFT key as you click the File menu, then choose Close All. In the process of closing, Excel will ask if you want each workbook saved. (This, of course, won’t work in Excel 2007 because it doesn’t even have a File menu.)

The big drawback to this is that Excel closes, and you need to again start Excel and open all your workbooks. If you want a true Save All command, you need to create it using a macro. The following is a good example of one you could use:

ExcelTips 2008 Page 393

Page 407: Excel tips 2008

Workbook and File Tips

Sub SaveAll() Dim Wkb As Workbook For Each Wkb In Workbooks If Not Wkb.ReadOnly And Windows(Wkb.Name).Visible Then Wkb.Save End If Next End Sub

Save the macro in your Personal.xls workbook, assign it to a toolbar button or a shortcut key, and you can call it up as often as you like. It saves all the workbooks that are open, except those that are read-only or hidden.

SAVING A WORKBOOK WITH A PREVIEW

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you use the Open dialog box in Excel, you can configure what you see in the dialog box. One of the settings you can make is for Excel to display a preview of whatever workbook you select in the left side of the dialog box. (Click on the drop-down arrow next to the Views tool, then choose Preview.)

You may have already noticed that some of your workbooks do not have a preview available in the Open dialog box. If this is the case, and you want to have a preview available, you need to make sure that the workbook is saved with the preview enabled. If the workbook is loaded in Excel, follow these general steps:

1. Choose Properties from the File menu. Excel displays the Properties dialog box for your workbook. (Displaying the dialog box in Excel 2007 is a bit more involved. Click the Office button, Prepare, and then Properties. This displays some of the properties just above the worksheet on the screen. You will need to click the Document Properties drop-down list and choose Advanced Properties.)

2. Make sure the Summary tab is selected.

ExcelTips 2008 Page 394

Page 408: Excel tips 2008

Workbook and File Tips

The Summary tab of the Properties dialog box.

3. Select the Save Preview Picture check box at the bottom of the dialog box. (In Excel 2007 it is called the Save Thumbnails for All Excel Documents check box.)

4. Click on OK to close the Properties dialog box. 5. Click the Save tool on the toolbar, or choose Save from the File menu.

At this point you can close the workbook. Now when you display the Open dialog box, and you have the preview feature turned on, the workbook displays a preview in the dialog box.

CORRECTLY SAVING DELIMITED FILES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Raymond indicated that he was having some problems properly exporting delimited files from within Excel. Raymond was requesting that Excel create a file using the tab character as a

ExcelTips 2008 Page 395

Page 409: Excel tips 2008

Workbook and File Tips

delimiter. It seems that Excel would not reliably add a tab character at the end of a row when the last field in the row was empty.

Actually, this is how Excel is designed to operate. When exporting information to a delimited file, each row in the data table is handled independently. If one particular row has fewer fields than other rows, Excel doesn’t “pad out” the exported row with “blank” fields. This can, of course, lead to problems with some other programs that use the Excel-created file and rely on a static number of fields in each input row.

A workaround for this potential problem is to simply make sure that Excel always has something in every cell of the final column of your data table. This is actually easier than it sounds—all you need to do is make sure the right-most column contains some unique text string, perhaps something like [{|}]. (It is unlikely that such a string would be used elsewhere in your data.) When you export to a delimited file, Excel will always export the same number of fields per row, right up to the unique text string. Then, when you import the delimited file into your other program, you can instruct it to ignore the last field of each row that it imports.

SETTING THE AUTORECOVER DIRECTORY

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel has a feature that causes automatic saving of temporary files, in case there is a problem with your computer. (You know the routine—power goes out, whatever.) This feature is called AutoRecover. When an AutoRecover file is saved to disk, it is placed in a directory that you specify. To change the directory used for saving AutoRecover files, follow these steps:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Click on the Save tab.

ExcelTips 2008 Page 396

Page 410: Excel tips 2008

Workbook and File Tips

The Save tab of the Options dialog box.

3. In the AutoRecover Save Location box, enter the full path of the folder in which you want the files saved.

4. Click on OK.

If you are using Excel 2007 then the steps are slightly different:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click the Save button at the left side of the dialog box.

ExcelTips 2008 Page 397

Page 411: Excel tips 2008

Workbook and File Tips

The Save options of the Excel Options dialog box.

3. In the AutoRecover File Location box, enter the full path of the folder in which you want the files saved.

4. Click on OK.

DATE LAST EDITED Applies to Excel 97, 2000, 2002, 2003, and 2007

As part of setting up a worksheet, you may want the header or footer to contain the date that the workbook was last edited. Excel doesn’t maintain this information, but it does allow you to perform macros whenever certain events occur, such as changes to a workbook. All you need to do is add a macro such as the following to the ThisWorkbook object in the VBA Editor:

Private Sub Workbook_SheetChange(ByVal _ Sh As Object, ByVal Target As Excel.Range) ActiveSheet.PageSetup.CenterFooter = _ "Worksheet Last Changed: " & _ Format(Now, "mmmm d, yyyy hh:mm") End Sub

The macro results in each footer on each worksheet in the workbook having separate dates and times on them, since each worksheet would be updated at different times. You can change the destination property (.CenterFooter) to one of the other header or footer properties (.LeftHeader, .CenterHeader, .RightHeader, .LeftFooter, .RightFooter) as desired.

You may want the header or footer to instead include the date that the workbook was last saved. (This is what many people really view as the “last edit date.”) The information is visible in the

ExcelTips 2008 Page 398

Page 412: Excel tips 2008

Workbook and File Tips

Properties dialog box for a worksheet (File | Properties | Statistics tab), but Excel has no menu selection or other command that allows you to insert this date into a header or footer. Instead, you must use a macro to add the desired information.

The best way to accomplish the task is to add a macro to the ThisWorkbook object that is triggered just before a workbook is saved:

Private Sub Workbook_BeforeSave(ByVal _ SaveAsUI As Boolean, Cancel As Boolean) Dim sht For Each sht In Sheets sht.PageSetup.CenterFooter = _ "Workbook Last Saved: " & _ Format(Now, "mmmm d, yyyy hh:mm") Next End Sub

This macro steps through each worksheet in the workbook and changes every center footer to have the date that the workbook was saved.

HANGING WHEN OPENING A WORKBOOK

Applies to Excel 97, 2000, 2002, 2003, and 2007

Kary wrote about a problem she was having with a workbook—whenever she would double-click it in Windows, Excel would start, but then freeze before opening the workbook completely.

If this is a problem that happens whenever you open any workbook, it could be because one of the startup files being opened by Excel is corrupted. You can determine if this is the case by instructing Excel not to open these files when it starts. Use the Run option from the Start menu, and run Excel by entering in either of the following lines:

"C:\Program Files\Microsoft Office\Office\Excel.exe" /Automation "C:\Program Files\Microsoft Office\Office\Excel.exe" /Safe

The quote marks are mandatory, and there is a good chance you will need to change the path to the Excel.exe file. When Excel starts with either the /Automation or /Safe switches, it doesn’t load the startup files it normally does. Once Excel starts, turn off automatic recalculation by choosing Tools | Options | Calculation tab and making sure the Manual option is selected.

Now try to open your workbook. If it opens, then you can assume that the problem is somewhere in the startup files. Track them down and make changes or deletions, as necessary. (Other ExcelTips issues have discussed startup files and their locations.) If the workbook doesn’t open,

ExcelTips 2008 Page 399

Page 413: Excel tips 2008

Workbook and File Tips

then the problem is with the workbook itself; it may be corrupted and you may need to recreate it.

Finally, it could be that there really is no problem with the workbook at all. If the workbook is very large and was created in an older versions of Excel, and you are opening it in Excel 2003 or Excel 2007, then there could be a long delay as the workbook is opened. This is because the newer versions of Excel rebuild the calculation tables associated with the workbook; rebuilding those can take some time to do for workbooks with lots of calculations.

FILE FORMATS THAT INCLUDE FIELD FORMATS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Wolfgang often imports CSV files that are created by other programs. When importing he needs to specify to Excel how it should treat the data that it is importing. This causes Wolfgang to wonder if there is a file format that Excel can import that has field formats embedded so that he doesn't have to do any manual work on import.

The short answer is no, there isn’t such a format. Technically you can create an XML-formatted file that uses the new Microsoft Office format of Office 2007, and it can specify what the field formats should be. Such a file consists of only text (like a traditional CSV file) and includes specifiers about how the data should be formatted. (Complete details on how such an XML file should be structured is beyond the scope of this tip.) If you are using an earlier version of Excel (pre-2007), then you can even get add-ons that will allow the XML files to be opened correctly:

http://support.microsoft.com/?kbid=924074

Such an endeavor is undeniably daunting to many people, so you could also simply import your CSV file with no formatting applied, and then use the macro recorder to record how you manually format the freshly imported data. This macro could then be executed every time you import another file that uses the same sort of data as the first CSV file you imported.

(Thanks to Steve Aprahamian, Richard Raciborski, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 400

Page 414: Excel tips 2008

Workbook and File Tips

FIXING "CAN'T FIND FILES" ERRORS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jamie is having problems starting Excel properly. When he starts the program he gets two error messages: One says that Excel cannot find the file Microsoft.xls, and the other that it cannot find the file Office.xls. After clicking OK to both of the errors, Excel works normally.

When you start Excel, it should do just that—start right up. Error messages like the ones mentioned mean that Excel thinks it should be able to find a couple of files, but it cannot. The two files in this instance are both XLS files, so they are workbooks that Excel thinks it should be able to open.

In doing searches of systems with newly installed versions of Excel, there are no workbooks with the names Microsoft.xls or Office.xls, so I can only conclude that the files were added to the machine by a user, by a third-party program, or by some add-in for Excel.

The first thing to try is to force Excel to re-register itself in the Windows Registry. You do this at the command prompt (or after choosing Start | Run), using a command line like the following:

"C:\Program Files\Microsoft Office\Office\Excel.exe" /Regserver

The quote marks around the full path are mandatory, and there is a good chance that the path name to Excel.exe will be different on your system than what is shown here. After executing this command line, try starting Excel again and see if you get the same errors; you may very well not get them.

If you continue to get the errors, then search your system for the XLSTART folder. Make sure there is nothing in there, such as a workbook. Anything in the folder is automatically loaded by Excel when it starts, and—if there is a workbook present—it could reference the two missing files.

LOADING UNWANTED FILES AT STARTUP

Applies to Excel 97, 2000, 2002, 2003, and 2007

Stephen ran into a problem using Excel—every time he starts the program, Excel tries to load all the files in the root directory as spreadsheets. This, of course, messes up his use of Excel.

This problem typically occurs when someone has instructed Excel to load those files. To undo this, follow these steps if you are using a version of Excel prior to Excel 2007:

ExcelTips 2008 Page 401

Page 415: Excel tips 2008

Workbook and File Tips

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the General tab is selected.

The General tab of the Options dialog box.

3. Make sure the Default File Location option is not set to C:\. 4. Make sure the Alternate Startup File Location option is not set to C:\. (In Excel 2002

and Excel 2003, the name of this option is At Startup, Open All Files In.) 5. Click on OK.

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Save at the left side of the dialog box. 3. Make sure the Default File Location option is not set to C:\. 4. Click Advanced at the left side of the dialog box. 5. In the General section, make sure the At Startup, Open All Files In option is not set to

C:\. 6. Click on OK.

The options in steps 3 and 4 (first set of steps) or steps 3 and 5 (second set of steps) represent directories whose files Excel should load whenever you start the program. If you don’t want

ExcelTips 2008 Page 402

Page 416: Excel tips 2008

Workbook and File Tips

Excel to load any files when it starts, just clear the settings in these options, or make sure they are set to directories that really contain things you want loaded.

It is possible that if one of these options is set to C: (the root directory on a Windows system), and you have a lot of files in the root directory, then Excel will try to load so many files that you won’t be able to use it at all in order to perform these steps. If that happens to you, use Windows to move the files from the root directory to a temporary directory, and then start Excel. (You won’t have to move any of the folders in the root directory, just files.) Once you change the settings in Excel, as described above, you can use Windows to move the files from the temporary directory back to the root directory.

ACCESSING OLD EXCEL DATA Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have used computers for some time, you have accumulated quite a bit of data over the years. Unfortunately, not all that data is accessible any more. I have very old spreadsheet data stored in Multiplan files, and if I search around a bit longer, I can probably find some disks containing VisiCalc information.

Accessing information stored in old formats can be a big problem. If you update your computer every couple of years—hardware and software—there is a very good chance that you have old data that is essentially lost because you can no longer load it into a program.

There are several approaches you can take if you need to access older data. First, you can install the older versions of the software on your system (if you have the software) and then save the data files in some “exchange” format. For instance, you can save old Multiplan or early Excel information in SYLK format, which can then be read into newer versions of Excel.

Second, you can search through the Microsoft Knowledge Base for information on doing conversions. For instance, when I searched through the Knowledge Base for “Multiplan,” I was able to find several pertinent articles that discussed different ways to update information for use with recent versions of Excel. The Microsoft Knowledge Base is available online at this URL:

http://support.microsoft.com/

Third, you could contact a user in your community who has the older version of the software and use their computer to do the upgrade. Many times you can find such users through a local user’s group or through a computer store that sells used computer systems.

Finally, there are companies that specialize in doing data conversions. You can search on the Web for such companies and get quotes for updating your data.

ExcelTips 2008 Page 403

Page 417: Excel tips 2008

Workbook and File Tips

LOCKED FILE PUZZLE Applies to Excel 97, 2000, 2002, 2003, and 2007

Eric was having a problem with one of his workbooks. It seems that every time he opened the workbook he saw a dialog box that said the file was locked and that he would have to save changes under a different name. Even when he does that, the dialog box still appears on the new workbook.

The first thing to try is to restart your machine, or copy the workbook to a different folder on your system. The reasoning for this is simple: Sometimes Excel can get confused and think that a file is “locked” by another user, when in fact it is not. Restarting or copying the workbook can help clear the confusion.

The most likely cause of this problem, however, is that there is some sort of macro running when the workbook is opened. Even if you save the workbook under a different name, the macro would be saved with the new workbook, and the process would repeat itself all over again. To test this, try the following:

1. Open the workbook like normal, dismissing the dialog box. 2. Select all the worksheets in the workbook. (Click on the left-most worksheet, then hold

down the SHIFT key as you click on the right-most worksheet.) 3. Choose Move or Copy Sheet from the Edit menu. Excel displays the Move or Copy

dialog box. (To display the proper dialog box in Excel 2007, display the Home tab of the ribbon. Click the Format tool in the Cells group, and then select Move or Copy Sheet from the resulting submenu.)

The Move or Copy Sheet dialog box.

4. Using the To Book drop-down list, choose (new book).

ExcelTips 2008 Page 404

Page 418: Excel tips 2008

Workbook and File Tips

5. Make sure the Create a Copy check box is selected. 6. Click OK.

Now you have two workbooks: the one you opened and a new, unnamed workbook. Close the original workbook without saving, and then save the new workbook under any name desired. You should be able to open the new workbook with no problems, as macros are not copied in the above steps.

If you cannot complete step 3 because the Move or Copy Sheet option is not available, it means that the worksheets have been protected. You would need to remove protection from the worksheets before you could copy them.

DUPLICATE WORKBOOKS OPENING

Applies to Excel 97, 2000, 2002, 2003, and 2007

Joan has a problem with one of her Excel workbooks: When she opens it, Excel always “replicates” the workbook. Once opened, Joan reports that she has two workbooks showing in the task bar. Both contain the proper workbook name, but one is followed by a 1 and the other followed by a 2.

Believe it or not, this problem is actually a feature of Excel. What you are seeing is two windows, both open on the same workbook. Excel allows you to create multiple windows on the same workbook by using the Window | New Window command or, in Word 2007, by displaying the View tab of the ribbon and clicking the New Window tool. Each new window has the same name, except they have a suffix consisting of a colon and a number that indicates the window number (1, 2, 3, etc.).

When you save a workbook that has multiple windows, the next time you open the workbook it will display the same number of windows. If you want to get rid of some of the windows, you need to close them. You do this by clicking the Close Window control. (This is the X at the upper-right corner of the worksheet, not at the upper-right of the program window. It is black, not red, although it should be just below the red X. If you hover the mouse pointer over it, you’ll see the ToolTip “Close Window” appear.)

Once you close any windows you don’t want, save the workbook again. The next time you open it, you should see only a single window.

ExcelTips 2008 Page 405

Page 419: Excel tips 2008

Workbook and File Tips

SAVING IN TWO LOCATIONS Applies to Excel 97, 2000, 2002, 2003, and 2007

Sam asked if there was a way to save the same workbook to two separate locations. For instance, one copy could be saved to the normal network location, and the other to a folder on the local hard drive.

There are any number of ways that this can be done. For instance, you could create your own macro that saves two versions of the same workbook. The macro could be assigned to a toolbar button, and then the button clicked when you want to save both copies. (In other words, you would bypass the normal Save function all together.)

Another approach is to make a small adjustment to how Excel saves the workbook. For instance, the following macro would be added to the ThisWorkbook object for the workbook:

Private Sub Workbook_BeforeSave(ByVal _ SaveAsUI As Boolean, Cancel As Boolean) With ThisWorkbook .SaveCopyAs ("c:\Backups\Backup of " & .Name) End With End Sub

This is an event handler, and it is triggered every time you go to do a save on the workbook. At that point, the macro is executed and a copy of the workbook is saved in the specified path on your local hard drive.

SHORT-LIVED BOOK1 Applies to Excel 97, 2000, 2002, 2003, and 2007

Fred ran into a problem with Excel—when he first starts the program, Excel opens Book1 as it should. Then, after a second or two, it switches to Book2 where Fred can start working. He’s curious as to why Excel switches to Book2, and what happened to Book1.

Startup problems in Excel can be rather tricky to track down, but there are a few things you should check. First, make sure that there is nothing in the XLStartup folder on your system; it is possible that Book2.xls is stored there, and Excel is opening it whenever you start the program.

Of course, it is also possible that errant add-ins are making the switch, or that a template is responsible for it. You’ll need to do some detective work in this case. A good place to start is this Web page, maintained by Excel MVP Jan Karel Pieterse:

http://www.jkp-ads.com/Articles/StartupProblems.asp

ExcelTips 2008 Page 406

Page 420: Excel tips 2008

Workbook and File Tips

FINDING THE PARENT FOLDER Applies to Excel 97, 2000, 2002, 2003, and 2007

Lawrence asked if there was a way to devise a formula that would return the name of the parent folder for the current workbook file. He wanted this to return just the folder name, and he wanted it to be derived using a regular Excel formula, not a macro or user-defined function.

The answer is, yes, it is possible to figure out the parent folder using a formula, but the formula is rather long and complicated. There were several examples of formulas submitted by readers; the following formula is the most concise:

=MID(CELL("filename"), FIND(CHAR(1), SUBSTITUTE(CELL("filename"), "\", CHAR(1), LEN(CELL("filename")) - LEN(SUBSTITUTE(CELL("filename"), "\", "")) - 1)) + 1, FIND("[", CELL("filename")) – 2 - FIND(CHAR(1), SUBSTITUTE(CELL("filename"), "\", CHAR(1), LEN(CELL("filename")) - LEN(SUBSTITUTE(CELL("filename"), "\", "")) - 1)))

Please note that this is a real formula; it must appear on a single line in a cell.

The formula works by using the number of backslashes in the complete file path, and then replacing the second to the last slash with an ASCII value of 1. This value is then used as a “positioning aid” to help extract the parent folder’s name.

MERGING MANY WORKBOOKS Applies to Excel 97, 2000, 2002, 2003, and 2007

Joy ran into a problem merging quite a few workbooks together. The majority of the workbooks—about 200 of them, all in a single folder—each contain a single worksheet, but some contain more. The worksheets form each of these workbooks needs to be added to a single workbook.

The easiest way to do merges of this magnitude—particularly if you have to do it often—is with a macro. The following macro displays a dialog box asking you to select the files to merge. (You can select multiple workbooks by holding down the CTRL key as you click each one.) It loops thru the list you select, opening each one and moving all its worksheets to the end of the workbook with the code.

Sub CombineWorkbooks() Dim FilesToOpen Dim x As Integer On Error GoTo ErrHandler Application.ScreenUpdating = False

ExcelTips 2008 Page 407

Page 421: Excel tips 2008

Workbook and File Tips

FilesToOpen = Application.GetOpenFilename _ (FileFilter:="Microsoft Excel Files (*.xls), *.xls", _ MultiSelect:=True, Title:="Files to Merge") If TypeName(FilesToOpen) = "Boolean" Then MsgBox "No Files were selected" GoTo ExitHandler End If x = 1 While x <= UBound(FilesToOpen) Workbooks.Open FileName:=FilesToOpen(x) Sheets().Move After:=ThisWorkbook.Sheets _ (ThisWorkbook.Sheets.Count) x = x + 1 Wend ExitHandler: Application.ScreenUpdating = True Exit Sub ErrHandler: MsgBox Err.Description Resume ExitHandler End Sub

In the process of adding the worksheets to the end of the workbook, Excel will automatically append a (2), (3), etc. when duplicates worksheet names are detected. Any formulas in the book referring to other sheets will also be updated to reflect the new names.

USING YOUR OWN FILE EXTENSIONS

Applies to Excel 97, 2000, 2002, 2003, and 2007

By default, versions of Excel prior to Excel 2007 use an XLS extension for all workbook files and Excel 2007 uses XLSX or XLSM, depending on whether the workbook contains macros or not. If you don’t want to use the default file extensions for a workbook you are saving, you can pick something different. (You may want to use a different extension if you are trying to hide the fact that the file is an Excel workbook.)

If you try to use a different file name extension by including it when you save the file, Excel still appends the XLS extension. For instance, if you explicitly save a file as MyFile.mef, Excel will still save it as MyFile.mef.xls.

ExcelTips 2008 Page 408

Page 422: Excel tips 2008

Workbook and File Tips

If you don't want Excel to do this, then simply enclose your file name in quotes when you save under a new name. Thus, you would use the name "MyFile.mef" (with the quotes) and that is the file name which Excel will use.

In addition, if you save a workbook with a different extension (not one of the defaults used by Excel), then Excel won't show the workbook by default when you use the Open command. To see all your varied-extension files, you need to follow these steps:

1. Displays the Open dialog box. 2. In the File Name field, enter an asterisk, period, and your desired extension. For

instance, you could enter "*.mef" (without the quotes). 3. Press ENTER. The desired files should be listed in the directory. 4. Select the file you want to open. 5. Click on Open.

GETTING RID OF "COPY OF" Applies to Excel 97, 2000, 2002, 2003, and 2007

Anna Lea has a read-only workbook that she uses as a template for a daily report that she creates. The file name is quite long, and ends in 20507xx. When she double-clicks on the workbook, it opens and shows that it is read-only. She makes her changes, and then uses Save As. Since Excel recognizes that the file is read-only, it suggests a new file name that consists of the old one with the words “Copy of” as a prefix. Anna wants to get rid of the “Copy of” so that all she has to do is change the “xx” portion of the file name to create the day’s report.

The “Copy of” verbiage is added by Excel automatically. If you are using Save As, there is no way to change this without using a macro to control the saving process. The following macro, saved as part of the ThisWorkbook object, shows how this can be done.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI _ As Boolean, Cancel As Boolean) Dim sTemp As String Dim sCheck As String sCheck = "xx.xls" If SaveAsUI Then sTemp = ThisWorkbook.Name If Right(sTemp, Len(sCheck)) = sCheck Then sTemp = Left(sTemp, Len(sTemp) - Len(sCheck)) sTemp = sTemp & Format(Now, "dd") & ".xls" sTemp = ThisWorkbook.Path & "/" & sTemp ThisWorkbook.SaveAs Filename:=sTemp, _ FileFormat:=xlNormal Cancel = True

ExcelTips 2008 Page 409

Page 423: Excel tips 2008

Workbook and File Tips

End If End If End Sub

The macro first checks to see if the Save As dialog box is about to be displayed. If it is, then the workbook’s name is assigned to the sTemp variable. This name is checked to see if the last six characters are “xx.xls” (from the sCheck variable). If they are, then the workbook is assumed to be the one where the name needs to be changed.

If you are using Excel 2007, you’ll want to change the line that assigns the value to sCheck so that it checks for either “xx.xlsx” or “xx.xlsm”, depending on your needs. You’ll also want to change

First the “xx.xls” characters (or whatever you’ve assigned to sCheck) are stripped from the end of the workbook name. Then today’s date (two digits, for the day of the month) is appended to the file name, followed by the “.xls” suffix; this suffix should be changed if you are using Excel 2007. Finally, the workbook is saved using this newly constructed filename. The Cancel flag is set to True so that the Save As dialog box never displays.

Note that the name is never checked for the verbiage “Copy of”. The reason for this is simple: The wording is not added to the start of the file name until the actual Save As dialog box is displayed. Before that point (when this event handler is being executed) the workbook name remains unchanged.

AVOIDING SCIENTIFIC NOTATION ON FILE IMPORTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Mark has a text file that he routinely imports into an Excel workbook. The file is created by a different program, and one of the columns in the file contains numbers, the letter “e,” and then more numbers. When importing the file into Excel, the column is converted to scientific notation by Excel, rather than being treated as text.

Chances are good that the file you are importing—the one created by the other program—is a CSV file. This means that the values in the file are “comma separated,” and easily understood by a program such as Excel. If you open a CSV file, Excel just “does it,” without asking very much about the data being imported. This is where the problem would occur—Excel is simply making the assumption that the problem column contains numeric values in scientific notation.

The solution is to get Excel to ask you how you want the data imported. The key to doing this is to rename the file you are importing. Change the file’s extension from CSV to something else, such as DAT. When you then try to open the file in Excel (start Excel and then use Open to

ExcelTips 2008 Page 410

Page 424: Excel tips 2008

Workbook and File Tips

locate and try to open the newly renamed file), the Import Wizard starts. This wizard gives you complete control over how Excel treats your incoming data.

Most of the wizard is self-explanatory. You’ll want to pay particular attention to the third step of the wizard which allows you to specify the data type for each column of the import data. The default data type for each column is “general,” which means that Excel tries to interpret the data based upon its regular parsing routines. Instead, you want to locate the column that contains the problem data and specify that the column should be treated as text—exactly what you want.

If you have to import this type of file regularly, you might want to create a macro that does the import for you. All you need to do is use the macro recorder to record each step of the Import Wizard. You can then replay the macro anytime you need to import the file again.

OPENING A WORKBOOK TO A SPECIFIC WORKSHEET

Applies to Excel 97, 2000, 2002, 2003, and 2007

Marcus wonders if it is possible to somehow configure a workbook so that it opens on the same worksheet tab each time it is opened, rather than on the worksheet tab that was displayed when the workbook was last saved. The short answer is that you can do this—provided you use a macro. (There is no way to do it without a macro.)

There are two ways you can set up your macro. First, you can use a traditional Auto_Open macro that is automatically run whenever a workbook is opened:

Sub Auto_Open() Sheets(“OpenToThisSheet”).Select End Sub

All you need to do is replace OpenToThisSheet with the name of the worksheet you want displayed when the workbook opens. A similar approach is to create a Workbook_Open event handler:

Sub Workbook_Open() ActiveWorkbook.Sheets("OpenToThisSheet").Activate End Sub

Again, change the sheet name to reflect the name of the actual sheet you want displayed. This event handler should be added as part of the ThisWorkbook module.

(Thanks to Andrija Vrcan, Wim de Groot, Hafizullah Chishti, Steve Aprahamian, Dave Latham, Alain M. Quere, Alec Whatmough, Luke Hannath, Karen Hine, Richard Raciborski, Gosta Berg, Al Grant, Mike Hirsch, Seoul Mate, Bob Hall, and Russell Hendel for contributing to this tip.)

ExcelTips 2008 Page 411

Page 425: Excel tips 2008

Workbook and File Tips

AUTOMATICALLY HIDING PERSONAL.XLS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Ken is having a problem with his Personal.xls workbook. When he needs to work on it, he unhides it. If he forgets to rehide it when he is done, then the next time he starts Excel the Personal.xls workbook is immediately visible. Since it looks like a new, blank worksheet, he often starts typing in it and this messes up her Personal.xls workbook. He wonders if there is a way to automatically force Personal.xls to be hidden if he forgets to hide it manually.

There are a couple of things you need to keep in mind. First, if you are only making changes to macros in Personal.xls, you don’t need to unhide the workbook to work on those macros. Instead, display the VBA editor and use the object browser to make sure you are working on the macros in the Personal.xls workbook. When you are done editing the macros, you can save them without ever needing to make the workbook visible.

If this still doesn’t work for you—perhaps you have some other reason to make Personal.xls visible—then you could make some sort of editing change to the first worksheet in the workbook. For instance, place the text “THIS IS PERSONAL” into cell A1 of the workbook. Do something to make it stand out (bold, colors, flashing, etc.), and you will never again miss that you are working in the Personal.xls workbook when you first start Excel.

If you want a macro approach to make sure that the workbook is hidden, then you could add the following code to the ThisWorkbook object for Personal.xls:

Private Sub Workbook_BeforeClose(Cancel As Boolean) Windows("PERSONAL.XLS").Visible = False ThisWorkbook.Save End Sub

The macro is executed just before the workbook is closed (when happens when Excel is exited). It hides the workbook and then saves it. That way, the next time you start Excel, Personal.xls will be automatically hidden.

(Thanks to Cliff Edwards, Steve Aprahamian, Richard Raciborski, Henric Bladh, Dennis Swearingen, Ron Glatley, and Chris Purtill for contributing to this tip.)

ExcelTips 2008 Page 412

Page 426: Excel tips 2008

Workbook and File Tips

LOSING DATA IN A SHARED WORKBOOK

Applies to Excel 97, 2000, 2002, 2003, and 2007

Karen described a problem in which a shared workbook, stored on a company network, periodically loses all the data it previously contained. In trying to track down the problem Karen did tests where she and her coworkers tried to open the file at the same time and save it at the same time, but all the tests left the data intact. Still, she reports that there are times when the workbook data is simply erased; wiped clean.

This problem is, perhaps, a prime example of why many people refuse to trust shared workbooks in Excel. Many folks have shared experiences where data has become corrupted, information is overwritten, or data just outright disappears. All the problems were traced to the fact that a workbook was shared, and the problems went away when the sharing was turned off.

This leads to the first suggestion: don’t share the workbook. If you “unshared” it, then only a single person can open the workbook at a time, which reduces complexity and decreases the chances of corruption. If the data contained in the workbook is extensive and it must be shared among multiple users, consider converting to a program that is designed for better data integrity in a multi-user environment, such as Access.

If this is not possible, consider turning on Track Changes in Excel (an option available when you share the workbook) so that a change history is maintained. This allows you to see who last changed a workbook. If you open the workbook and find the data missing, checking the change history may actually disclose that the data was deleted—probably inadvertently—by a user.

Of course, it is possible that the change history may not provide the information that you hope it will. The reason that sharing a workbook can lead to data corruption is the way in which Excel allows users to work with data. In a program such as Access, data is fetched and worked with on a record-by-record basis. While the record is in use by a user, no other user can make changes to the record, but they can make changes to other records.

In Excel, the entire workbook is transferred to the user’s computer, not just a single record from the data in the workbook. In a shared-workbook scenario, this means that multiple copies of the workbook are actually open at the same time, and Excel is charged with resolving potential conflicts in data. Consider the following scenario:

• User 1 opens the workbook, which means that a copy of the workbook now resides in his system memory.

• Ten minutes later User 2 opens the shared workbook. This version, now residing in the memory of User 2’s system, does not contain any of the changes done during the last 10 minutes by User 1.

• Five minutes later User 2 saves the shared workbook, but continues working.

ExcelTips 2008 Page 413

Page 427: Excel tips 2008

Workbook and File Tips

• Two minutes later User 3 opens the shared workbook. This version is the one that User 2 just saved, and doesn’t include anything done by User 1 or any additional changes made by User 2 since last saving.

• Thirteen minutes later, all three users save their versions of the shared workbook and exit Excel.

In this thirty-minute scenario, can anyone tell which of the users’ changes are saved in the final version of the workbook? Which changes should be saved? When you consider the ramifications of such a scenario (and this scenario is not uncommon), then you can see why many people suggest not using Excel in a shared environment.

PROBLEMS WITH DEFAULT WORKBOOK AND WORKSHEET TEMPLATES

Applies to Excel 97, 2000, 2002, 2003, and 2007

David decided that he wanted to create default templates for Excel. He created both book.xlt and sheet.xlt files and stored both templates in the xlstart folder. He then restarted Excel, whereupon he was greeted with the message "The file is not in a recognizable format." If he clicks OK, the workbook opens, appearing as garbage. After a fraction of a second, another window opens, displaying a blank worksheet with the expected formatting on the top row and left column. David knows the template is not really corrupted; he can copy it to a different folder and open it just fine in Excel. The error only happens when he puts the templates in the xlstart folder.

Checking to make sure that the template is not corrupt is a good first step. It is also good that you are trying to store these templates in xlstart—this is where Excel expects your default templates to be. (This has been discussed in other issues of ExcelTips.) You should also try the following ideas:

• Make sure that the template is really a template. In other words, use the Format setting in the Save As dialog box to specify you are saving an Excel template. (Don’t just change the filename extension on the workbook file and expect it to recognized as a template by Excel.)

• Check to see if there are any other files in the xlstart folder or in the default startup folder. (You need to check both places.) If there are other files, you might want to move them to make sure that they aren’t causing problems with loading the default templates.

If the problem still exists, then you may really have a corrupt file after all. There could be something out of kilter in the file that allows it to be loaded directly into Excel, but doesn’t allow it to be loaded as a default template. You can try to fix any minor corruption by saving the file in HTML format, restarting Excel, loading the HTML file, and resaving it as a template.

ExcelTips 2008 Page 414

Page 428: Excel tips 2008

Workbook and File Tips

(Thanks to Steve Aprahamian for contributing to this tip.)

IMPORTING HUGE DATA FILES Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel has a limit on the number of rows you can have in a worksheet—up to 65,535 rows prior to Excel 2007. It is very possible, however, to have a raw data file that has more than this number of rows. If you need to import that file into Excel, then doing so can appear almost impossible without upgrading to Excel 2007. Even in Excel 2007 you may run into the limits of your system if you try to import a file that has hundreds of thousands of rows. There are a couple of things you can do, however.

One possibility is to make copies of the raw text file (the one you want to import) and then cut the size of each file down. For instance, if you have a total of 110,000 rows you need to import into Excel, and you are operating under the 65,535-row limit, you could make two copies of the raw text file. Delete the second half of the first text file and the first half of the second. Thus, you can import the first file (now 55,000 rows) into one worksheet and the second file (also 55,000 rows) into the second.

If you don’t want to break up your input files, you might consider importing the file into Access. Unlike Excel, Access has virtually no limit on the number of rows you can import. You could then either work with the file in Access, or export portions of the file to use in Excel.

Finally, you could use a macro to import the records in the large source file. There are many ways you can do this, but the basic idea behind any approach is to fetch each row from the source file and place it in a new row of a worksheet. The macro must keep track of how many rows it’s placed, and switch to a new worksheet, if necessary.

Public Sub LoadFile() Dim strLine As String Dim I As Long Dim J As Long Dim iLen As Integer Dim iSh As Integer Dim lL As Long Dim sDelim As String Dim MaxSize As Long sDelim = Chr(9) MaxSize = 65000 I = 0 Open "C:\MyDir\MyFile.txt" For Input As #5 Do While Not EOF(5) iSh = (I / MaxSize) + 1 lL = I Mod MaxSize Line Input #5, strLine

ExcelTips 2008 Page 415

Page 429: Excel tips 2008

Workbook and File Tips

If Right(strLine, 1) <> sDelim Then strLine = Trim(strLine) & sDelim End If J = 0 Do While Len(strLine) > 1 iLen = InStr(strLine, sDelim) Worksheets("Sheet" & iSh).Offset(lL, J).Value = _ Trim(Left(strLine, iLen - 1)) strLine = Trim(Right(strLine, Len(strLine) - iLen)) J = J + 1 Loop I = I + 1 Loop Close #5 End Sub

The macro assumes you have enough worksheets already in your workbook to contain the data, and that they are numbered Sheet1, Sheet2, Sheet3, etc. Two variables you’ll want to check in the program are the settings of sDelim and MaxSize. The first specifies what character is used as a field delimiter in the information that is being read. The second specifies the maximum number of rows you want on each worksheet. (Don’t set MaxSize greater than whatever your version of Excel will allow.)

Finally, note that the macro opens the text file MyFile.txt. You’ll want to change this Open statement so that it opens the real source file you want to import.

CSV FILE OPENS WITH DATA IN A SINGLE COLUMN

Applies to Excel 97, 2000, 2002, 2003, and 2007

Jan uses a program to create a CSV file. This file can then be opened in Excel for further analysis. When Jan double-clicks the CSV file in Windows, Excel starts and then loads the file. The problem is that the file, when opened, isn’t parsed by Excel. Instead of the comma-separated values being in different columns, every record appears in a single column.

The reason for this behavior is probably quite simple and has to do with the format in which the data is stored in the CSV file by the non-Excel program. To understand that, it is critical to understand how Excel opens CSV files.

When you open a CSV file in Excel (either by double-clicking in Windows or by using File | Open in Excel), the program treats any commas in the file as delimiters. This makes sense; after all, the file is supposed to contain comma-separated values (CSV). You cannot override this automatic filtering when opening the file.

ExcelTips 2008 Page 416

Page 430: Excel tips 2008

Workbook and File Tips

So, how does Excel treat the incoming data? Consider, for a moment, if the CSV file contains the following four records:

a,b,c,d,e "a,b,c,d",e a,"b,c",d,e "a,b,c,d,e"

As far as Excel is concerned, the first record has five fields, separated by commas. The second record has only two fields, “a,b,c,d” and “e.” The inclusion of the quote marks around “a,b,c,d” causes Excel to treat the string as a discrete unit. In other words, Excel ignores any commas that may appear between the quote marks.

Given the effect that quote marks have, you can probably figure out how Excel interprets the third and fourth records. In this case, the third record has only four fields, and the fourth record is interpreted to have only a single field.

What does this have to do with the CSV file that seems to be loading incorrectly? It is very possible that the program creating the CSV file is putting a pair of quote marks around each record. This would cause everything in the record to be treated as a single field by Excel, which means it ends up in a single column when the CSV file is loaded.

There are a couple of ways to verify this. The first is to simply open the CSV file with Notepad and look at each record. (Right-click on the CSV file in Windows, choose Open With | Choose Program, then choose Notepad.)

Another way is to rename the CSV file so that its extension is not .csv but .txt instead. When you choose to open this file within Excel, the Text Import Wizard is started. Choose Delimited, click Next, and then you can see what delimiters are chosen. Pay attention to the Text Qualifier; if you change it, you can immediately see at the bottom of the dialog box how Excel interprets the file’s records.

If you find that there are extra quote marks around each record in the CSV file, there are three things you can do. The first is to change the program that creates the CSV file so that it doesn’t add the extra quote marks—you’ll then be able to import with no problem. The second is to go ahead and load the CSV file into Excel, such that each record is in column A. Note that the surround quote marks are gone, stripped out by the import process. This means that you can now use the Text to Columns wizard to separate the data in column A into individual columns.

Finally, the third thing you can do is to create a macro that will open the CSV file and parse it for you. This is particularly helpful if you will be opening, over time, many CSV files that have the exact same format. Your macro could be as elaborate as desired, even formatting columns and processing data as it is imported. Ways to create macros such as this are found in other issues of ExcelTips.

ExcelTips 2008 Page 417

Page 431: Excel tips 2008

Workbook and File Tips

IMPORTING MANY FILES INTO EXCEL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Andrew asked if there is a way to import many different files into Excel, all using the same import specifications. For instance, when you choose to import a comma-delimited text file, Excel’s import filter asks you a series of questions about how the import should be done. If you are importing a single file, this is not a problem. If you have fifty or sixty files to import, answering the questions over and over again can get very tedious very quickly.

The short answer is that there is no way to do a “mass import” in Excel. Some questions asked by the import filter simply need to be asked for each file. The only way around this is to create your own “import” process using a macro. The macro can either open the source file itself, or it can answer the Import Wizard questions, as it sees fit.

Of course, writing such a macro can be a daunting exercise. It is beyond the scope of ExcelTips to attempt such a macro, particularly since the process to be followed during the import can vary so much from one type of input file to another.

GETTING INPUT FROM A TEXT FILE

Applies to Excel 97, 2000, 2002, 2003, and 2007

True to its BASIC roots, VBA allows you to do file input on sequential files. This means you can open and read a sequential text file, loading the information from the file into string variables. The steps are simple. You only have to open the file, get the input, and then close the file. The following code is a common example of reading from a sequential file:

Dim Raw As String Dim NumValues As Integer, J As Integer Dim UserVals() As String Open "MyFile.Dat" For Input As #1 Line Input #1, Raw NumValues = Val(Raw) ReDim UserVals(NumValues) For J = 1 to NumValues Line Input #1, UserVals(J) Next J Close #1

ExcelTips 2008 Page 418

Page 432: Excel tips 2008

Workbook and File Tips

ExcelTips 2008 Page 419

In this example you should note that the first line read from the text file (MyFile.Dat) is assumed to contain a value that indicates how many items are to be read in from the file.

Page 433: Excel tips 2008

Tools Tips

SETTING SPELL-CHECKING OPTIONS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Word includes a spelling checker that you can use to proof the text in your worksheets. There are a few options that you can set for the spelling checker. For instance, you can make sure the spelling checker doesn't check words that are all uppercase or those that have numbers in the word.

To change the spelling checker options, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. You will see the Options dialog box. 2. Make sure the Spelling tab is selected.

ExcelTips 2008 Page 420

Page 434: Excel tips 2008

Tools Tips

The Spelling tab of the Options dialog box.

3. Make changes in the options, as desired. 4. Click on OK.

You can change the same options in Excel 2007 by following these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Proofing.

ExcelTips 2008 Page 421

Page 435: Excel tips 2008

Tools Tips

The proofing options in the Excel Options dialog box.

3. Make changes in the options, as desired. 4. Click on OK.

SPELL-CHECKING UPPERCASE WORDS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel includes a powerful spell-checker that, in reality, does a pretty good job. You can use this tool to locate potential spelling errors in your worksheets. If your worksheets contain lots of acronyms, you’ll find that Excel flags most of them as misspelled words.

You can make sure that Excel ignores uppercase words in any spell-check by following these steps in versions of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Spelling tab is selected.

ExcelTips 2008 Page 422

Page 436: Excel tips 2008

Tools Tips

The Spelling tab of the Options dialog box.

3. Make sure the Ignore Words in UPPERCASE check box is selected. 4. Click on OK.

To accomplish the same task in Excel 2007, follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Proofing.

ExcelTips 2008 Page 423

Page 437: Excel tips 2008

Tools Tips

The Proofing options of the Excel Options dialog box.

3. Make sure the Ignore Words in UPPERCASE check box is selected. 4. Click on OK.

The only downside to this, of course, is if you use all uppercase for section titles or for other special words. In this case, Excel still ignores them, since they are uppercase. Make sure you change the setting of this check box based on the type of work you are doing in your worksheet.

ADJUSTING SPELL CHECK FOR INTERNET ADDRESSES

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you use the spelling checker to examine the text in a worksheet, you might want it to ignore Internet-related data, such as URLs and e-mail addresses. You can instruct the spelling checker to ignore anything that looks like an Internet address by following these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Spelling tab is selected.

ExcelTips 2008 Page 424

Page 438: Excel tips 2008

Tools Tips

The Spelling tab of the Options dialog box.

3. Make sure the Ignore Internet and File Addresses check box is selected. 4. Click on OK.

The steps are different if you are using Excel 2007. Follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Proofing.

ExcelTips 2008 Page 425

Page 439: Excel tips 2008

Tools Tips

The Proofing options of the Excel Options dialog box.

3. Make sure the Ignore Internet and File Addresses check box is selected. 4. Click on OK.

ALLOWING FOR WORDS THAT CONTAIN NUMBERS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Have you ever noticed that one of the side effects of our fast-paced world is the creation of new words? It seems that every day—particularly in the technological or medical fields—that new words are bursting forth on the scene. Some of these words are actually composed of letters and numbers together. For instance, b2b is an acronym (word?) meaning business-to-business.

Normally such words would be flagged by Excel’s spelling checker as being incorrect. If you create worksheets that contain quite a few words that are formed by mixing letters and numbers, you may want to instruct Excel to ignore them. You can do so by following these steps if you are using a version of Word prior to Word 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Spelling tab is selected.

ExcelTips 2008 Page 426

Page 440: Excel tips 2008

Tools Tips

The Spelling tab of the Options dialog box.

3. Make sure the Ignore Words with Numbers check box is selected. 4. Click on OK.

If you are using Excel 2007 then the steps are a bit different:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Proofing at the left side of the dialog box.

ExcelTips 2008 Page 427

Page 441: Excel tips 2008

Tools Tips

The proofing options of the Excel Options dialog box.

3. Make sure the Ignore Words that Contain Numbers check box is selected. 4. Click on OK.

WATCHING CELL VALUES Applies to Excel 2002, 2003, and 2007

There’s a nifty feature added in Excel 2002 (and available in subsequent versions of Excel) that allows you to keep an eye on the value of certain cells. This is really handy in large worksheets. Let’s say that you have a large worksheet, and you want to track the results at two or three cells all of the worksheet. Follow these steps if you are using Excel 2002 or Excel 2003:

1. Right-click a cell you want to watch. Excel displays a Context menu. 2. Choose Add Watch from the Context menu.

That’s it—Excel displays the Watch Window, showing the cell and information about it (name, value, formula, etc.) If you are using Excel 2007 then you cannot simply right-click a cell to add it to the Watch Window. You must follow these steps:

1. Select the cell (or cells) you want to watch. 2. Display the Formulas tab of the ribbon. 3. Click Watch Window in the Formula Auditing group. Excel displays the Watch

Window. 4. Within the Watch Window click Add Watch. Excel displays the Add Watch dialog box,

with the addresses of the selected cells already filled in.

ExcelTips 2008 Page 428

Page 442: Excel tips 2008

Tools Tips

5. Click Add. The cells are added to the list of cells in the Watch Window.

You can add additional cells by following either the two steps (Excel 2002 and Excel 2003) for each of them, or else click the Add Watch button in the Watch Window.

If you close the Watch Window, you can later display it again by choosing View | Toolbars | Watch Window (Excel 2002 and Excel 2003) or by clicking Watch Window on the Formulas tab of the ribbon (Excel 2007). You can also delete cells from the Watch Window by selecting the entry and clicking Delete Watch.

IMPORTING CUSTOM LISTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Custom lists are a rather esoteric Excel feature that allows you to specify ordered lists of information for virtually any purpose. For instance, a list might include a series of classes or workshops, or it might include a series of employee names. Custom lists can be used when sorting data tables, and they can be used by the AutoFill feature.

How you create a custom list from scratch has been covered in other issues of ExcelTips. Rather than creating a list from scratch, however, you might find it easier to import a list from a series of cells already in your worksheet. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Select Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Custom Lists tab is selected.

ExcelTips 2008 Page 429

Page 443: Excel tips 2008

Tools Tips

The Custom Lists tab of the Options dialog box.

3. Click once in the Import List from Cells box. 4. Either enter the address range that contains the list you want imported, or use the mouse

to select the range on the worksheet. 5. Click Import. The values from the selected cells are listed in the List Entries box. 6. Click OK to close the dialog box.

If you are using Excel 2007 then you should follow these steps, instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Make sure Popular is selected at the left of the dialog box. 3. Click Edit Custom Lists. Excel displays the Custom Lists dialog box and hides the

Excel Options dialog box. 4. Click once in the Import List from Cells box. 5. Either enter the address range that contains the list you want imported, or use the mouse

to select the range on the worksheet. 6. Click Import. The values from the selected cells are listed in the List Entries box. 7. Click OK to close the Custom Lists dialog box. The Excel Options dialog box

reappears. 8. Click OK to close the Excel Options dialog box.

ExcelTips 2008 Page 430

Page 444: Excel tips 2008

Tools Tips

You can now use the custom list as you would any other custom list in Excel.

AUTOFILLING FROM A CUSTOM LIST

Applies to Excel 97, 2000, 2002, 2003, and 2007

A great timesaver when entering data is to use Excel’s AutoFill feature. To use the feature, enter enough cells that Excel can figure out how you want to fill the remaining cells in series. For instance, enter 1 and 2 into two cells, or 5 and 10 into two others, or Monday and Tuesday. Select the two cells and then click and drag the Fill handle at the bottom-right corner of the selection border.

As cool as AutoFill is, an even cooler timesaving feature is to define your own series of values that AutoFill can use. Follow these steps if you are using a version of Excel prior to Excel 2007:

1. Select Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the Custom Lists tab is selected.

The Custom Lists tab of the Options dialog box.

3. Select NEW LIST in the Custom Lists list.

ExcelTips 2008 Page 431

Page 445: Excel tips 2008

Tools Tips

4. In the List Entries portion of the dialog box, start typing the items in your fill series, in the order they should appear. For instance, you might type a list of department managers in alphabetic order. Press ENTER at the end of each element.

5. When you are done, click the Add button. 6. Click OK to finish.

If you are using Excel 2007, follow these steps instead:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Make sure Popular is selected at the left of the dialog box. 3. Click Edit Custom Lists. Excel displays the Custom Lists dialog box and hides the

Excel Options dialog box. 4. Select NEW LIST in the Custom Lists list. 5. In the List Entries portion of the dialog box, start typing the items in your fill series, in

the order they should appear. For instance, you might type a list of department managers in alphabetic order. Press ENTER at the end of each element.

6. When you are done, click the Add button. 7. Click OK to close the Custom Lists dialog box. The Excel Options dialog box

reappears. 8. Click OK to close the Excel Options dialog box.

You can now use the custom list for the AutoFill feature. Simply type whatever entry from the custom list you want to start with, select the cell, and then drag the Fill handle. Excel fills the selected cells with the items from your custom list, in order.

VIEWING COMMENTS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to add comments to the cells in your workbook. At some point you may want to view your comments. Simply follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Options from the Tools menu. Excel displays the Options dialog box. 2. Make sure the View tab is selected.

ExcelTips 2008 Page 432

Page 446: Excel tips 2008

Tools Tips

The View tab of the Options dialog box.

3. Select from the three radio buttons in the Comments section of the dialog box. (The meanings of these settings are described shortly.)

4. Click on OK to close the Options dialog box.

If you are using Excel 2007 then you should follow these steps:

1. Click the Office button and then click Excel Options. Excel displays the Excel Options dialog box.

2. Click Advanced at the left of the dialog box. 3. Scroll down until you see the Display section.

ExcelTips 2008 Page 433

Page 447: Excel tips 2008

Tools Tips

The advanced options of the Excel Options dialog box.

4. Select from the three radio buttons in the For Cells with Comments portion of the dialog box. (The meanings of these settings are described shortly.)

5. Click OK to close the dialog box.

Regardless of the version of Excel you are using, notice that there are three possible settings for comments. The three radio buttons are as follows:

• None. This option is selected by default. You can’t see any indication of comments in a workbook if this option is selected. (In Excel 2007 this option is called No Comments or Indicators.)

• Comment Indicator Only. This option results in a small red triangle displayed in the upper-right corner of cells that have comments. (In Excel 2007 this option is called Indicators Only, and Comments on Hover.)

• Comment & Indicator. With this option selected, the comment indicators (red triangles) still appear, but all the comments in your workbook are visible. If you have a lot of comments, then your screen can appear very cluttered very quickly. (In Excel 2007 this option is called Comments and Indicators.)

USING DATA VALIDATION Applies to Excel 97, 2000, 2002, 2003, and 2007

One of the tools provided with Excel allows you to ensure that the data in your workbook is within specific bounds, and therefore of a higher quality than unchecked data. This tool is referred to as data validation, and it allows you to set the bounds applicable to your data.

ExcelTips 2008 Page 434

Page 448: Excel tips 2008

Tools Tips

For example, lets assume you are creating a simple worksheet to calculate the future value of a sum, and that in order to do so, you need input from the user (regular deposit, interest rate, and months). You may want to place limits on the information which can be used in the worksheet. For example, you may want to make sure the user always enters an interest rate between 2.5% and 25%. Follow these steps:

1. Select the cell where the user enters the interest rate. 2. Choose the Validation option from the Data menu. (In Excel 2007 display the Data tab

of the ribbon and click the Data Validation tool in the Data Validation group.) Excel displays the Data Validation dialog box.

The Data Validation dialog box.

3. Use the Allow drop-down list to specify what type of number you want to allow. In this instance choose the Decimal option, indicating you want the user to be able to enter a decimal value. The dialog box changes a bit so you can specify the type of data to be entered.

4. Use the Data drop-down list to specify how you want the information the user is entering to be compared in your validation rule. You can pick settings such as “between” and “greater than.” In this case, you should choose “between,” since you want to specify a range for the interest rate.

5. Specify a minimum and maximum acceptable value for the cell. In the case of this example, the minimum should be .025 (which can also be entered as =2.5%) and the maximum should be .25 (which can be entered as =25%).

6. Click on the OK button.

ExcelTips 2008 Page 435

Page 449: Excel tips 2008

Tools Tips

Effectively, you have set a validation rule that says “accept any decimal value that is between 2.5% and 25%.” If the user tries to add information to the cell that is outside the range you specified, they are notified that they have made an error and a different value must be entered.

SETTING DATA VALIDATION INPUT MESSAGES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Once you have defined a validation rule for the data in a cell, Excel allows you to easily define a message that should appear whenever the cell is selected. These messages are called input messages, and their purpose is to help the user understand what information they should enter in the cell. To enter a data validation input message, follow these steps:

1. Select the cell for which you want to define the messages. 2. Choose the Validation option from the Data menu. (In Excel 2007 display the Data tab

of the ribbon and click the Data Validation tool in the Data Validation group.) Excel displays the Data Validation dialog box.

3. Set any data validation rules desired. 4. Click on the Input Message tab.

The Input Message tab of the Data Validation dialog box.

5. Enter a message in either field in the dialog box, as desired. 6. Click on the OK button.

ExcelTips 2008 Page 436

Page 450: Excel tips 2008

Tools Tips

Notice that Excel allows you to specify both a title and body for your data validation message. The only difference between the two is that the title appears on its own line and is shown in a bold typeface. You can define any message you desire. When you later select the cell, the data validation messages appear in their own message box near the selected cell.

CHANGING AUTOFILTER DROP-DOWN ARROW COLORS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Gus asked if there was a way to change the color of the drop-down arrows that appear at the top of each column when AutoFilter is turned on. When a filter is not applied to a column, the drop-down arrow is black; when a filter is applied, the drop-down arrow is navy blue. Gus wanted to change the colors because there isn’t enough contrast between black and navy blue on his monitor.

Unfortunately, it appears that the color of the drop-down arrows is hard-coded into Excel and cannot be changed. You can try a workaround, if you desire, that would instead color the first cell in each of the filtered columns. Add the following macro to a regular module in the workbook:

Sub ColorDisplayFilter() Dim flt As Filter Dim iCol As Integer Dim lRow As Long iCol = 0 lRow = ActiveSheet.AutoFilter.Range.Row Application.EnableEvents = False For Each flt In ActiveSheet.AutoFilter.Filters iCol = iCol + 1 If flt.On Then Cells(lRow, iCol).Interior.Color = vbYellow Else Cells(lRow, iCol).Interior.ColorIndex = xlColorIndexNone End If Next flt Application.EnableEvents = True End Sub

The code steps through the filters for a worksheet and, if the filter is active for a column, colors the first cell yellow. If the filter is not active, then it gets rid of the yellow color.

To trigger the routine so that it runs automatically, there are two things you need to do. First of all, you need to add the following macro to the thisWorkbook object:

ExcelTips 2008 Page 437

Page 451: Excel tips 2008

Tools Tips

Private Sub Workbook_SheetCalculate(ByVal Sh As Object) If Sh.AutoFilterMode Then ColorDisplayFilter End Sub

This triggers every time the worksheet is calculated. If the AutoFilterMode property is True, then the coloring macro is executed.

The second thing you need to do is add a SUBTOTAL formula to your worksheet. Assuming that column A is one of the columns in the filter, you could add the following to the worksheet:

=SUBTOTAL(9,A:A)

The SUBTOTAL function is recalculated every time a filter is changed, so this helps ensure that the coloring macro is executed. The formula can be hidden, if desired, but it must be on the worksheet that has the filter to ensure that the sheet triggers the event.

USING AUTOCORRECT Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel includes a handy tool that is included in most Office applications: AutoCorrect. The purpose of AutoCorrect is to automatically change things you type, as you type them. This may sound strange, but it can really be a benefit. For instance, if you know you always misspell a certain word, you can force Excel to recognize that word and replace it with the proper one. Similarly, you can define short codes that can be automatically replaced with long words or phrases.

To add information to AutoCorrect you use the AutoCorrect dialog box. How you display it depends on the version of Excel you are using:

• Excel 97: Choose AutoCorrect from the Tools menu. • Excel 2000: Choose AutoCorrect from the Tools menu. • Excel 2002: Choose AutoCorrect Options from the Tools menu. • Excel 2003: Choose AutoCorrect Options from the Tools menu. • Excel 2007: Click the Office button, click Excel Options, click Proofing, and then click

AutoCorrect Options.

Near the bottom of the AutoCorrect dialog box is a list of AutoCorrect entries. Each entry is made up of two parts; the part on the left is what you would type, and the part on the right is what Excel automatically uses instead of what you typed.

ExcelTips 2008 Page 438

Page 452: Excel tips 2008

Tools Tips

The AutoCorrect dialog box.

To add your own custom AutoCorrect entries, you do it using the Replace and With fields. All you need to do is type in the Replace field what you want Excel to recognize and in the With field what you want it replaced with. For instance, let’s say you worked for the FDA, and you wanted Excel to replace “FDA” with “Food and Drug Administration,” as you typed. All you would do is place “FDA” in the Replace field and “Food and Drug Administration” in the With field, and then click your mouse on Add.

ADDING AND USING A COMBO BOX

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel includes several different form controls that you can add to your worksheets. One of these controls is a combo box. This control allows you to pick an option from a drop-down list, and then determine what was picked. To create a combo box, follow these steps:

Somewhere in your worksheet, create a list that specifies what you want to appear in the combo box. For instance, if you have a list of names you want to appear in the combo box, create that

ExcelTips 2008 Page 439

Page 453: Excel tips 2008

Tools Tips

list of names in your worksheet. (For this example, let’s assume that you create the list in cells K7 through K13.)

1. In versions of Excel prior to Excel 2007 make sure the Forms toolbar is displayed. (Choose View | Toolbars | Forms.) In Excel 2007, click on the Developer tab of the ribbon. (The controls are visible when you click the Insert tool in the Controls group on the ribbon.)

2. Click on the Combo Box tool in the toolbar or ribbon. The mouse pointer changes to a small crosshair.

3. Create the actual combo box by clicking and dragging to define the parameters of the control. When you release the mouse button, the combo box appears in your worksheet.

4. Right-click on the newly created combo box. A Context menu appears. 5. Choose the Format Control option from the Context menu. Excel displays the Control

tab of the Format Control dialog box.

The Control tab of the Format Control dialog box.

6. In the Input Range box, specify the range used by the list you created in step 1. (For instance, K7:K13.) You can also click once in the Input Range box and then use the mouse to select the range in the worksheet.

7. In the Cell Link box, specify the worksheet cell that you want to contain the index value of what is selected in the combo box.

ExcelTips 2008 Page 440

Page 454: Excel tips 2008

Tools Tips

8. Click on OK.

Your combo box should now work properly. If you click on the down-arrow to the right of the combo box, you should see the items from you list. If someone selects an option in the combo box, the cell you specified in step 7 is updated to contain the relative position of the item selected in the combo box. In other words, if some selects the fourth item in the combo box, then the cell specified in step 7 will contain the value 4. (Similarly, if you change the value at that cell—the one specified in step 7—to a different value, then Excel changes what is displayed in the combo box.)

INDEPENDENT RADIO BUTTONS Applies to Excel 97, 2000, 2002, 2003, and 2007

Larry is using Excel to put together a way to track his performance at bowling. As part of his system, he would like to use the Controls toolbox to add radio buttons (sometimes called option buttons) to his worksheet, one for each of the ten pins. He would like a way to click on the radio buttons representing the pins he left standing after the first roll of the ball.

The problem is that radio buttons are not designed to allow multiple selections. When there are multiple radio buttons in a group, only one of the radio buttons in that group can be selected at a time. (This would be acceptable if Larry never left more than one pin standing after each roll, but such an expectation may be unreasonable.)

There are two options that can be tried. The easiest is to use check boxes instead of radio buttons. By design, check boxes are independent of each other; you can click one or all of them—it doesn’t matter. You can easily arrange the check boxes in a triangular pattern to simulate the position of the bowling pins.

The drawback to this approach is that the check boxes are square. If this aesthetic does not meet your expectations, then the second approach might better. This approach involves putting each radio button into its own group.

Remember that only one radio button per group can be selected at a time. When you add radio buttons to a worksheet, they default to the same group, the name of which matches the worksheet name. As you add each radio button you could right-click on it and display its properties. One of the properties is GroupName; change this to something like Ball1, Ball2, etc. As long as each radio button uses a different group name, they will be considered independent of each other.

There is an advantage to using check boxes instead of radio buttons—a huge advantage. Check boxes can be selected and then deselected; radio buttons cannot. Thus, you can click once on a check box to select it and a second time to deselect it. If you try this with radio buttons, it won’t work—once a radio button is selected, it is selected for good. This isn’t that big of a deal if you have multiple radio buttons in the same group—if you make a mistake in clicking one, just click

ExcelTips 2008 Page 441

Page 455: Excel tips 2008

Tools Tips

on another to undo it. If you configure the properties so there is one radio button per group, then you can only select that single radio button in each group; you cannot undo it.

FORMATTING COMBO BOX TEXT Applies to Excel 97, 2000, 2002, 2003, and 2007

You can use the Forms toolbar to add a combo box to your worksheet, as has been discussed in other issues of ExcelTips. (If you are using Excel 2007 then the Forms toolbar has been done away with. Instead, you access the Forms controls on the Developer tab of the ribbon.)

You can control many attributes of the combo box (right-click it and choose Format Control), but you cannot change the attributes of the font used to display information in the combo box. This seems to be an odd oversight on the part of Microsoft, but it has been that way since the earliest days of the Forms controls.

If you want greater control over how the combo box looks, then you will need to skip the Forms controls and instead add one from the Control Toolbox. You can display this toolbox by choosing Toolbars from the View menu, and then choosing Control Toolbox. If you are using Word 2007 then you can see the same controls by displaying the Developer tab of the ribbon and then clicking Insert. (In Excel 2007 the Control Toolbox controls are called ActiveX controls.)

The controls available in the Control Toolbox look very similar to the Forms controls. The Control Toolbox controls, while they have the same names as the Forms controls, are quite different. For instance, you can place a combo box, but it looks a bit different than the one you place using the Forms controls. In addition, you can select a newly placed combo box and then click Properties to see all the attributes you can change—there are quite a few more of them when you add a combo box in this manner.

So what differences are there between the two ways of adding a combo box? Besides appearance and a richer set of properties, there isn’t a whole lot of difference. There is one operational difference—you can insert a combo box from the Forms controls onto a chart sheet, but you cannot do so from the Control Toolbox.

COMPARING WORKBOOKS Applies to Excel 97, 2000, 2002, 2003, and 2007

Krishna Kumari asked if there was a way to compare the contents of two Excel workbooks. Unfortunately, there is no built-in comparison feature, as there is in Word to compare two documents. There are third-party programs available that can help you out, and a quick search of the Web can help to locate such programs.

ExcelTips 2008 Page 442

Page 456: Excel tips 2008

Tools Tips

ExcelTips 2008 Page 443

Depending on your needs, there can be an easier way. If the worksheets in each workbook are laid out the same, and you just want to find differences between values in the cells of each worksheet, then you can use formulas to compare worksheets. Try the following steps:

1. Create a new workbook called Compare.xls. 2. In cell A1 of the first worksheet in Compare.xls, enter the following formula:

=IF([WB1.xls]Sheet1!A1<>[WB2.xls]Sheet1!A1,"Different","")

3. Copy the formula from A1 into all the other cells that represent the range you want to compare. For instance, if you want to compare A1:G12 in both worksheets, then you would copy the formula from A1 into the full range of A1:G12.

These steps assume that the worksheets you want to compare are both named Sheet1, and they are in WB1.xls and WB2.xls, respectively. If you have other sheets in WB1.xls and WB2.xls to compare, you can use similar formulas in other sheets of Compare.xls.

When done, any cell that has the word “Different” in it represents a cell that is different in the ranges being compared. Thus, if C7 had “Different” in it, then there is a difference between the cell C7 of Sheet1 in WB1.xls and cell C7 of Sheet1 in WB2.xls.

If you are comparing only numeric values between the two worksheets, you could use a different formula in step 2, above:

=[WB1.xls]Sheet1!A1-[WB2.xls]Sheet1!A1

The result is a worksheet that subtracts the values in one workbook from the other, which results in the numeric differences.

Page 457: Excel tips 2008

Macro Tips

UNDERSTANDING VARIABLES IN VBA MACROS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to write macros in a language called Visual Basic for Applications (VBA). This is a specialized version of the BASIC programming language, and as such, allows you to use variables. Variables are nothing but names which represent other data. During the course of your macro you can even change the data to which the name applies.

VBA allows you to use quite a few different types of variables. There are eleven types of variables you can use in your macros. These are known as data types, and you should use the data type that most closely matches the characteristics of the information you are storing in the variable. VBA supports the following data types:

• Byte. A numeric variable within the range of 0 to 255. • Boolean. A variable with two possible values: True (-1) or False (0). • Integer. A numeric variable designed for whole numbers in the range of -32,768 to

32,767. • Long. A numeric variable designed for very large whole numbers. • Currency. A numeric variable designed for calculations involving monetary values. • Single. A numeric variable designed for single-precision floating-point values; accurate

to about six or seven decimal places. • Double. A numeric variable designed for double-precision floating-point values;

accurate to about 15 decimal places. • Date. A numeric variable designed to represent a date and time as a real number. The

value to the left of the decimal point is the date, and that portion to the right of the decimal point is the time.

• String. A variable that can contain any type of text or character you desire. You can assign a maximum of approximately 63,000 characters to a string variable.

• Object. A variable that contains a pointer to a defined object within VBA. • Variant. A variable that can contain any type of data.

ExcelTips 2008 Page 444

Page 458: Excel tips 2008

Macro Tips

An additional data type (Decimal) is also specified in the VBA documentation, but is not currently supported by the language. As in other versions of BASIC, VBA also allows you to define variable arrays and you can also create user-defined data types. The full range of variable specifications is much too complex for a simple ExcelTip, however. If you need specific information about how to work with variables, refer to a good Visual Basic or VBA programming book. You can also look in the VBA on-line help under the Dim statement.

UNDERSTANDING SUBROUTINES Applies to Excel 97, 2000, 2002, 2003, and 2007

When you write macros in Excel, you use a programming language called Visual Basic for Applications (VBA). This is based on the BASIC programming language, with extensions specific to Excel. One of the features of the language is the capability to use subroutines in your programs. For instance, consider the following VBA macro:

Sub Macro1() TestSub End Sub

Sub TestSub() MsgBox "In the subroutine" End Sub

This simple macro (Macro1) does nothing but call a subroutine (TestSub), which in turn displays a message box to inform you that it is in the subroutine. When you click on OK to dismiss the message box, the subroutine ends and returns control to the main program. You can have as many subroutines in a VBA program as you desire. The purpose of each should be to perform common tasks so you don’t have to rewrite the same code all the time.

You can also pass parameters to your subroutines. These parameters can then be acted upon by your subroutine. For instance, consider the following macro:

Sub Macro1() A = 1 PrintIt A End Sub

Sub PrintIt(x) MsgBox "Value: " & x End Sub

This is a simple macro that sets a variable, and then passes it in a subroutine call to PrintIt. This subroutine displays the value of the variable in a message box, and then (after you press OK) returns to the calling program.

ExcelTips 2008 Page 445

Page 459: Excel tips 2008

Macro Tips

Notice that the subroutine does not use the same variable name as it was passed. This is because VBA reassigns the value of x (what the subroutine expects to receive) so that it matches the value of A (what the program is passing to the subroutine). The important thing to remember in passing parameters to subroutines is that your program must pass the same number of parameters as the subroutine expects, and that the parameters must be of matching types and in the proper order.

UNDERSTANDING FUNCTIONS Applies to Excel 97, 2000, 2002, 2003, and 2007

You already know that you can use subroutines in your macros. VBA also allows you to define functions that can be used in your macros. The difference between functions and subroutines is that functions can return values, whereas subroutines cannot. Consider the following macro:

Sub Macro1() TooMany = TestFunc If TooMany Then MsgBox "Too many columns selected" End Sub

Function TestFunc() TestFunc = False If Selection.Columns.Count > 10 Then TestFunc = True End If End Function

The macro (Macro1) calls the TestFunc function. This function returns either the value False or True, depending on a test it performs. Macro1 then acts upon the value returned. Notice that the function name can appear on the right side of an equal sign. This makes functions very powerful and an important part of any program. Within the function the result is assigned to TestFunc, which is the name of the function itself; this is the value returned by the function.

As with subroutines, you can also pass parameters to your functions. This is illustrated in the following macro:

Sub Macro1() A = 12.3456 MsgBox A & vbCrLf & RoundIt(A) End Sub

Function RoundIt(X) As Integer RoundIt = Int(X + 0.5) End Function

ExcelTips 2008 Page 446

Page 460: Excel tips 2008

Macro Tips

This simple macro (Macro1) defines a number, and then uses a message box to display it and the result of passing the number to the RoundIt function. The output is 12.3456 and 12. Notice that the parameter should be passed to the function within parentheses. Also notice that the function does not use the same variable name as it was passed. This is because VBA reassigns the value of X (what the function needs) so it matches the value of A (what the program is passing to the function). The important thing to remember in passing parameters to functions is that your program must pass the same number of parameters as the function expects, and the parameters must be of matching types and in the proper order.

EXITING A FOR ... NEXT LOOP EARLY

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you use For ... Next loops in your macro programming (who doesn’t?), then you should know that they can take a great deal of time. You can minimize this by only checking what you need. For instance, consider the following code, which checks an array to see if a value exists. If it doesn’t, then it adds the value to the end of the array. If it does, then the value is not added.

AddIt = False For J = 1 to NumEntries If NumValues(J) = ToAdd Then AddIt = True Next J If AddIt Then NumEntries = NumEntries + 1 NumValues(NumEntries) = ToAdd End If

This works great, but if the array gets large, you can end up going through the For ... Next loop quite a few times. Now consider the following code, which accomplishes the same task, but dumps out of the For ... Next loop early if a match is detected.

AddIt = False For J = 1 to NumEntries If NumValues(J) = ToAdd Then AddIt = True Exit For End If Next J If AddIt Then NumEntries = NumEntries + 1 NumValues(NumEntries) = ToAdd End If

ExcelTips 2008 Page 447

Page 461: Excel tips 2008

Macro Tips

Now if a match is found early on in the loop, all the rest of the iterations are skipped because the Exit For statement is encountered and the loop is basically exited right away. The result is a faster running macro.

UNDERSTANDING THE SELECT CASE STRUCTURE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Macros in Excel are written in a language called Visual Basic for Applications (VBA). Like any other programming language, VBA include certain programming structures which are used to control how the program executes. One of these structures is the Select Case structure. This structure has the following syntax:

Select Case expression Case expression program statements Case expression program statements Case Else program statements End Select

When a macro is executing, and this structure is encountered, Excel uses the expression to test each subsequent Case statement to see if the code under the Case statement should be executed. For instance, consider the following code:

Select Case DayOfWeek Case 1 DayName = "Monday" Case 2 DayName = "Tuesday" Case 3 DayName = "Wednesday" Case 4 DayName = "Thursday" Case 5 DayName = "Friday" Case 6 DayName = "Saturday" Case 7 DayName = "Sunday" Case Else DayName = "Unknown day" End Select

ExcelTips 2008 Page 448

Page 462: Excel tips 2008

Macro Tips

This code assumes you enter it with DayOfWeek already set to a numeric value. Let's say (for example’s sake) the value is 4. In this structure, the only code that would be executed is the code under the Case 4 statement—in other words, the macro would set DayName to “Thursday.” If DayOfWeek were set to some other value not accounted for by the Case statements (outside of the 1 to 7 range), then the code under Case Else would execute, and the macro would set DayName to "Unknown day."

DOCUMENTING CHANGES IN VBA CODE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Phil is a member of his bank’s MIS department. The department creates a lot of management reports using Excel. In doing so they write a lot of macros to automate the reports as much as possible. Because of the Sarbanes-Oxley act the bank is required to track changes to the VBA code. Phil wonders if there is any products or methods to track the changes in the VBA code that would highlight what was changed and then preserve those changes for documentation purposes.

The easiest way to do this would be to periodically export the macro code to a text file, and then archive the text files. This could be done every day, week, month, etc., or it could be done anytime there is a change in the code. Simply give each text file a different descriptive name so you can tell which version the file contains.

Once in text-file format, the files can be easily compared against one another to highlight differences; there are any number of commercial products that could be used for comparing the text files. (You could even use Microsoft Word to compare different versions of files.)

(Thanks to Steve Aprahamian, Peter Grebenik, Russell Hendel, Margaret Hassall, and Lisa Dickison for contributing to this tip.)

STEPPING THROUGH A MACRO WITH A WORKSHEET VISIBLE

Applies to Excel 97, 2000, 2002, 2003, and 2007

Ted asked if there was a way to step through VBA code while viewing a worksheet, so he could view the effects on the worksheet as each step in his macro is executed.

This is actually quite easy to do—all that needs to be done is to arrange the Excel window and the VB Editor window so that both of them are visible at the same time. In other words, neither one of them should be “full screen.” You can arrange the window sizes so that you maximize

ExcelTips 2008 Page 449

Page 463: Excel tips 2008

Macro Tips

what you can see in your worksheet, and minimize what you see in the VB Editor—perhaps showing only a few lines of code in the window.

Another closely related approach is to make the Excel workbook full-screen, and then make the VB Editor window as small as possible, overlaying the Excel screen. With the VB Editor window active, you can step through the macro using F8 and view the results in the background, on the Excel workbook.

SELECTING A RANGE OF CELLS RELATIVE TO THE CURRENT CELL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Sometimes in a macro it is helpful to select cells relative to whichever cell is currently selected. For instance, let’s say you want to select the first three cells of the current row. You can do that by using the following VBA code:

Range(Cells(Selection.Row, 1), Cells(Selection.Row, 3)).Select

The Cells property returns an object that represents a specific row and column (individual cell) of a worksheet. In this usage, Cells is used twice to determine a specific range of cells. The first instance returns the first cell of the current row, while the second returns the third cell of the current row. Thus, the range becomes the first through third cells of the current row.

Instead of using the Cells property to specify a location, you can use the Offset property to accomplish much of the same task. Consider the following code:

Range(ActiveCell.Offset(-3, 5), ActiveCell.Offset(0, 10)).Select

This uses the Offset property of the ActiveCell object to specify a range relative to the currently selected cell. The Offset property takes an argument that represents the row and column of the offset. A negative value represents up (for the row) and left (for the column). A positive value is down (for the row) and right (for the column). You can also use a value of 0, which represents the current row or column.

ExcelTips 2008 Page 450

Page 464: Excel tips 2008

Macro Tips

SELECTING A CELL IN THE CURRENT ROW

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are developing Excel macros, you may wonder how you can select a cell relative to the one in which you are located. For instance, if you are using Excel and you press the HOME key, the cell at the left side of the current row is selected. Unfortunately, using the macro recorder to record this does not help in this situation, since it records destination of the action, instead of the your actual action. For instance, if you press HOME and you are on the fourth row in a worksheet, Excel doesn’t record the Home action, but instead records the destination, as follows:

Range("A4").Select

This is great if you always want to go to cell A4, but terrible if you want to go to the first cell of whatever row you are on.

As with many tasks in VBA, there are several ways you can approach a solution to this dilemma. The first method is actually a variation on what the macro recorder returns, as shown above. All you need to do is change the row designator so it represents the current row, as in the following:

Range("A" & (ActiveCell.Row)).Select

VBA figures out what the current row is, slaps it together with the “A” designator, and comes up with a cell reference that works with the Range method.

Another technique you can use is to put the Cells property to work, as follows:

Cells(Application.ActiveCell.Row, 1).Select

This approach, of course, can be modified so that you actually select any given cell in the current row. All you need to do is change the column designation (1, in the above example) to a number representing the column desired.

Another approach (which produces the same result) is to use the Range object in conjunction with the Cells property, as shown here:

Range(Cells(Selection.Row, 1).Address).Select

Selection.Row gives the row number of the current selection. The Address property of the Cells method returns the address of a particular cell in A$1$ format. This address is then used as the parameter for the Range object, and the actual cell is selected by the Select method.

ExcelTips 2008 Page 451

Page 465: Excel tips 2008

Macro Tips

JUMPING TO THE START OF THE NEXT DATA ENTRY ROW

Applies to Excel 97, 2000, 2002, 2003, and 2007

Do you need to always jump to the first cell right after all the data you’ve already put in your worksheet? For instance, if you have a worksheet that contains data in A1:G251, do you ever need to jump to cell A252 so that you can start entering data?

Moving to the first cell in row 252 is easy, provided there is data in all the cells in A1:A251. But if there can be empty cells in column A, then jumping to A252 can be a bit more difficult. In that case, you might be interested in a macro that makes jumping to the first cell of the empty row after your data quite easy:

Sub FindFirstCellNextRow() Dim x As Integer x = ActiveSheet.UsedRange.Rows.Count ActiveCell.SpecialCells(xlLastCell).Select ActiveCell.EntireRow.Cells(1, 1).Offset(1, 0).Activate End Sub

The first two lines effectively recompute the “last cell” in the worksheet and then the next two lines select that cell and jump to the cell in column A that is one row down.

Assign the macro to a keyboard shortcut, and you’ll always be just one keystroke away from jumping to the first truly empty row in the worksheet.

COMPARING STRINGS Applies to Excel 97, 2000, 2002, 2003, and 2007

It is not uncommon to compare strings in a macro. For instance, you may need to compare what a user typed with some pre-determined value. If you do this directly, you must take into consideration that the user may not have typed his (or her) string in the same way as you expected. Particularly vexing is the fact that the user may have mixed upper and lower case in their response.

The quickest and easiest way around this is to use either the UCase() or LCase() function on their input before you do the comparison. For instance, let's assume you prompt the user for the word "yes" to verify they want an action done. The following code will check the input, regardless of how the user typed it.

If LCase(sUserIn) = "yes" then bDoIt = True

ExcelTips 2008 Page 452

Page 466: Excel tips 2008

Macro Tips

The trick is make sure your test string is either all upper or all lower case, and then convert the user’s input to that same case.

DETERMINING IF A NUMBER IS ODD OR EVEN

Applies to Excel 97, 2000, 2002, 2003, and 2007

A common programming task is validating user input. Often, you may need to determine if a number entered by a user is odd or even. For instance, suppose you wrote your own macro that asked the user what page number of the document they wanted to process. If your macro had to process odd and even pages differently, then you need to figure out if the number the user provided was odd or even. The technique for this is relatively simple, as shown here:

Even = (UserNum Mod 2) - 1

After execution of this line, Even will be True (-1) if UserNum was even, or False (0) if UserNum was odd.

CREATING WORKSHEETS WITH A MACRO

Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel lets you create new worksheets in a number of different ways. What if you want to create a new worksheet and name it all in one step? The easiest way to do this is with a macro. The following is an example of a macro that will ask for a name, and then create a worksheet and give that worksheet the name provided.

Sub AddNameNewSheet1() Dim Newname As String Newname = InputBox("Name for new worksheet?") If Newname <> "" Then Sheets.Add Type:=xlWorksheet ActiveSheet.Name = Newname End If End Sub

This macro works fine, as long as the user enters a worksheet name that is “legal” by Excel standards. If the new name is not acceptable to Excel, the worksheet is still added, but it is not renamed as expected.

ExcelTips 2008 Page 453

Page 467: Excel tips 2008

Macro Tips

A more robust macro would anticipate possible errors in naming a worksheet. The following example code will add the worksheet, but keep asking for a worksheet name if an incorrect one is supplied.

Sub AddNameNewSheet2() Dim CurrentSheetName As String 'Remember where we started 'Not needed if you don't want to return 'to where you started but want to stay 'on the New Sheet CurrentSheetName = ActiveSheet.Name 'Add New Sheet Sheets.Add 'Make sure the name is valid On Error Resume Next 'Get the new name ActiveSheet.Name = InputBox("Name for new worksheet?") 'Keep asking for name if name is invalid Do Until Err.Number = 0 Err.Clear ActiveSheet.Name = InputBox("Try Again!" _ & vbCrLf & "Invalid Name or Name Already Exists" _ & vbCrLf & "Please name the New Sheet") Loop On Error GoTo 0 'Go back to where you started 'Not needed if you don't want to return 'to where you started but want to stay 'on the New Sheet Sheets(CurrentSheetName).Select End Sub

REMOVING ALL MACROS Applies to Excel 97, 2000, 2002, 2003, and 2007

Gerald asked if there was a way to get rid of all the macros in an Excel workbook, without the need to individually delete them. There are two ways you can accomplish this task. The first approach is used if you don’t want to mess with the macros at all. Just follow these steps:

ExcelTips 2008 Page 454

Page 468: Excel tips 2008

Macro Tips

1. Unhide any worksheets that may be hidden. 2. Select all the worksheets in the workbook. (Click on the first worksheet tab, then hold

down SHIFT as you click on the last worksheet tab.) 3. Right click on one of the worksheet tabs. Excel displays a Context menu. 4. Choose Move or Copy from the Context menu. Excel displays the Move or Copy dialog

box.

The Move or Copy dialog box.

4. Using the To Book drop-down list, choose (new book). 5. Make sure the Create Copy check box is not selected. 6. Click on OK. 7. Rehide any worksheets you unhid in step 1.

Your worksheets have now been moved to a new workbook—one that does not have any macros attached to it.

The second approach is to simply work with the existing workbook, and is a viable choice if you feel comfortable with macros in the first place. Follow these steps:

1. Press ALT+F11 to display the VBA Editor. 2. In the Project Explorer (upper-left corner of the Editor), right-click on a module that

you want to delete. (Remember that macros are stored in modules, and that you should only right-click on a module that is associated with the workbook that you want to cleanse.) Excel displays a Context menu.

3. Choose the Remove option from the Context menu. The actual wording of the option will include the name of the module you want to remove, such as Remove Module1.

4. When asked if you want to export the module before removing it, click on No.

ExcelTips 2008 Page 455

Page 469: Excel tips 2008

Macro Tips

5. Repeat steps 2 through 4 for any other modules you want to remove. 6. Close the VBA Editor.

WORKING WHILE A MACRO IS RUNNING

Applies to Excel 97, 2000, 2002, 2003, and 2007

Macros are great for doing the mundane (or not so mundane) processing that is often necessary with Excel data. After you start to use them, you may find that running macros can consume quite a bit of time. While you are running them, there is very little else that you can do, since Excel won’t allow you to do any other work while the macro is chunking away.

The best way to do additional work is to open another instance of Excel. As you are working on one workbook in the foreground, the other instance of Excel continues to work away at the macro in the background. This approach works because Windows allows multiple instances of a program, each in its own workspace. The only thing you cannot do is work in the foreground on the same workbook which the macro is using.

In order to open a second instance of Excel, simply follow the steps you followed to open the first instance. For example, if you started Excel by calling up the Start menu and then the Programs submenu, you could do the same thing to open the second instance.

You should realize that the macro running in the background instance of Excel will be affected by you working on a different instance of Excel in the foreground. This, again, is related to how Windows treats different programs. On most systems, the background programs are given a smaller percentage of the CPU’s attention than the foreground program.

FORCING A MACRO TO RUN WHEN A WORKSHEET IS RECALCULATED

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you write a macro, it is designed to be run whenever you choose to run it. What if you need to develop a macro that will run whenever something changes in your worksheet? What if you want the macro to run automatically? This is particularly necessary if you are creating a custom function that you want to use within the cells of the worksheet.

ExcelTips 2008 Page 456

Page 470: Excel tips 2008

Macro Tips

This is where the Volatile method comes in handy. All you need to do is include the following statement within your macro:

Application.Volatile

This informs Excel that the results of the macro are dependent on the values in the worksheet, and that it should be executed whenever the worksheet is recalculated. For instance, consider the following user-defined function:

Function CountCells(MyRange As Range) Dim iCount As Integer iCount = 0 For Each cell In MyRange If cell.HasFormula Then iCount = iCount + 1 End If Next cell CountCells = iCount End Function

This function, if used in a cell, counts the number of cells that contain formulas within a specified range. However, the function will only run the first time it is entered into a cell, or whenever the cell containing the formula is edited. If you want the function to recalculate every time the worksheet is recalculated, you would add the Volatile method near the beginning of the function:

Function CountCells(MyRange As Range) Dim iCount As Integer Application.Volatile iCount = 0 For Each cell In MyRange If cell.HasFormula Then iCount = iCount + 1 End If Next cell CountCells = iCount End Function

The inclusion of the Application.Volatile method means that every time the worksheet is recalculated, this function (macro) is again run.

ExcelTips 2008 Page 457

Page 471: Excel tips 2008

Macro Tips

AUTOMATING COPYING MACROS Applies to Excel 97, 2000, 2002, 2003, and 2007

Sreekanth asked if there is a way to automate the copying of macros from one workbook to another. It seems that Sreekanth has to create a new "distribution" workbook each month that contains a PivotTable that analyzes data, and the workbook needs to contain certain macros.

Perhaps the easiest way to do this is to create a new Excel template that contains only the macros you want to distribute. Then, you can use that template as a basis for your distribution workbook. Simply copy your PivotTable to the workbook, and it will be ready to distribute, as needed.

If you would rather not use a template, then you can create a macro that will copy macro procedures from one workbook to another. Such a macro can get rather involved, and would take some testing. A good place to start in developing such a macro is a great online resource located at this Web page:

http://www.cpearson.com/excel/vbe.aspx

MACRO FAILS AFTER AUTOFILTER

Applies to Excel 97, 2000, 2002, 2003, and 2007

In testing new macros that you develop, you may find that the macro fails when it is run and the information in a worksheet is filtered using the AutoFilter. This can happen because the macro may expect that all the information in the worksheet is available, or it may try to update information that is not visible on the screen.

The best solution to this problem is to make sure that the macro turns off the AutoFilter feature. This can be easily done by adding the following line of code near the beginning of the macro:

ActiveSheet.AutoFilterMode = False

This ensures that AutoFilter is off, and removes the problems that AutoFiltered data may present for your macro.

(Thanks to Dustin Keith for this tip.)

ExcelTips 2008 Page 458

Page 472: Excel tips 2008

Macro Tips

DISABLED MACROS Applies to Excel 97, 2000, 2002, 2003, and 2007

If you recently upgraded to new version of Excel, you may have run into a situation where the macros you created in the earlier version no longer run because they are disabled. This can be disturbing, particularly if you absolutely need the macros to get your work done.

The reason this happens is that the more recent versions of Excel (beginning with Excel 2000) include a macro security feature which wasn't present in earlier versions. The default security setting, when first installing Excel, is “High.” This setting automatically disables any macros in any workbook that are not digitally signed by a “trusted source” (for more info, search for Macro Security in Excel’s online help).

This automatically presents a couple of possible solutions. The first possible solution is to get your macros “digitally signed.” Such a process is beyond the scope of this tip, but you can find help on the process in the online help files or at the Microsoft Web site.

Finally, you can lower the default setting for the macro security used by Excel. For instance, you can set it to “Medium,” which results in only a warning message about the macros rather than an outright disabling. To change the security setting, follow these steps if you are using a version of Excel prior to Excel 2007:

1. Choose Macro from the Tools menu, and then choose Security from the submenu. Excel displays the Security dialog box.

ExcelTips 2008 Page 459

Page 473: Excel tips 2008

Macro Tips

The Security dialog box.

2. Choose an available security setting. 3. Click on OK.

If you are using Excel 2007 then you should follow these steps to change the macro security level:

1. Click the Office button and then choose Excel Options. Excel displays the Excel Options dialog box.

2. At the left side of the dialog box click Trust Center. 3. Click Trust Center Settings. Excel displays the Trust Center dialog box. 4. At the left side of the dialog box click Macro Settings.

ExcelTips 2008 Page 460

Page 474: Excel tips 2008

Macro Tips

The Macro Settings in the Trust Center dialog box.

5. Choose an available security setting. 6. Click on OK.

SELF-AWARE MACROS Applies to Excel 97, 2000, 2002, 2003, and 2007

For some macros you may need to determine if there is a way to determine the particular machine on which the macro is operating. For instance, you may have a desktop PC that has a particular directory at D:\OraNT\Plus33, while your notebook PC has the directory at C:\OraNT\Plus33. The macro, of course, needs to detect which machine is in use so that it knows which directory to use for its processing.

There are different ways that this task can be approached. It is possible to create an Excel macro that actually accesses the Windows API and determines the name of the computer on which it is running. Such an approach can get quite involved, however.

An easier way is to just use VBA’s DIR command to determine where the desired directory exists. The following will do the trick:

Sub OracleQueries() Dim sTemp As String Dim sGoodPath As String sGoodPath = "D:\OraNT\Plus33\" sTemp = Dir("D:\OraNT\Plus33\nul") If sTemp = "" Then sGoodPath = "C:\OraNT\Plus33\"

ExcelTips 2008 Page 461

Page 475: Excel tips 2008

Macro Tips

sTemp = Dir("C:\OraNT\Plus33\nul") End If 'Now have directory information If sTemp <> "" Then 'Process queries using sGoodPath Else MsgBox "Directories not found!" End If End Sub

Notice how the DIR function is used in this example. Normally DIR returns the name of the first file it finds in the requested directory. If the directory is empty, however, DIR returns an empty string—even if the directory actually exists. Since all we want to do is find out if the directory exists (not if there are files in it), it is necessary to append the letters “nul” at the end of the directory path used by DIR. This causes DIR to return the an empty string if the directory is not located, or else the characters “nul” if it is (even if the directory is empty).

Toward the end of the macro, sTemp will be empty if neither directory could be located. If one of them was located, then sTemp will not be empty, and sGoodPath will be set to the directory name that can be used in further processing.

COUNTING COLORS OF CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

Besides using values and text in your worksheets, Excel allows you to use colors to either enliven or provide meaning to your data. If you use colors in your worksheets, you may wonder if there is a way to count the number of cells that are formatted with a particular fill color. There is no intrinsic function in Excel to perform such a task, but you can certainly make one with a user-defined function. The following is an example of one that will count the number of cells in a range that are formatted with a yellow fill color:

Function CountYellow(MyRange As Range) Dim iCount As Integer Application.Volatile iCount = 0 For Each cell In MyRange If cell.Interior.ColorIndex = 6 Then iCount = iCount + 1 End If Next cell CountYellow = iCount End Function

ExcelTips 2008 Page 462

Page 476: Excel tips 2008

Macro Tips

To use the function, all you need to do is use a formula such as the following in a cell of your worksheet:

=CountYellow(A1:A99)

This example returns the number of cells in the range of A1:A99 that use the yellow fill color.

Notice in the CountYellow function that the cells are examined to see if the ColorIndex property is equal to 6. In other VBA coding you may be used to seeing near-English constants that define colors. In this case, the normal color constants don’t work. Instead, the ColorIndex property works based on a set of index values into a particular palette of colors. If you are interested in seeing the various index values used for the different colors, take a look at the VBA online help file for the ColorIndex property.

Once you know how to walk through the cells in a range in this manner, it is easy to perform other types of operations based on the color used to fill cells in the range. For instance, instead of simply counting the number of cells, you could add up the values of the cells in the range, or you could find the average of the values in the range. All you need to do is to make the appropriate changes in the code in the innermost If … End If structure.

COUNTING SHADED CELLS Applies to Excel 97, 2000, 2002, 2003, and 2007

Excel allows you to apply all sorts of formatting to the cells in your workbook. One of the things you can do is to “shade” cells using a pattern or color. (You do this on the Patterns tab of the Format Cells dialog box.) At some point you may want to know how many cells in a range are shaded.

There is no worksheet formula in Excel that will allow you to count shaded cells. Instead, you must develop your own macro to do this. The following macro is an example of a way to approach this problem. It counts the number of shaded cells in the range of A1 through J20, and places the count in cell A1.

Sub CountColor() Dim irow, icol As Integer Cells(1, 1) = 0 For irow = 1 To 20 For icol = 1 To 10 If Cells(irow, icol).Interior.ColorIndex _ <> xlColorIndexNone Then Cells(1, 1) = Cells(1, 1) + 1 End If Next icol Next irow

ExcelTips 2008 Page 463

Page 477: Excel tips 2008

Macro Tips

End Sub

Notice that the heart of the routine is the comparison that is done between the ColorIndex of each cell and the pre-defined xlColorIndexNone constant. If they are not equal, then the cell has been shaded in some way.

This same basic technique can be easily adapted to a custom function. Notice in the following that the same comparison is done on a cell-by-cell basis:

Function FindShades(a As Range) As Integer FindShades = 0 For Each c In a If c.Interior.ColorIndex <> xlColorIndexNone Then FindShades = FindShades + 1 End If Next c End Function

In order to use this function, simply use it in a cell, as a formula, and specify a range in the formula:

= FindShades(B7:E52)

OUT OF MEMORY ERRORS WHEN ACCESSING THE VBA EDITOR

Applies to Excel 97, 2000, 2002, 2003, and 2007

Chris wrote about a problem he is having with VBA. It seems that he’s getting the error message "out of memory" when attempting to access the VBA editor. He’s tried closing all other applications, checked for background programs, and he has ample disk space. The error message even occurs in workbooks with relatively small procedures.

It could, realistically, be any number of conditions causing the problem. Because of this, it can be hard to track down the cause. There are a couple of clues that suggest that the problem may be due to either an add-in or to a problem with your macro modules.

You can figure out if it is an add-in by simply starting Excel with all the add-ins disabled. Add them back in, one at a time, until you notice the error again cropping up. You will then have a pretty good idea that the problem is caused by the last add-in you enabled.

If the problem is not due to your add-ins, then you should suspect your macro modules. If you spend a lot of time editing your modules, they can become corrupted over time. (This has been a known problem for some time in VBA.) You can usually get around this problem by recreating

ExcelTips 2008 Page 464

Page 478: Excel tips 2008

Macro Tips

the workbook in which the problem occurs. Copy the worksheets from the old to the new workbook, and then use the VBA export and import capabilities to move the macro modules from the old workbook to the new one.

A good discussion on memory problems with Excel can be found at these pages:

http://www.decisionmodels.com/memlimitsc.htm http://www.decisionmodels.com/memlimitsd.htm

(Thanks to Steve Aprahamian for contributing to this tip.)

DETERMINING HOW MANY WINDOWS ARE OPEN

Applies to Excel 97, 2000, 2002, 2003, and 2007

It is sometimes helpful for your macro to know how many Excel workbook windows are open at any given time. For instance, you might want your macro to only run if there is a single window open, or you might even require there to be two windows open. Either way, you need to check how many there are.

You determine the number of open windows by using the Count property of the Windows object. This is done using the following syntax:

X = Windows.Count

After executing the line, X is equal to the number of open windows.

SAVING CHANGES WHEN CLOSING

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you modify an Excel workbook, and then close the file, you are asked if you want to save your changes. This is a good feature that helps ensure you don’t mistakenly throw away some of your work.

When running a macro, however, you may not want to be bothered with a dialog box asking if you want to save your changes. If the macro modifies a workbook in some way, and you use the Close method, you are asked if you want to save your changes, just as you are if you manually close a workbook without first saving.

ExcelTips 2008 Page 465

Page 479: Excel tips 2008

Macro Tips

The way to get around this is to use one of the parameters available with the Close method. Consider the following:

ActiveDocument.Close SaveChanges:=False ActiveWorkbook.Close SaveChanges:=True

Both lines of code close the active worbook. The difference between the lines is in the setting of the SaveChanges parameter. In the case of the first line, any changes will be discarded, while the second line results in the workbook being saved when it is closed.

UPGRADING A PERSONAL.XLS WORKBOOK

Applies to Excel 97, 2000, 2002, 2003, and 2007

Barbara updated to Office 2007, but her company has dictated that files created in Excel 2007 be saved in Excel 2003 format since many of their clients have not yet upgraded. Barbara is wondering if she should continue to use Personal.xls as the personal macro workbook or copy all macros to Personal.xlsb.

Honestly, you can’t make that choice in Excel 2007. If you are using the program, all of your macros that previously were stored in Personal.xls should be transferred to your new Personal.xlsb file. Why? Because the Personal.xlsb file is for use on your machine, so there is no issue of backward compatibility for your clients. Workbooks that you save in the older Excel 2003 format will continue to save just fine and be readable by your clients using the older version of Excel.

If, however, you have clients with whom you need to share the macros in your Personal.xlsb file, and they aren’t using Excel 2007, then you will need to unhide the workbook and save it in the older format explicitly. It is this older format that you will save with them, and such saving will still not affect the Personal.xlsb file on your system.

(Thanks to Steve Aprahamian and Piers Morgan-Harvey for contributing to this tip.)

ExcelTips 2008 Page 466

Page 480: Excel tips 2008

Macro Tips

SEARCHING FOR LEADING APOSTROPHES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Richard would like to be able to search for an apostrophe (') in the leftmost position in a cell, but Excel won't let him do it. In other words, if a cell contains '123 or 'a34tp, Richard would like to be able to find that leading apostrophe and, optionally, replace it with something else.

Doing what Richard wants to do takes a bit of preliminary explaining. Technically, it is a misnomer to refer to the apostrophe as a “leading character” or mentioning that it is in the “leftmost position” of a cell. Even though you may be able to look at the Formula bar and see the apostrophe at the beginning of the formula, that apostrophe is not really a part of the cell’s contents; that is why you can’t use Find and Replace to find and replace it.

The apostrophe is actually considered a “prefix character” for a cell. The possible values of the prefix character are set by the Transition Navigation Keys setting in Excel, and the value of the setting is saved on a workbook-by-workbook basis. You can change this setting by using the Transition tab of the Options dialog box or (in Excel 2007) the advanced area of the Excel Options dialog box (at the bottom of the dialog box).

If the setting is cleared (the default condition for the setting), then the value of the prefix character for each cell can either be blank or an apostrophe. If the cell contains text, then the setting of the prefix character doesn’t really matter much. If the cell contents are not text, then setting the prefix character to an apostrophe forces Excel to treat the cell contents as if they are text. So, for instance, the number 123 is treated as text—not a number—and shows up in the Formula bar as '123.

If the Transition Navigation Keys setting is selected (the check box has a check mark in it), then the value of the prefix character for each cell can have one of five different values. These values are consistent with the prefixes used in Lotus 1-2-3 and are, oddly enough, supported in Excel only as a transitional aid to the regular usage in the program. The possible values are an apostrophe (left-justified), quote mark (right-justified), carat (centered), back slash (repeated), or blank (non-text item).

Now, back to Richard’s original question: how to search and get rid of that leading apostrophe. You can’t use Find and Replace to do the editing because the apostrophe isn’t really part of the cell contents. So, you must do the changing in a macro. The changing is relatively easy. First, you’ll want to make sure that the workbook has the Transition Navigation Keys setting cleared. Why? Because you probably don’t want to mess up the prefix character for the cells if the workbook could be used at some future point with Lotus 1-2-3 again. You make sure that the setting is correct, in your macro, with the following line:

Application.TransitionNavigKeys = False

ExcelTips 2008 Page 467

Page 481: Excel tips 2008

Macro Tips

You can then step through a selection of cells and check to see if the prefix character for each cell is an apostrophe. If it is, then all you need to do is have the macro do the equivalent of manually retyping the contents of the cell, in the following manner:

For Each c In Selection If c.PrefixCharacter = "'" Then c.Value = c.Value End If Next c

Note that the macro checks what is in the PrefixCharacter property. This property can be read in VBA, but it cannot be changed directly. That is why the macro needs to use the seemingly simple line to assign the value of each cell back into the cell—essentially retyping the contents.

If you would rather not use a macro to get rid of the apostrophe prefix characters, then you can take advantage of a strange little quirk of Paste Special. Follow these general steps:

1. Select a blank cell and copy it to the Clipboard (use CTRL+C). 2. Select the range of cells from which you want to remove the prefix character. 3. Display the Paste Special dialog box. 4. Click the Add radio button. 5. Click OK.

After the “adding” of the blank cell to each of the target cells, the prefix character—if any—is removed.

(Thanks to Mike Hughes, Steve Aprahamian, Marc Prosl, Richard Raciborski, and Roger Mason for contributing to this tip.)

WAITING FOR UPDATE COMPLETION

Applies to Excel 97, 2000, 2002, 2003, and 2007

It is not unusual to create a macro that loads data from an external source (such as a database query) and then processes that data. If you create such a macro, you may notice a slight problem—Excel doesn’t wait for the data refresh to complete before it begins merrily chunking away on the code that follows.

The reason for this is simple—when you refresh information in a workbook from an external source (such as the Oracle query), Excel won’t wait around. This is contrasted with internal events in Excel, which can be easily waited upon. To overcome this difference, you need to change the way you write the macros. Essentially, you need to write two separate macros. The

ExcelTips 2008 Page 468

Page 482: Excel tips 2008

Macro Tips

first macro basically initiates the refresh from the external source, and the second macro is executed once the refresh is completed.

How do you know when you can run the second macro? You could do it manually after visually inspecting the worksheet to make sure everything loaded, but that ties you up. Instead, you can tie a macro to the AfterRefresh event. This event is triggered when (as its name suggests) the refresh is complete. For more information on how to use this event in your programming, visit the Microsoft Knowledge Base articles at these addresses:

http://support.microsoft.com/?kbid=182735 http://support.microsoft.com/?kbid=213187

These Knowledge Base articles are for Excel 97 and Excel 2000, but the information they contain will also work with later versions of Excel.

GENERATING UNIQUE NUMBERS FOR WORKSHEETS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Sometimes you may need Excel to generate a unique number for your worksheets. For instance, you could be using Excel to create forms such as invoices, statements, or tracking sheets, and you need an unique numbers for each form (I’ll call this a ticket number). This, of course, implies that Excel needs to remember the number from one session to the next.

There are a couple of ways you can approach this problem. If the numbers don’t need to be sequential, you could create a ticket number based on the current time of day, in seconds. The following macro can be added to the ThisWorksheet object:

Private Sub Workbook_NewSheet(ByVal Sh As Object) Dim lTicket As Long lTicket = CLng(Time * 24 * 60 * 60) Sh.Range("A1") = lTicket End Sub

The macro is triggered every time a new worksheet is added to the workbook. It takes the current time, converts it to an integer number of seconds, and then places that value into cell A1. The likelihood of duplicating ticket numbers within any given day is remote, but it could happen over time. (For instance, if you create a ticket at the exact same time today that you did yesterday or last week.)

To get around this problem, you could create a ticket number in the following manner:

Private Sub Workbook_NewSheet(ByVal Sh As Object)

ExcelTips 2008 Page 469

Page 483: Excel tips 2008

Macro Tips

Dim sTemp As String sTemp = Format(Date, "yymmdd") & Format(Time, "hhmmss") Sh.Range("A1") = sTemp End Sub

This version of the event handler constructs a ticket number based both the date and time. Unless you are creating trouble tickets very quickly, this approach should reduce the possibility of duplicate numbers generated by the macro.

If the numbers must be sequential within the current workbook, then you can define a name that contains the current high value of your ticket number, and then a macro that places that number in a cell on a new worksheet and increments the value of the stored number. Follow these steps to start:

1. Choose Name from the Insert menu, then choose Define. Excel displays the Define Name dialog box. (To display the equivalent dialog box in Excel 2007, display the Formulas tab of the ribbon and then click on Define Name in the Defined Names group. Excel displays the New Name dialog box.)

The New Name dialog box.

2. In the Name box, enter a name such as MaxNum. 3. In the Refers To area at the bottom of the dialog box, enter an equal sign followed by

the value you want used for the next ticket number. 4. Click on OK. The new name is stored in the workbook.

Now, add the following macro to the ThisWorksheet object in the VBA Editor:

Private Sub Workbook_NewSheet(ByVal Sh As Object) Dim iMax As Integer iMax = Mid(ThisWorkbook.Names("MaxNum"), 2) Sh.Range("A1") = iMax iMax = iMax + 1 ThisWorkbook.Names("MaxNum").RefersTo = "=" & iMax

ExcelTips 2008 Page 470

Page 484: Excel tips 2008

Macro Tips

End Sub

This macro is executed every time you insert a new worksheet in the workbook. It retrieves the value you stored in the MaxNum, places that value into cell A1 of the new worksheet, and then increments what is stored in MaxNum.

SAVING A WORKBOOK IN A MACRO

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you want to save a workbook under control of your macro, you can use the Save method. This is the same as choosing the Save command from the File menu, so it will display the Save As dialog box if the document you are saving has not been previously saved. The syntax is as follows:

ActiveWorkbook.Save

If you want to save the workbook to a file with a new name, use the following basic syntax:

ActiveWorkbook.SaveAs FileName:=”filename”

where filename is the full name (including a path) that you want used for the file.

PUTTING AN X IN A CLICKED CELL

Applies to Excel 97, 2000, 2002, 2003, and 2007

Wendy has a worksheet that has quite a bit of data in it, with the main data in the range C3:P312. She would like to have a macro that, if she clicks a cell in this data range, would put an "x" into the cell.

There is no event that Excel can recognize as a “click” on a cell. Perhaps the closest event is the SelectionChange event, which is triggered every time the cell selection changes. The event handler could then check to make sure that the cell selection is within the C3:P312 range, and then place an “x” in the cell if it is. The following event handler will do that:

Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim rInt As Range

ExcelTips 2008 Page 471

Page 485: Excel tips 2008

Macro Tips

Dim rCell As Range Set rInt = Intersect(Target, Range("C3:P312")) If Not rInt Is Nothing Then For Each rCell In rInt rCell.Value = "x" Next End If Set rInt = Nothing Set rCell = Nothing End Sub

There is a problem with this approach, however: Not only will the SelectionChange event trigger when you click on a different cell, it also triggers if you use the keyboard to move from one cell to another in the worksheet. This means that if you use the keyboard to move about the worksheet you will leave a tail of “x” characters in each cell you transit.

One way around this is to change the event that triggers the check and change of the cells. While Excel has no “click” event, there is a “double click” event. This means that you can change the cell on which you double click, as shown here:

Private Sub Worksheet_BeforeDoubleClick( _ ByVal Target As Range, Cancel As Boolean) Dim rInt As Range Dim rCell As Range Set rInt = Intersect(Target, Range("C3:P312")) If Not rInt Is Nothing Then For Each rCell In rInt rCell.Value = "x" Next End If Set rInt = Nothing Set rCell = Nothing Cancel = True End Sub

(Thanks to Steve Aprahamian, Marc Prosl, Andrija Vrcan, Patrick Bares, Richard Raciborski, Tim Cantley, Dennis Swearingen, Russell Hendel, and Matthew Murphy for contributing to this tip.)

HIDING EXCEL IN VBA Applies to Excel 97, 2000, 2002, 2003, and 2007

Many macros are written to perform a specific, limited task. Other macros are written as part of a larger, overall application designed to be used start-to-finish by a user. For instance, I have seen accounting packages written completely in Excel VBA. The functions of the accounting package

ExcelTips 2008 Page 472

Page 486: Excel tips 2008

Macro Tips

are written in VBA, of course. The user of the accounting package never uses “regular Excel,” but instead utilizes menus, dialog boxes, and choices presented exclusively by the VBA application.

If you are writing an application in VBA, you may need a way to completely “hide” Excel so that the user never sees it. To do so, you can use this code in a macro:

Application.Visible = False

If your application ends without exiting Excel (such as if an error is encountered), it is important that you set the Visible property to True. If you don’t, Excel will remain in memory, but the user will never see it. The user cannot set this property; it must be done under macro control.

DETERMINING A WORKSHEET'S NUMBER

Applies to Excel 97, 2000, 2002, 2003, and 2007

Lawrence needs a way to determine the number of a worksheet even if the worksheet has been renamed. For instance, if a worksheet is named Sheet11 it is easy enough to figure out that it is sheet 11. If he renames the sheet to January, Lawrence still needs a way to know this is sheet 11.

The solution to this problem is best done with a user-defined function (a macro). There are, in reality, two numbers that the macro could return for each worksheet. The first is the index number for the worksheet. This number represents the index of the worksheet within the worksheets collection for the workbook. This value can be returned by a macro similar to the following:

Function SheetNumber1(shtname As String) Dim sht As Worksheet Application.Volatile For Each sht In ThisWorkbook.Worksheets If LCase(sht.Name) = LCase(shtname) Then SheetNumber1 = sht.Index Exit Function End If Next SheetNumber1 = -1 End Function

This function, when used in a worksheet, will return the index number of any worksheet whose name is passed to the function. If the name that is passed to the function doesn’t exist in the worksheets collection, then a value of -1 is returned by the function. For instance, the following used in a cell would return the index value for the worksheet within the collection:

ExcelTips 2008 Page 473

Page 487: Excel tips 2008

Macro Tips

=SheetNumber("January")

The problem with this approach is that the order of worksheets in the worksheets collection can change over time. Thus, you can’t always assume that the eleventh sheet in the collection is the sheet that was originally Sheet11.

A more consistent way of figuring out the original name for a worksheet (regardless of how it is renamed) is to use what Visual Basic refers to as the sheet’s “CodeName.” This is a property of the worksheet and can be determined in the following manner:

Function SheetNumber2(shtname As String) Dim sht As Worksheet Dim sTemp As String Application.Volatile For Each sht In ThisWorkbook.Worksheets If LCase(sht.Name) = LCase(shtname) Then sTemp = sht.CodeName SheetNumber2 = Val(Mid(sTemp, 6, 4)) Exit Function End If Next SheetNumber2 = -1 End Function

The CodeName property is read-only in a macro. It is assigned at the time that the worksheet is created, but it is possible for it to be manually changed within the Visual Basic editor. The CodeName is always a string, representing the very first name that was applied to the worksheet, so it will be something like “Sheet11”. Once the CodeName is set, even if the worksheet is renamed (such as to “January”), it will remain stable (“Sheet11”).

In the macro example (SheetNumber2) the CodeName property is assigned to the sTemp variable. This will, most of the time, be something like “Sheet3” or “Sheet11”. So, the macro then grabs the numeric value of whatever begins with the sixth character (right after “Sheet”). This is the value that is returned by the function.

(Thanks to Dave Latham, Marc Prosl, Steve Aprahamian, Bob Gannon, Javid Mohammed, Richard Raciborski, Anita Bouman-Eijs, Russell Hendel, Anil Malhotra, Chris Purtill, and Henric Bladh for contributing to this tip.)

RETRIEVING DRIVE STATISTICS Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are creating a full-blown application using Excel, you may want to know a bit about the environment in which your application is running. For instance, you might want to know how

ExcelTips 2008 Page 474

Page 488: Excel tips 2008

Macro Tips

many drives are attached to the system, what their drive letters are, and how much space they have free.

The following macro will retrieve the requested information. All you need to do is provide the column headings. The macro assumes that you’ll have three columns: In cell A1 you should place the heading "Drive," in cell B1 you place the heading "Free%," and in cell C1 you place the heading "Used%." In addition, you should format columns B and C as percentages.

Sub DriveSizes() Dim Drv As Drive Dim fs As New FileSystemObject Dim Letter As String Dim Total As Variant Dim Free As Variant Dim FreePercent As Variant Dim TotalPercent As Variant Dim i As Integer On Error Resume Next i = 2 For Each Drv In fs.drives If Drv.IsReady Then Letter = Drv.DriveLetter Total = Drv.TotalSize Free = Drv.FreeSpace FreePercent = Free / Total TotalPercent = 1 - FreePercent Cells(i, 1).Value = Letter Cells(i, 2).Value = FreePercent Cells(i, 3).Value = TotalPercent i = i + 1 End If Next End Sub

When you first run this macro, you may get an error. If you do, it means that you need to configure your macro to reference the Microsoft Scripting Runtime. Follow these steps from within the VBA Editor:

1. Choose the References option from the Tools menu. VBA displays the References dialog box.

2. In the list of available references, make sure Microsoft Scripting Runtime is selected. 3. Click on OK.

Now the macro should run just fine, and you will have a fully populated table representing all the drives available on your system. (If your system has drives that use removeable media—such as floppy drives—they may not show up unless you have media in them.)

ExcelTips 2008 Page 475

Page 489: Excel tips 2008

Macro Tips

DEFAULT WORKSHEET WHEN OPENING

Applies to Excel 97, 2000, 2002, 2003, and 2007

When you open a workbook, Excel normally displays the worksheet last displayed when the workbook was last saved. You may want a specific worksheet to always be displayed when the workbook is opened, regardless of the worksheet displayed when the workbook was last saved.

You can control which worksheet is displayed by using this macro:

Private Sub Workbook_Open() Worksheets("StartSheet").Activate End Sub

This macro will always display a worksheet named StartSheet. You will obviously need to change the worksheet name to something different; it should exactly match the name of the desired worksheet.

For this macro to work properly, it has to be associated with the workbook object. Follow these steps:

1. Make sure you have only a single Excel workbook open. While this isn’t exactly mandatory, it will make creating the macro a bit easier.

2. Press ALT+F11 to display the VBA Editor. 3. In the Project Explorer window you will see a list of the open workbooks and templates.

If the Project Explorer is not visible on your screen, choose Project Explorer from the View menu.

4. Locate your current workbook in the Project Explorer. It will be named something like VBAProject (MyWorkbook), where “MyWorkbook” is the name of the actual workbook.

5. If there is a plus sign to the left of the current workbook in the Project Explorer, click on it. You should see a list of worksheets appear underneath the workbook.

6. If you don’t see a list of worksheets, but instead see a list of folders with plus signs to their left, click on the plus sign to the left of Microsoft Excel Objects. Now you should see the worksheets.

7. At the bottom of the list of worksheets is the ThisWorkbook object. Double-click on it. A code window is opened.

8. In the code window, paste or create the macro shown above. Make sure you name it exactly as shown.

9. Close the VBA Editor. 10. Save your workbook.

Now, whenever you open the workbook, the specified worksheet will be displayed.

ExcelTips 2008 Page 476

Page 490: Excel tips 2008

Macro Tips

SELECTING CELLS OF A SPECIFIC COLOR

Applies to Excel 97, 2000, 2002, 2003, and 2007

Vanita Ashar asked if there is a way to select cells containing a specific color. Accomplishing the task is easy if you are using Excel 2003 or Excel 2007. Just follow these steps:

1. Press CTRL+F to display the Find tab of the Find and Replace dialog box.

The Find tab of the Find What dialog box.

2. Make sure there is nothing in the Find What box. 3. Click Format. (You may need to click Options to see the Format button.) Excel displays

the Find Format dialog box. 4. Make sure the Patterns tab (Excel 2003) or the Fill tab (Excel 2007) is displayed.

ExcelTips 2008 Page 477

Page 491: Excel tips 2008

Macro Tips

The Fill tab of the Find Format dialog box.

5. From the colors available, choose the color you want to find. 6. Click OK to close the Find Format dialog box. 7. Click Find All. The Find and Replace dialog box expands to show the addresses of all

the cells formatted with the color you specified in step 5.

ExcelTips 2008 Page 478

Page 492: Excel tips 2008

Macro Tips

The expanded Find What dialog box.

8. Click one of the cell addresses in the bottom of the dialog box. Excel selects the cell within the actual worksheet.

9. Press CTRL+A. All of the addresses within the dialog box are selected. 10. Click Close. All the cells of the desired color are selected.

If you are using Excel 97, Excel 2000, or Excel 2002 the only way to select cells of a particular color is to use a macro. Consider the macro shown here:

Sub SelectColoredCells() Dim rCell As Range Dim lColor As Long Dim rColored As Range 'Select the color by name (8 possible) 'vbBlack, vbBlue, vbGreen, vbCyan, 'vbRed, vbMagenta, vbYellow, vbWhite lColor = vbBlue 'If you prefer, you can use the RGB function 'to specify a color 'lColor = RGB(0, 0, 255) Set rColored = Nothing For Each rCell In Selection If rCell.Interior.Color = lColor Then If rColored Is Nothing Then Set rColored = rCell Else

ExcelTips 2008 Page 479

Page 493: Excel tips 2008

Macro Tips

Set rColored = Union(rColored, rCell) End If End If Next If rColored Is Nothing Then MsgBox "No cells match the color" Else rColored.Select MsgBox "Selected cells match the color:" & _ vbCrLf & rColored.Address End If Set rCell = Nothing Set rColored = Nothing End Sub

To use the macro, select a range of cells before running it. The macro then steps through each selected cell and compares its color with whatever color you specify in lColor. If a match is found, then the cell is added to a selection set. When completed, the macro selects only those matching cells, and then exits.

If you would like to find out other macro-based solutions, you can refer to the following article at the Microsoft Knowledge Base:

http://support.microsoft.com/?kbid=142122

DETERMINING MOUSE CURSOR COORDINATES ON A GRAPHIC

Applies to Excel 97, 2000, 2002, 2003, and 2007

Gerald notes that when moving the mouse over a picture on a worksheet the mouse pointer is a cross. He wants to know how he can determine, using VBA, the coordinates of the cross when the mouse is clicked.

Excel doesn’t allow you (even with VBA) to get the coordinates of the mouse pointer on a graphic inserted as a regular picture in the worksheet. If you insert the picture using an Image object in the Control toolbox, you have quite a bit more latitude. Indeed, you can use the MouseDown event handler to determine the coordinates, as shown here:

Private Sub Image1_MouseDown(ByVal Button As Integer, _ ByVal Shift As Integer, ByVal X As Single, _ ByVal Y As Single) MsgBox X & ", " & Y End Sub

ExcelTips 2008 Page 480

Page 494: Excel tips 2008

Macro Tips

This code assumes that the image is named Image1. Similar code could be used to display the cursor coordinates in real time on the status bar:

Private Sub Image1_MouseMove(ByVal Button As Integer, _ ByVal Shift As Integer, ByVal X As Single, _ ByVal Y As Single) Application.StatusBar = Round(X, 0) & "," & Round(Y, 0) End Sub

Either (or both) of these event handlers are obviously associated with Image1, so they need to be added to the code window for that object.

(Thanks to Steve Aprahamian and Stephen Barrett for contributing to this tip.)

LIMITING SCROLL AREA Applies to Excel 97, 2000, 2002, 2003, and 2007

When putting together a worksheet for others to use, you may want to limit the cells that the user can access. One esoteric way to add limits is to use the following steps:

1. Right-click the sheet tab for the sheet on which you want to place a limit. 2. In the resulting Context menu, choose View Code. The VBA editor appears, displaying

the code window for the worksheet whose tab you right-clicked. 3. If the Properties window is not visible, press F4. 4. In the Properties Window, place the insertion point in the box to the right of the Scroll

Area property.

ExcelTips 2008 Page 481

Page 495: Excel tips 2008

Macro Tips

The Properties window in the VBA Editor.

5. Enter the range in which you want navigation possible. For instance, if you want the user to only be able to access the cells in the range A3:D15, then enter that range.

6. Close the VBA Editor.

That’s it; you can no longer move to or select cells outside the range you specified in step 5. The range you enter must be a contiguous range; you cannot enter a non-contiguous group of cell addresses.

COUNTING PRECEDENTS AND DEPENDENTS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Because Excel allows you to create formulas that refer to other cells, it stands to reason that cells can be dependent on each other. In fact, Excel has two technical terms that are used to define the relationship between cells: precedents and dependents. Precedents are those cells on which a formula is based. Thus, if cell A5 contains the formula =A3 + A4, then both A3 and A4 are precedents for cell A5. Dependents are the reverse of precedents. Thus, in this example, cell A5 is a dependent of cells A3 and A4. You can use the auditing tools in Excel to graphically depict these relationships between cells, as described in other issues of ExcelTips.

What if you want to know how many dependents and precedents there are in a worksheet, however? There is no Excel command that displays this information. You can use a macro to calculate and display this information, however. The following macro will do just that:

Sub CountDependentsPrecedents()

ExcelTips 2008 Page 482

Page 496: Excel tips 2008

Macro Tips

Dim ws As Worksheet Dim lDep As Long Dim lPre As Long On Error GoTo err For Each ws In Worksheets ws.Select lDep = 0 lPre = 0 lDep = Range("a1:iv65536").Dependents.Count lPre = Range("a1:iv65536").Precedents.Count MsgBox "Worksheet: " & ActiveSheet.Name & vbCr & _ "Dependents: " & lDep & vbCr & _ "Precedents: " & lPre Next ws Exit Sub err: Resume Next End Sub

When you run this macro, it steps through each worksheet in your workbook and displays the number of dependents and precedents in each.

You should note that the macro only checks the cells in the range A1:IV65536. This is for compatibility with versions of Excel up through Excel 2003. If you are using Excel 2007 and you will have cells outside of this range that contain formulas or values, then you’ll want to modify the range that is checked in the macro.

PREPARING DATA FOR IMPORT INTO ACCESS

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are a database programmer you may sometimes get Excel files that you have to “clean up” to put into Access. Two common problems are caused by Social Security Numbers and ZIP Codes. These are best stored as text in the database, and not as numbers as they often are in Excel. (In Excel the numbers may display properly because of cell formatting, and not because they are stored as text.)

Even when the range is formatted as text in Excel, complete with leading zeroes, Access more often than not converts these values to numbers. However, if the number is preceded with an apostrophe, as for a label, Access will correctly import it as text without the leading apostrophe.

To prepare Social Security Numbers for importing in Access a quick little macro can come in handy—one that makes sure that leading zeros are present and that the apostrophe is in place for

ExcelTips 2008 Page 483

Page 497: Excel tips 2008

Macro Tips

the cell. To use the macro, just select the range of Social Security Numbers and then run the macro:

Sub SSN2Text() Dim c As Range Application.ScreenUpdating = False 'Format selected cells as text Selection.NumberFormat = "@" For Each c In Selection If Left(c, 1) = "'" Then 'strip the apostrophe, if any c = Mid(c, 2, 99) Else c = "'" & Right("000000000" & c, 9) End If Next c Application.ScreenUpdating = True End Sub

The solution for the ZIP Codes is similar in nature. The macro to process ZIP Codes steps through each cell in the selection, formats it as text, adds a leading apostrophe, and plugs in any leading zeroes. The difference is that the macro must also account for instances where there are either five-digit or nine-digit ZIP Codes.

Sub ZIP2Text() Dim c As Range Application.ScreenUpdating = False 'Format selected cells as text Selection.NumberFormat = "@" For Each c In Selection If Left(c, 1) = "'" Then 'strip the apostrophe, if any c = Mid(c, 2, 99) End If If Len(c) <= 5 Then c = "'" & Right("00000" & c, 5) Else c = "'" & Right("00000" & c, 10) End If Next c Application.ScreenUpdating = True End Sub

ExcelTips 2008 Page 484

Page 498: Excel tips 2008

Macro Tips

COUNTING COMMAS IN A SELECTION

Applies to Excel 97, 2000, 2002, 2003, and 2007

At work, Mark regularly needs to count the number of commas in a range of selected cells. He can’t find an Excel function to do this type of task, and is wondering if a macro might be able to do the trick.

While there is no worksheet function that will produce the desired count, there is a formula or two you can use. If you just want to know the number of cells that have at least one comma in them, the following formula will work just fine:

=COUNTIF(A1:A10,"*,*")

If you, instead, need to figure out the number of commas in the range when there could be multiple commas per cell, then you need to use a different formula:

=SUM(LEN(A1:A10))-SUM(LEN(SUBSTITUTE(A1:A10,",","")))

This formula should be entered as an array formula, which means that you should use CTRL+SHIFT+ENTER to enter the formula. If you need to derive the count for a different range, just change the range in two places in the formula.

If you prefer, you could also create a user-defined function to count the number of commas. There are multiple ways to approach such a task; the following is just one example.

Function CountComma(rng As Range) Dim iCount As Integer Dim rCell As Range Dim sTemp As String Application.Volatile iCount = 0 For Each rCell In rng sTemp = Application.WorksheetFunction. _ Substitute(rCell.Value, ",", "") iCount = iCount + _ (Len(rCell.Value) - Len(sTemp)) Next CountComma = iCount Set rCell = Nothing Set rng = Nothing End Function

In order to use the function in the worksheet, enter the following into a cell:

ExcelTips 2008 Page 485

Page 499: Excel tips 2008

Macro Tips

=CountComma(A1:A10)

All of these methods described so far will count commas that are actually in the cell. They will not count commas that appear to be in the cell because of formatting. For instance, if a number appears as “1,234” in a cell, chances are good that the comma is there because of the way that the cell is formatted; it is not really in the cell itself. Such commas are not counted.

Of course, if all you need to do is know the number of commas and you don’t need the value in your worksheet, you can bypass the use of formulas and macros all together. Follow these general steps:

1. Select the range of cells in which you want to count commas. 2. Press CTRL+H to display the Replace tab of the Find and Replace dialog box. 3. In the Find What box, enter a comma. 4. In the Replace With box, enter a comma. 5. Click Replace All.

Excel does the replacement and displays a dialog box that shows how many replacements were made.

(Thanks to Andrija Vrcan, Dave Pettit, Terry O'Connor, Bernard Liengme, Steve Aprahamian, Denise Luhman, Benazir Ibrahim, Daniel Houle, Lou Aiello, Abhay Jain, Marc Prosl, Ellis Smith, Adrian Fielden, Bob Purosky, Mike Abrahams, Brian Rowe, Sequoia Schroeder, Curtis Izen, John Vander Linden, Richard Raciborski, Luis Cabezas, and Joe Smith for contributing to this tip.)

EXTRACTING PROPER WORDS Applies to Excel 97, 2000, 2002, 2003, and 2007

Vanita has a worksheet that contains different combinations of letters in each cell of column A. He is looking for a way to extract the words from that list that are “proper,” meaning that they are found in a spell-check dictionary.

Assuming that the column contains only words (no spaces, punctuation, or phrases), you can manually check the list in this manner:

1. Make a copy of column A into column B. You now have two identical columns. 2. Select column B and run spell check. 3. Every time a spelling change is suggested, accept it. When done, you should have

column A as your original and column B as a spell-checked version of column A. 4. In column C, enter the formula =IF(A1=B1,B1,"") and copy the formula down. This

formula only shows a word in column C if the original word matches the spell-checked version of the word.

ExcelTips 2008 Page 486

Page 500: Excel tips 2008

Macro Tips

5. Copy all the words in column C and use Paste Special to paste Values into another location. You now have a list of validly spelled words.

If you need to perform the validation process regularly, you may want to use a macro to instead create your final list. The following macro steps through the word list in column A and clears any cells that contain words not in the dictionary. After checking all the words, it then deletes all the cleared cells.

Sub ExtractDictionaryWords() Dim rWords As Range Dim rCell As Range Application.ScreenUpdating = False Set rWords = Range(Range("A1"), _ Range("A65536").End(xlUp)) For Each rCell In rWords If Not Application.CheckSpelling(rCell.Value) Then rCell.Clear End If Next On Error Resume Next rWords.SpecialCells(xlCellTypeBlanks). _ Delete (xlShiftUp) On Error GoTo 0 Set rCell = Nothing Set rWords = Nothing Application.ScreenUpdating = True End Sub

Remember—this macro is intentionally destructive in its behavior, meaning that it clears out cells. If you have any need for the original data, you’ll want to run the macro on a copy of the data, not on your only copy.

AUTOMATICALLY LOADING ADD-INS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Michael asked if there is a way to selectively load add-ins for specific worksheets. There is a way to do this, but it involves the use of macros attached to the Workbook module for the specific worksheets. Follow these general steps:

1. Load the worksheet for which you want a specific add-in loaded. 2. Press ALT+F11 to display the VBA Editor.

ExcelTips 2008 Page 487

Page 501: Excel tips 2008

Macro Tips

3. Double-click on the “This Workbook” object in the Project Explorer. Excel opens a code window for This Workbook.

4. Place the following macros in the code window:

Private Sub Workbook_BeforeClose(Cancel As Boolean) AddIns("Add-In Name").Installed = False End Sub

Private Sub Workbook_Open() AddIns("Add-In Name").Installed = True End Sub

5. In the code, change the name of the add-ins (“Add-In Name”) to the real name of the add-in you want to use with the worksheet.

6. Close the VBA Editor. 7. Save your worksheet.

If you are not sure of the correct name for a particular add-in (see step 5), you can use the macro recorder to record the process of activating an add-in. That will show you the exact name you should use in the above macros.

SHEETS FOR DAYS Applies to Excel 97, 2000, 2002, 2003, and 2007

When you are starting a new workbook, it is very common to name each worksheet after a different day of the month. If you do this quite a bit, you know it can be tiresome to rename each worksheet, in turn, to exactly what you need.

The following macro was developed to help in these situations. It checks the names of the worksheets in your workbook, renaming them to the days of the month if they begin with the letters “Sheet”. If there are not enough sheets in the workbook, it adds sheets, as necessary, for each day of the month.

Sub DoDays() Dim J As Integer Dim K As Integer Dim sDay As String Dim sTemp As String Dim iTarget As Integer Dim dBasis As Date iTarget = 13 While (iTarget < 1) Or (iTarget > 12) iTarget = Val(InputBox("Numeric month?"))

ExcelTips 2008 Page 488

Page 502: Excel tips 2008

Macro Tips

If iTarget = 0 Then Exit Sub Wend Application.ScreenUpdating = False sTemp = Str(iTarget) & "/1/" & Year(Now()) dBasis = CDate(sTemp) For J = 1 To 31 sDay = Format((dBasis + J - 1), "dddd mm-dd-yyyy") If Month(dBasis + J - 1) = iTarget Then If J <= Sheets.Count Then If Left(Sheets(J).Name, 5) = "Sheet" Then Sheets(J).Name = sDay Else Sheets.Add.Move after:=Sheets(Sheets.Count) ActiveSheet.Name = sDay End If Else Sheets.Add.Move after:=Sheets(Sheets.Count) ActiveSheet.Name = sDay End If End If Next J For J = 1 To (Sheets.Count - 1) For K = J + 1 To Sheets.Count If Right(Sheets(J).Name, 10) > _ Right(Sheets(K).Name, 10) Then Sheets(K).Move Before:=Sheets(J) End If Next K Next J Sheets(1).Activate Application.ScreenUpdating = True End Sub

The macro sets each tab name equal to the day of the week followed by the actual date, as in “Wednesday 08-13-2008.” If you want to change the way that the tabs are named for each day, just change how the sDay variable is constructed in the macro.

The last step in the macro is that it places the worksheets in proper order, based on the days of the month. The result is that if you have any other worksheets left in the workbook (in other words, you had some that did not begin with the letters “Sheet,” then those worksheets end up at the end of the workbook, after the sheets for each day.

ExcelTips 2008 Page 489

Page 503: Excel tips 2008

Macro Tips

SHEETS FOR MONTHS Applies to Excel 97, 2000, 2002, 2003, and 2007

When you are starting a new workbook, it is very common to name each worksheet after a different month of the year. If you do this quite a bit, you know it can be tiresome to rename each worksheet, in turn, to exactly what you need.

The following macro was developed to help in these situations. It checks the names of the worksheets in your workbook, renaming them to the months of the year if they begin with the letters “Sheet”. If there are not enough sheets in the workbook, it adds sheets, as necessary, for each month of the year.

Sub DoMonths() Dim J As Integer Dim K As Integer Dim sMo(12) As String sMo(1) = "January" sMo(2) = "February" sMo(3) = "March" sMo(4) = "April" sMo(5) = "May" sMo(6) = "June" sMo(7) = "July" sMo(8) = "August" sMo(9) = "September" sMo(10) = "October" sMo(11) = "November" sMo(12) = "December" For J = 1 To 12 If J <= Sheets.Count Then If Left(Sheets(J).Name, 5) = "Sheet" Then Sheets(J).Name = sMo(J) Else Sheets.Add.Move after:=Sheets(Sheets.Count) ActiveSheet.Name = sMo(J) End If Else Sheets.Add.Move after:=Sheets(Sheets.Count) ActiveSheet.Name = sMo(J) End If Next J For J = 1 To 12 If Sheets(J).Name <> sMo(J) Then For K = J + 1 To Sheets.Count If Sheets(K).Name = sMo(J) Then Sheets(K).Move Before:=Sheets(J) End If

ExcelTips 2008 Page 490

Page 504: Excel tips 2008

Macro Tips

Next K End If Next J Sheets(1).Activate End Sub

The last step in the macro is that it places the worksheets in proper order, for the months 1 through 12. The result is that if you have any other worksheets left in the workbook (in other words, you had some that did not begin with the letters “Sheet”, then those worksheets end up at the end of the workbook, after the 12 months.

USING BIN2DEC IN A MACRO Applies to Excel 97, 2000, 2002, 2003, and 2007

Most of Excel’s worksheet functions can be accessed in VBA by using the WorksheetFunction object. Some functions may not seem to be available, however. One such function is BIN2DEC, which converts a binary value to a decimal value. The reason it isn’t available is that BIN2DEC isn’t really an Excel worksheet function—it is part of the Analysis ToolPak add-in.

That being the case, you have two options: you can either load the VBA equivalent of the Analysis ToolPak, or you can create your own BIN2DEC function in VBA. To do the first, make sure that in Excel you install the Analysis ToolPak – VBA add-in. If it is not listed in the available add-ins, use Windows to search for the file ATPVBAEN.XLA. (If you are using a language version of Excel other than English, then the “EN” portion of the file will be different.) This is the actual add-in you want to enable.

Once you’ve enabled the add-in, display the VBA Editor and choose Tools | References to display the References dialog box. Make sure the atpvbaen.xla reference is selected. Close the dialog box, and you can then use BIN2DEC just like you would any other worksheet function.

The other option is to create your own BIN2DEC function. The following is an example of a function that accepts a string that contains the binary digits and returns a numeric value that represents the decimal value of that string.

Function Bin2Dec(sMyBin As String) As Long Dim x As Integer Dim iLen As Integer iLen = Len(sMyBin) - 1 For x = 0 To iLen Bin2Dec = Bin2Dec + _ Mid(sMyBin, iLen - x + 1, 1) * 2 ^ x Next End Function

ExcelTips 2008 Page 491

Page 505: Excel tips 2008

Macro Tips

This function actually doesn’t have the same limitations as the BIN2DEC worksheet function; it will work with binary numbers containing more than 10 digits.

SELECTING ALL VISIBLE WORKSHEETS IN A MACRO

Applies to Excel 97, 2000, 2002, 2003, and 2007

In Excel, selecting all the visible worksheets is as easy as right-clicking on any sheet tab and choosing Select All Sheets. However, accomplishing the same task with VBA code is more difficult.

Excel's online help suggests using the Array function with the Sheets collection to select sheets by name. This works great when you know the names of each sheet in the workbook. This poses a problem when you want to create generic code to select all sheets for any workbook. The good news is that you can use a variant of Microsoft's technique to reference sheets by index number. Below is the code:

Sub SelectSheets() Dim myArray() As Variant Dim i As Integer For i = 1 To Sheets.Count ReDim Preserve myArray(i - 1) myArray(i - 1) = i Next i Sheets(myArray).Select End Sub

This works great, unless the workbook contains hidden sheets, where Sheets(i).Visible = False. Of course, the above code can be adapted to ignore hidden worksheets:

Sub SelectSheets() Dim myArray() As Variant Dim i As Integer Dim j As Integer j = 0 For i = 1 To Sheets.Count If Sheets(i).Visible = True Then ReDim Preserve myArray(j) myArray(j) = i j = j + 1 End If Next i Sheets(myArray).Select End Sub

ExcelTips 2008 Page 492

Page 506: Excel tips 2008

Macro Tips

However, there is a little known parameter of the Select method: the Replace parameter. By using the Replace parameter, selecting all visible sheets becomes much easier:

Sub SelectSheets1() Dim mySheet As Object For Each mySheet In Sheets With mySheet If .Visible = True Then .Select Replace:=False End With Next mySheet End Sub

Note that mySheet is defined as an Object data type, instead of a Worksheet data type. This is done because in testing I encountered a problem with Chart sheets—they wouldn’t be selected because they weren’t of a Worksheet type.

GETTING USER INPUT IN A DIALOG BOX

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you need to get input from a user under control of a macro, one method you can use is to employ the InputBox function. This function displays a dialog box and allows the user to type a response. The result is a string, returned to your macro, which you can then process and use.

The syntax for the InputBox function is as follows:

sResponse = InputBox(sPrompt, sTitle, sDefault)

There are three parameters you can use with InputBox (each of them strings), although only the first one is absolutely required. In this syntax, sPrompt is the text you want displayed as the user prompt, sTitle is the text to display in the title bar of the dialog box, and sDefault is the default text string offered to the user in the dialog box. The user can edit or accept the default string, as desired.

As an example, the following code lines can be used to display a dialog box and ask the user for his or her name:

Dim sUserName as String Dim sPrompt as String Dim sTitle as String Dim sDefault as String sPrompt = "Please check your name and make any corrections" sTitle = "Name Entry"

ExcelTips 2008 Page 493

Page 507: Excel tips 2008

Macro Tips

sDefault = "John Doe" sUserName = InputBox(sPrompt, sTitle, sDefault)

MOUSE CLICK EVENT IN VBA Applies to Excel 97, 2000, 2002, 2003, and 2007

Supriyo asked if there is a mouse event handler in VBA. He wants a value inserted in a cell when that cell is clicked on.

The standard way to do this is with the SelectionChange event. Every time the selection changes in the worksheet, the event is triggered. The event doesn’t just trigger when a cell is clicked on, but also if someone presses a cursor control key that results in a different cell being selected.

As an example, let’s say that you wanted cell B5 to contain the value 10 whenever that cell is selected. To implement that, you could use the following:

Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target, Range("B5")) Is Nothing Then _ Range("B5").Value = 10 End Sub

This code is added to one of the sheet objects in the Project Explorer area of the VB Editor. Double-click the worksheet you want the event handler to apply to, and then add the macro to the resulting code window.

When the SelectionChange event is triggered, the target (the cell range being selected) is passed to the handler. The macro then checks to see if the target range contains cell B5, and if it does, stuffs the value 10 into cell B5. If you want to make sure that the macro only stuffs information into B5 if only B5 (the single cell) is selected, you can use this version of the macro:

Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Address = Range("B5").Address Then _ Range("B5").Value = 10 End Sub

CONVERTING PHONE NUMBERS Applies to Excel 97, 2000, 2002, 2003, and 2007

We have all seen the ads on TV: “Call 1-800-GET THIS for your set of super-sharp knives.” You may be faced with the need to convert phone numbers from the text version (as shown on

ExcelTips 2008 Page 494

Page 508: Excel tips 2008

Macro Tips

the ads) to the numbers represented by that text. The following macro, DoPhone, will perform the conversion magic for you:

Sub DoPhone() Dim rngSrc As Range Dim lMax As Long, lCtr As Long Dim J As Integer Dim Phone As String, Digit As String Set rngSrc = ActiveSheet.Range(ActiveWindow.Selection.Address) lMax = rngSrc.Cells.Count For lCtr = 1 To lMax If Not rngSrc.Cells(lCtr).HasFormula Then Phone = rngSrc.Cells(lCtr).Value For J = 1 To Len(Phone) Digit = Ucase(Mid(Phone, J, 1)) Select Case Digit Case "A" To "P" Digit = Chr((Asc(Digit) + 1) \ 3 + 28) Case "Q" Digit = "7" 'May want to change Case "R" To "Y" Digit = Chr(Asc(Digit) \ 3 + 28) Case "Z" Digit = "9" 'May want to change End Select Mid(Phone, J, 1) = Digit Next J rngSrc.Cells(lCtr).Value = Phone End If Next lCtr End Sub

The DoPhone procedure tries to convert the information in any cell that does not contain a formula. All you need to do is select the cell (or cells) you want to convert, and then run the procedure. The result is that any text in the cells are converted to their digit equivalents on a phone. Thus, 598-Tips becomes 598-8477.

You should note one small peculiarity of DoPhone, and you may want to change it. Some phones recognize the letters Q and Z as the digits 7 and 9, respectively. Others simply leave these digits out, or they are converted to 0. DoPhone, as written here, converts these letters to 7 and 9. You can change the appropriate places in the Select Case structure, as desired, so they are changed to numbers according to your needs. (The appropriate places are commented in the listing.)

ExcelTips 2008 Page 495

Page 509: Excel tips 2008

Macro Tips

RETRIEVING WORKSHEET NAMES Applies to Excel 97, 2000, 2002, 2003, and 2007

If you have a very large number of worksheets in a workbook, you might want to retrieve the names of those worksheets and put then on their own worksheet. For instance, you may want them in one place so you can use them in a table of contents or in some other fashion. The following macro, GetSheets, will quickly retrieve the names of the worksheets in the current workbook and put them in the first column of the current workbook, beginning at cell A1.

Sub GetSheets() Dim J As Integer Dim NumSheets As Integer NumSheets = Sheets.Count For J = 1 To NumSheets Cells(J, 1) = Sheets(J).Name Next J End Sub

GETTING A FILE NAME Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are writing a VBA macro in Excel, you may have a need to allow the user to specify a file they want from the disk. Fortunately, you can access the standard Open dialog box from within VBA and use it to return just a file name. The following example subroutine shows how this is done:

Sub GetFName() Dim FName As Variant Dim Msg As String FName = Application.GetOpenFilename() If FName <> False Then Msg = "You chose " & FName MsgBox Msg Else 'Cancel was pressed End If End Sub

When you run this macro, you will see the standard Open dialog box used in Excel. The user can select a file, and when they click on Open, the file name (including the full path) is assigned to the variable FName. If the user clicks on the Cancel button, then FName is set equal to False. (Thus the test for that in the code.)

ExcelTips 2008 Page 496

Page 510: Excel tips 2008

Macro Tips

FINDING THE LAST-USED CELL IN A MACRO

Applies to Excel 97, 2000, 2002, 2003, and 2007

If you are working in a worksheet, you know that you can press CTRL+END to jump to the last-cell in the worksheet. What the shortcut does is to choose the cell that represents the intersection of the last column containing data and the last row containing data. Thus, if the last column in which you have data is column F, and the last row in which you have data is row 27, then CTRL+END will select cell F27.

To do this same task from a macro, you use a very simple command, as shown here:

Sub FindLast1() ActiveCell.SpecialCells(xlLastCell).Select End Sub

This is functionally the same as pressing CTRL+END. However (and this is a big issue), Excel doesn’t dynamically keep track of which rows and columns are the last used in a worksheet. For instance, let’s suppose that you open a workbook, press CTRL+END, and you are taken to cell F27. If you then delete 3 rows and one column, you would expect that CTRL+END would take you to cell E24. It doesn’t; it still takes you to cell F27, until you save the workbook and reopen it.

This same problem affects the macro code shown in the FindLast1 macro; it will take you to the “highest” cell, regardless of which columns or rows you have deleted during the current session.

What’s needed is a way to reset the “last cell” indicator, just as if you had saved and reopened the workbook. There is no intrinsic macro command that does that, but there is a way to force Excel to do the reset. All you need to do is adjust the macro as follows:

Sub FindLast2() x = ActiveSheet.UsedRange.Rows.Count ActiveCell.SpecialCells(xlLastCell).Select End Sub

This macro will always take you to the proper cell—it works as you would expect CTRL+END to always work. It works because apparently Excel, when it calculates the Count property for the number of rows in the worksheet, will always reset the “last cell” indicator.

ExcelTips 2008 Page 497

Page 511: Excel tips 2008

Macro Tips

USING MACROS IN PROTECTED WORKBOOKS

Applies to Excel 97, 2000, 2002, 2003, and 2007

Lori had a problem with a workbook she wanted to share with others. The workbook contained a macro, but whenever the workbook is protected to prevent others from making changes to the workbook, Lori reports that “the macro is disabled.”

Lori’s exact problem is a little hard to reproduce, as testing shows that macros are still available in both protected worksheets and protected workbooks. You can still display the Macros dialog box and see the list of available macros. You can still choose one of the macros and run it.

Of course, seeing and running the macros may not be Lori’s problem; it could be that the macro fails to run correctly when used on a protected worksheet. If that is the case, the problem typically only crops up if the macro is attempting to perform some action that violates the protection applied to the worksheet. For instance, if the protection doesn’t allow for rows or columns to be deleted and the macro tries to do such, then it won’t work.

The solution in this case is to modify your macro so that it unprotects the worksheet before making its changes. The following shows the basics of how this is done:

Sub ModifyProtectedSheet() ActiveSheet.Unprotect password:="yourpassword" 'work on the worksheet here ActiveSheet.Protect password:="yourpassword", _ DrawingObjects:=True, Contents:=True, Scenarios:=True End Sub

The first line of this example unprotects the worksheet, you can then perform your processing, and then the last line again protects it. If your workbook uses protection, then the same technique can be used with the workbook—unprotect it, then make changes, then reprotect it.

Lori’s problem could also be related to the word “sharing,” which she used in her problem statement. If, by sharing, Lori means using Share Workbook to make the workbook “sharable” by others, then you will see a warning when sharing is activated. The warning indicates that macros cannot be “viewed or edited” in shared workbooks. This does not, however, mean that the macros are disabled, since you can still display the Macros dialog box to see a list of macros and choose one to run. You cannot, however, display the VBA Editor and look at the actual macro code.

Finally, there are some features of Excel that are simply disabled in shared workbooks. If your macro tries to perform any of these disabled actions, it won’t work properly. This is a limitation of Excel, and there is nothing that can be done about it. (For more information on what cannot be

ExcelTips 2008 Page 498

Page 512: Excel tips 2008

Macro Tips

done in a shared workbook, use the online help system and search for “shared workbooks, limitations.”) The only way around these limitations is to not share the workbook.

ITEM NOT AVAILABLE IN LIBRARY Applies to Excel 97, 2000, 2002, 2003, and 2007

Ravi has placed some VBA controls and code in a worksheet. When he shares the workbook with other users and they open it, the functions don't work and report an error "item not available in library." Ravi is wondering how he can get rid of this error.

The first thing to check is whether your macros are actually in the workbook you are sharing with others. Open it on your system, go to the VBA editor, and make sure that the macros are in the project associated with the workbook being shared. If not, you will want to move the macros to the workbook.

A more likely cause of this problem, however, is that your macros are referencing a function or feature that is in a module that you have access to but that the other people do not. An easy way to check this out is to go to their system (if possible) and open the workbook. Then go to the VBA editor and choose Tools | References. Go through the list of available modules and see if there are any that are prefaced with the word “missing.” These are modules that are required for your macros, but are missing on the current system.

If you find missing modules, or perhaps modules that the user needs to reference in VBA in order to use your macros, then it might be best to rewrite your macros so that they don’t use those modules. This may be easier said than done, but it may (again) be the easiest, cleanest way to let others use your macros.

(Thanks to Steve Aprahamian, Eddie Thomas, and Rob Krueger for contributing to this tip.)

AUTOMATICALLY CHANGING REFERENCES TO VBA LIBRARIES

Applies to Excel 97, 2000, 2002, 2003, and 2007

Mark is in a work environment that uses two versions of Excel—2002 and 2003. A problem arises when he opens a workbook with a macro in Excel 2003, which installs the VB library of Office 11, and then later someone tries to open the same workbook in Excel 2002, which gives an error when the macro tries to run because it cannot find the correct VBA library reference. Mark knows he can manually correct this by going to the VB editor and clearing the reference to

ExcelTips 2008 Page 499

Page 513: Excel tips 2008

Macro Tips

ExcelTips 2008 Page 500

the missing VBA library, but he wonders if there is any way to have the workbook check the Excel version automatically and update the VBA library reference accordingly.

One way to deal with this is to create and save the workbook using the earlier version of Excel. When it is opened in the later version of Excel, the reference to the VBA library will be automatically updated. Excel does the updates going to later versions, but it doesn’t do them going to earlier versions.

This means, however, that even if the workbook is created in the earlier version of Excel, once it is opened and subsequently saved in the later version of Excel, users of the earlier version will have problems opening it.

The solution, according to some sources, is to resort to what is known as “late binding.” This simply means that the macro is written so that it looks up specific functions only during run-time, not when the macro is saved. This is referenced a bit in the following Microsoft Knowledge Base article:

http://support.microsoft.com/?kbid=244167

You can try late binding techniques by opening the VBA editor and removing any references previously established. Then add code similar to the following near the start of your macro:

If Application.Version = "10.0" Then 'Excel 2002 Dim oExcel As Object 'Apply late binding Set oExcel = CreateObject("Excel.Application") End If If Application.Version = "11.0" Then 'Excel 2003 ' ' Add whatever references you want for Excel 2003 ' End If

At the end of the macro make sure that you set any defined objects (such as oExcel) to Nothing. A good example of code that is more robust than what is presented here can be found in these articles:

http://www.vbaexpress.com/kb/getarticle.php?kb_id=267 http://www.vbaexpress.com/kb/getarticle.php?kb_id=272

(Thanks to Steve Aprahamian, Eddie Thomas, Richard Raciborski, and Chris Purtill for contributing to this tip.)

Page 514: Excel tips 2008

ExcelTips Archives Your best source of usable Excel information!

For more ExcelTips archives, visit our Web site:

http://store.tips.net