How To Record Excel Macros That Work How To Record Excel Macros That W ork – Make your recorded macros shorter, faster and adaptable to variable-size arrays and workbooks
© By John Franco, Feb 26, 2011
Licensing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publ publisher. isher. If you want to sell this book, use it for commercial purposes, distribute it in bulk quantities in your workplace, or a hard copy version; please Contact me Disclaimer
The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold s old without warranty, warranty, either express expres s or implied. Neither the authors and Wizdoh.com, nor its dealers or distributors, will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software software or hardware hardware products described herein. Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademar t rademark. k. Excel is a registered trademark of of the Microsoft® Corporation Language disclaimer
I do my best but English is not my native language. I apologize for language errors in my writing.
2
How To Record Excel Macros That Work How To Record Excel Macros That W ork – Make your recorded macros shorter, faster and adaptable to variable-size arrays and workbooks
© By John Franco, Feb 26, 2011
Licensing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publ publisher. isher. If you want to sell this book, use it for commercial purposes, distribute it in bulk quantities in your workplace, or a hard copy version; please Contact me Disclaimer
The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold s old without warranty, warranty, either express expres s or implied. Neither the authors and Wizdoh.com, nor its dealers or distributors, will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software software or hardware hardware products described herein. Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademar t rademark. k. Excel is a registered trademark of of the Microsoft® Corporation Language disclaimer
I do my best but English is not my native language. I apologize for language errors in my writing.
2
How To Record Excel Macros That Work Table of contents TABLE OF CONTENTS.................................................................................................................................... 3 TESTIMONIALS ............................................................................................................................................. 6 ACKNOWLEDGEMENT .................................................................................................................................. 8 ABOUT JOHN FRANCO ................................................................................................................................. 9 PURPOSE OF THIS BOOK ............................................................................................................................ 11 1 - INTRODUCTION TO EXCEL MACROS ..................................................................................................... 13 2 - WHAT IS AN EXCEL MACRO .................................................................................................................. 16 3 - HOW THE EXCEL MACRO RECORDER WORKS ...................................................................................... 22
3.1. THE EXCEL RECORDER REGISTERS EVERY ACTION YOU PERFORM ON EXCEL ...................... ................................. 23 3.2. THE EXCEL RECORDER GENERATES A VBA INSTRUCTION AFTER THE GIVEN ACTION HAS BEEN PERFORMED ON EXCEL 25 3.3. THE EXCEL RECORDER CHANGES THE “PROPERTIES ” OF EXCEL OBJECTS PROGRAMMATICALLY ................. ............. 25 25 3.4. THE EXCEL RECORDER USES THE “METHODS” OF EXCEL OBJECTS PROGRAMMATICALLY ...................................... ............. ......................... 30 3.5.
USING “RELATIVE REFERENCE ” PRODUCES DIFFERENT VBA CODE ............................................. ............. 31 31
4 - HOW TO PLAN THE RECORDING OF AN EXCEL MACRO ........ .............. ............. ............. ............. .............. .............. ............. ............. .............. .......... ... 35
4.1. GET RID OF RANDOM PATTERNS ........................................................................... ................................... 36 4.2. BREAK THE MACRO INTO SMALLER CHUNKS ............................................................................................... 37 4.3. DEFINE THE TYPE OF MACRO: STATIC (SPECIFIC ) OR DYNAMIC MACRO ............................................................ 39 Use relat r elative ive references ....................................................... .................................................................................................................. ............................................................... .... 39 Use absolute absolute reference .................................................................................. ........................ ............................................................................................. ................................... 43 43
4.4. PLAN ONLY ONE INSTANCE ....................................................................... .............................................. 44 44 4.5. FINISH THE MACRO SMARTLY ................................................................................................. ................ 44 44 4.6. BACKUP THE FILE BEFORE RECORDING ............................................................. .......................................... 45 45 5 - HOW TO RECORD AN EXCEL MACRO ................................................................................................... 46
5.1. WHERE TO PLACE THE CURSOR BEFORE RECORDING A MACRO ?........................................................ ............. 47 5.2. WHERE TO PLACE THE CURSOR BEFORE STOPPING A MACRO ? ....................................................................... 48 5.3. HOW TO SET UP A MACRO .............................................................................................. ....................... 49 Use a descriptive name .............................................................................................. ....................... 49 49 Assign a shortcut ................................................................ ............................................................................................................................. ............................................................... .. 50 Define where where to store the Macro .............................. ........................................................... ........................................................................ ............. 52 Set a description description ................................................................ .............................................................................................................................. ................................................................ .. 52 52
5.4. HOW TO RECORD A DYNAMIC MACRO ................................................................................................ ...... 52 5.5. HOW TO RECORD A STATIC MACRO................................................................ .......................................... 53 53 5.6. HOW TO START THE RECORDING ......................................................... ..................................................... 54 5.7. HOW TO MODIFY THE MACRO WHILE YOU RECORD ................................................................................. .... 55 55 5.8. HOW TO STOP THE RECORDING OF A MACRO? ........................................................................................... 56 5.9. HOW TO MODIFY THE CODE AFTER YOU RECORD A MACRO ........................................................................... 57 5.10. HOW TO MERGE TWO OR MORE MACROS ............................................................................................... 58 6 - HOW TO INTEGRATE AN EXCEL E XCEL MACRO INTO YOUR WORKBOOKS............. .................... ............. ............. .............. ............. ............ ......61
6.1. HOW TO ACCESS A MACRO FROM THE WORKBOOK IT WAS CREATED ............................................................. .. 62 62 Access a Macro Macro from the Macro Macro Dialog Dialog ........................................................... ............................................................................................ ................................. 68
3
How To Record Excel Macros That Work Access a Macro from a shape, picture, or graph............................................................................... 69 Access a Macro from a shortcut........................................................................................................ 71 Access a Macro from an Event .......................................................................................................... 72
6.2. HOW TO ACCESS A MACRO FROM ANY WORKBOOK ..................................................................................... 75 Access a Macro from the Ribbon (Excel 2007) .................................................................................. 78 Access a Macro from the Ribbon (Excel 2010) .................................................................................. 80 Access a Macro from a toolbar (Excel 2003) ..................................................................................... 84 Access a Macro from a menu (Excel 2003) ....................................................................................... 88
6.3. WHERE TO PUT A MACRO YOU RECEIVE FROM OTHERS ................................................................ ................ 92 6.4. HOW TO STOP THE EXECUTION OF A MACRO ................................................. ............................................ 92 6.5. WHAT TO DO WHEN YOUR MACRO DON’T DO WHAT YOU WANT .......................................... ......................... 92 7 - HOW EXCEL VBA WORKS ...................................................................................................................... 94
7.1. VBA SYNTAX ............................................................... ............................................................ ............ 98 7.2. EXCEL OBJECTS’ PROPERTIES AND METHODS ...................................... ...................................................... 100 7.3. HOW TO FIND EXCEL OBJECTS’ PROPERTIES AND METHODS?....................................................................... 101 Record instructions in a new Macro and then copy and paste them on the Macro you are modifying ........................................................................................................................................................ 102 Get assistance from the “Auto List Members” command while you write ..................................... 102
Use the VBA editor Help section..................... ................................................................................. 105 Use the Object browser .................................................................................. ................................. 107 Use the Local Windows ....................................................................... ............................................ 109
7.4. EXCEL OBJECT MODEL REVEALED ................................................................ .......................................... 110 7.5. POPULAR EXCEL VBA OBJECTS ........................................................................................ ..................... 117 Range .............................................................................................................................................. 117 Worksheet....................................................................................................................................... 122 Workbook........................................................................................................................................ 126 Application (Excel)........................................................................................................................... 129 8 - HOW TO MAKE A MACRO MORE EFFICIENT: SHORTER, FASTER AND SMALLER .............................. 134
8.1. DELETE INCIDENTAL ACTIONS AND MISTAKES ............................................................. ............................... 134 8.2. POLISH ALL THE “WITH ” STRUCTURES ............................................................ ........................................ 137 Delete unnecessary instructions...................................................................................................... 141 Delete “With” structures ................................................................................................................. 141
8.3. GET RID OF FAT CODE (UNNECESSARY SELECTIONS AND REFERENCES) ............................................................ 142 Delete unnecessary Selection statements ....................................................................................... 142 Delete unnecessary references...................................................................................................... .. 143
8.4. ADD VBA CODE HERE AND THERE ....................................................... ................................................... 143 8.8. MAKE THE CODE MORE READABLE ........................................................................ ................................. 144 8.6. DOCUMENT EVERY MACRO .................................................................................................... .............. 145 9 - HOW TO MAKE AN EXCEL MACRO ADAPTABLE TO VARIABLE-SIZED ARRAYS .................................146
9.1. MAKE YOUR MACRO VALID FOR STARTING EVERYWHERE IN THE SHEET .......................................................... 147 9.2. HOW TO CHANGE ABSOLUTE REFERENCES INTO RELATIVE ONES ......................................................... ........... 154 9.3. MAKE YOUR MACRO MAKE DECISIONS ......................................................... .......................................... 154 9.4. AVOID REPETITION ............................................................................................................................. 156 “For Next” Loop ............................................................................................................................... 156 “Do Until” loop ................................................................................................................................ 158
Use counters............................................................................................ ........................................ 159
4
How To Record Excel Macros That Work 10 - HOW TO TROUBLESHOOT AN EXCEL MACRO .................................................................................. 162
10.1. FIX VBA SYNTAX ERRORS ..................................................................................................... .............. 162 10.2. FIX COMPILATION-TIME ERRORS ..................................................................................... ..................... 165 10.3. FIX RUN-TIME ERRORS .......................................................... ............................................................. 166 Ignore an error .......................................................................... ...................................................... 167 Proceed certain way when an error is produced ............................................................................. 168 11 - STRENGTH AND WEAKNESS OF RECORDED MACROS .....................................................................169
11.1. WHAT THE EXCEL MACRO RECORDER CAN DO......................................................... ............................... 170 11.2. WHAT THE EXCEL MACRO RECORDER CANNOT DO .................................................................................. 170
5
How To Record Excel Macros That Work
“Dear John, This is the book I was waiting for! Looking forward to your online Excel School on VBA TNX! Fondest Regards, Dick PS: I ’m verry glad to see you back online again”
Dick
“Just wanted to say thanks for putting out such wonderful, helpful, easy - to-understand tips and instructions. You’re one of the b est resources for Excel on the web! I look forward to learning about VBA!”
Will “Hi John, I downloaded your ebook 'How to record excel macros that work' last night and found the information great . The organisation where I do the course through has been very little help in this area and only has information on Excel 2003 (Can u believe that??). Anyway, your information was much more helpful than anything MS had online - it was great… Thanks again for helping me and everyone else. HAPPY NEW YEAR! Kind regards”
Kylie “Its a wonderful book, helps me to augment my knowledge, tx john !”
6
How To Record Excel Macros That Work Dave “Dear John, I would like to tall you that you do a good job as you give it free. I am a Executive of a pharmaceuticals & I worked here as a Cost Accountant and I believe that I can do a lot better with your book . Thanks” Hasan
7
How To Record Excel Macros That Work
You are enjoying a better Excel Macro book because I received the great advice and suggestions of a spontaneous/welcomed editor. Thank you Ron S.
8
How To Record Excel Macros That Work
“I believe Excel empowers us to express our creativity at work, life and business, and the more you understand it, the more you enjoy working with data and information, and the more things you can do (with less effort).”
I
am John Franco, Excel author of many books like How to write Excel macros from scratch, Understanding Pivot Tables mechanics, How to design Excel dashboards, How to record Excel macros that work, and many more. Since 2009, I have been teaching Excel in a fresh, integrated and intuitive way, using explanations that make sense so you apply Excel tools and tricks to your own context. During this time, I have served to more than 10000 subscribers and more than 1000 customers. I unified all my Excel websites into Wizdoh.com, an online training portal dedicated to make you “Understand Excel More”
I worked as a Civil Engineer for 8 years, for one of the 25th biggest construction companies in the world. At that time I worked under a very stern boss. He was from Brazil, and he was VERY particular in the way he wanted things done. He was also considered an Excel “god”! He could do things with a spreadsheet that I never even knew were possible! And because of HIS expertise, he required a lot out of ME. So this forced me to learn how to become a “guru” myself. It’s true that when you surround yourself with people who are better than you at something, YOU become better in the process! Know my full Excel story here Thanks
9
How To Record Excel Macros That Work
Email me at:
[email protected] Find the education you need to “Understand Excel More” at: http://www.wizdoh.com
10
How To Record Excel Macros That Work
Hi dear Excel user, welcome to my book: “How to Record Excel Macros that Work - Make your recorded macros shorter, faster and adaptable to variable- size arrays and workbooks The purpose of this book is empowering you to delegate to the machine all the tasks that can be done by it. This way you will save tons of hours of tedious work, you will be happier and more efficient at work.
To do that, you will take full control of the recording Macro feature in Excel. After reading and practicing the book concepts you will…
Understand what a Macro is Understand the approach Excel uses to record Macros Plan and record Excel Macros efficiently Increase your confidence to alter the VBA Macro code that is created Integrate your Excel Macros into your workbooks using buttons, menus, ribbons, etc. Get rid of fat code consistently and make your macros shorter and faster Make Excel Macros usable for variable-size arrays And much more…
Keep in mind that this book does not cover Excel VBA language to its fullest. However, I guarantee that you will develop a practical Excel
VBA foundation to move to highest stages with confidence (writing Excel Macros from scratch). How to take full advantage of this book? The book was written for Excel 2007+ users in mind, but I included Excel 2003 directions so both users groups could benefit. I recommend you start at chapter one: Introduction to Excel Macros. Do it even if you are already familiar with recording Excel Macros, the reading is simple and you will refresh vital concepts. Otherwise, jump to the area that most interests you by using the table of contents. 11
How To Record Excel Macros That Work All my experience with recording Excel Macros is here, nothing is left behind. I hope you enjoy the book. John Franco
12
How To Record Excel Macros That Work
“Computing is not about computers any more. It is about living” Nicholas Negroponte
M
acros are for your work on Excel the same thing an Excavator for a Building construction project. Excavating a given building foundation by hand would take maybe months…
=
13
How To Record Excel Macros That Work While doing it by machine, would take only days …
=
When you use manual labor, your productivity is set by your muscle power and the time you can employ your force decreases as you use it because you get exhausted. Even worst…
All the important tasks (pouring concrete, raising pillars and walls, etc.) are halted during the excavation process. You cannot pour any drop of concrete until you finish the foundation hole, only occurring after 12 months. Yes, your goal is finishing the building but you are limited to employ your force and talent on digging, for some boring months. On Excel, the time you employ copying/pasting or moving cells using your mouse is manual labor. While you are doing this industrious work, you cannot employ your energy and talent on the things that add value to your work and organization: analyzing data, finding relationships, etc. (in other words, finishing the building). Here is the good news…
You can reduce your excavation time from months to days by shifting the use of your hands for an excavator. On Excel, you are able to transform your PC from manual to machine mode. 14
How To Record Excel Macros That Work How do you do it? By recording a Macro. Would you excavate by hand if you know an excavator can do the work for you? Would you do the work with your mouse if you know the computer can do it?
Let’ s get deeper!
15
How To Record Excel Macros That Work
“All programmers are playwrights and all computers are lousy actors” – Author unknown
H
ave you used a voice recording? The main benefit of such device is that everything you spoke once can be repeated over and over again without you physically speak again. Your voice is in the tape.
You can even be heard without you been there. The Excel Macro recorder feature is a similar device. The difference is that you store Excel actions instead of your voice. These actions can be repeated again and again without your physical intervention on Excel. For example:
Select a given data region, insert a table, and create a Pivot Table Select a heading of a given table and apply a particular formatting Delete all the empty sheets Delete all sheets except the current one Arrange cells in a particular layout And more…
An audio tape is a set of recorded sounds. A Macro is a set of recorded instructions.
What kind of instructions? Actions like: changing the color of a cell, renaming a sheet, creating a table, sorting, filtering, etc.
16
How To Record Excel Macros That Work To reproduce your voice you hit the Play button on t he recording device; on the other hand, to reproduce a set of actions on Excel you run a Macro. At the same time, your voice is recorded on a magnetic tape, while your Excel actions are recorded in a text file, specifically in a Sub procedure inside a text window called “Module”. See below…
Here is where your instructions are stored…
Your instructions are recorded here
How do you record instructions in a macro? If you are using Excel 2007 or 2010, go to: View>Record Macro>Macro name:>Ok 17
How To Record Excel Macros That Work Or click the status bar. See below…
The Excel 2007/2010 status bar also indicates that Excel is in recording mode…
On Excel 2003 Go to: Tools>Macro>Record New Macro And specify the Macro configuration (name, description, etc.)…
After pressing OK, the status bar indicates that Excel is in recording mode…
While this mode is activated, EVERYTHING you do on Excel will be recorded.
This is not so good as it might appears; the same way your voice recording device registers your hesitations and background noise, the Excel recorder captures all your mistakes and incidental actions. This creates the need to edit recorded actions in Macros.
18
How To Record Excel Macros That Work Tip
While Excel is on recording mode, its behavior is normal, with one exception: in the background, Excel creates a Module (Module1, Module2, Module3, ModuleN) and a Sub procedure with the name you specify on the “R ecord Macro” dialog. By default: Macro1, Macro2, Macro3, MacroN. Now I will record a simple Macro (Macro1). Proceed as above to put Excel in recording mode. Want to see what’ s going in the background? Split the Excel and the Excel VBA editor windows by right clicking on the Windows task bar (arrange windows vertically). See below the code window (Module1) with the Sub “Macro1” before I do my first action on Excel… In other words, this is “Macro1” before I start any action on Excel.
No actions recorded yet
19
How To Record Excel Macros That Work This is “Macro1” after I select the cell A1 on Excel…
This is “Macro1” after I write the words “Hello world” on the cell A1 and press
Enter:
This is “Macro1” after I select the cell A1 again and
delete the content:
If you have never recorded a Macro, you have understood little of what was written on the code windows above. Don’ t worry; you will learn the Excel VBA basics on the chapter: How Excel VBA works on page 84. This way you will 20
How To Record Excel Macros That Work better interpret instructions, get rid of fat code and turn specific Macros into general ones. You will learn now the essential behavior of the Excel Macro recorder…
21
How To Record Excel Macros That Work
“Computers have lots of memory but no imagination” - Unknown
he Excel macro recorder is a built-in engine that traces and stores your actions in Excel; its capabilities and features must be understood so you record efficient macros. Additionally, you will need the Macro recorder even after you learn how to write macros from scratch ; I still use it to record simple macros and as an Excel VBA content provider. So let’s start…
22
How To Record Excel Macros That Work
On your audio recording device; while the Record button is pressed, everything is recorded : your voice and the background noise. On Excel; the same thing happens; while it is in recording mode every action is recorded. These actions might be: selecting a cell, writing a formula, scrolling, formatting a cell, zooming, etc. And every action is written on a line per line basis. Give a look…
The same way a voice recording captures your hesitations and background noise, the Macro recorder captures everything you do, including your mistakes and incidental actions .
23
How To Record Excel Macros That Work Tip
Overlooked actions like: minimizing a window, adding a workbook, closing the current workbook, zooming, etc. are also recorded Look at Macro1 again (below) but now pay attention to some incidental actions I performed while recording the Macro…
Incidental action 1. Maximizing the window
Incidental action 2. Selecting “Sheet2” to make a visual
check of a given cell
Incidental action 4
Incidental action 3. Getting back to “Sheet1”
24
How To Record Excel Macros That Work
When you record your voice, you need to talk first so the recording device captures your speech; the same thing happens with Excel Macros. You need to perform an action on Excel (see left window below) so the Excel recorder registers it. See below…
Selection first Recording later
This is one of the main shortcomings to develop smart applications. A Macro does not have flow control, it starts and ends. It has no anticipation, no decision. The unique way to build smart applications is by improving a Macro or by writing it from scratch.
Let’s see the next feature…
At first sight the produced VBA language is Greek; nothing more far from truth. Decode the VBA language grammar quickly by reading a short introduction to objects…
On the real world, your hair has properties: length, color, type; you c an cut it, change its shape, etc. Your hair behaves in specific ways: it grows, it falls, etc. 25
How To Record Excel Macros That Work Some properties can be changed, like the color. Yes you can apply a cosmetic treatment and turn your black hair into red, blond, etc. Some properties properties are read-only, r ead-only, you can know them but you can’ t change them. For example: your hair type: curly, straight. Let’s summarize the features of your hair…
A Property is what wh at you hair is: length, le ngth, color, etc. A Method is what you yo u can do with your hair: cut it, change chang e its shape s hape An Event is how your yo ur hair behaves: beh aves: it grows, it falls, fall s, etc.
Now back to Excel…
Excel has properties and methods too, and you can manipulate them by using VBA language. You are fully aware of the way wa y you change properties prop erties of Excel objects, objects , you know how to change the color of a cell, the font, the name of a sheet, etc. But you are not quite aware of how to change them programmatically; a Macro preforms that very easily. Let’s see it… Record a new Macro, t hen, change the column A width…
26
How To Record Excel Macros That Work
On the background, background, Excel translates that into VBA code. For now, imagine im agine there is one by one correspondence between everything you do on Excel and the VBA code.
27
How To Record Excel Macros That Work So the above action would produce the following code…
Now do this action…
It would produce the following code…
28
How To Record Excel Macros That Work This other action …
Would produce this code …
29
How To Record Excel Macros That Work
The same way you change the properties, you use the methods of Excel objects when you cut a cell, delete a sheet, open a workbook, etc. Here are some examples of how the Excel recorder uses Excel methods: The following action…
Would produce the following code…
Here is another example:
30
How To Record Excel Macros That Work This action…
Would produce this code…
These actions…
Cut A1 Select B1 Paste
are recorded differently when you set the reference of the Macro to absolute… 31
How To Record Excel Macros That Work Here’ s the recorded Macro… When you run this Macro it will always select the Range(“A1”)
How do you set an absolute reference? On Excel 2007 go to View>Macros>Clic k on the drop down arrow; and then…
Don’ t press it
On Excel 2013 go to Developer>Code>Use Relative References. Deactivate it
On Excel 2003, use the “Stop Recording” toolbar (displayed in recording mode)
32
How To Record Excel Macros That Work Now if you perform the same actions above: cut, select and paste but using relative reference, you would get a code like this one…
When you run this Macro it will select the active cell instead of Range(“A1”)
Using relative reference is critical if you want to create Macros that work for variable-size arrays and workbooks. How do you set the reference to Relative? See below… On Excel 2007 go to View>Macros>Click on the drop down arrow; and then…
Press it
On Excel 2013 go to Developer>Code>Use Relative References. Activate it
On Excel 2003, use the “Stop Recording” toolbar (displayed in recording mode)
33
How To Record Excel Macros That Work Tip
You can change the reference from absolute to relative and vice versa while you record. This has been all about how the Excel recorder works. Now, let me share to you everything about…
34
How To Record Excel Macros That Work
“Simplicity i s the ultimate sophistication” - Leonardo Da Vinci
R
ecording a Macro is very easy from the point of view of the initiation process; you launch the Record Macro command and Excel starts to record everything you do.
But the Excel recorder will also record your mistakes, so if you want to record Macros that make what you want, you need to do some extra steps. I will show them below. But before you plan a Macro, you must answer the question: can this given task be done without Macros? You will know it to the extent you know the available functions and commands of Excel. Here’ s an example: not many users know how to transpose a column into a row and vice versa.
35
How To Record Excel Macros That Work You can do this by using the Transpose option of the Paste Special command but if you don’ t know this, you would intend to record a Macro. It is not good trying to reinvent the wheel. Overlooking available Excel commands leads you to record unnecessary Macros. Tip
You will avoid recording unnecessary Macros as long as you know more about Excel available features. Now that you are ready to record a Macro, here’ s the process to make it efficiently…
Imagine you have a database like the one shown below with thousands of registers in raw format on column A. All the records are separated by one row, except the first group that is separated by two rows. See below…
Only this group is separated by two rows
36
How To Record Excel Macros That Work The purpose of your Macro is to turn each block of data into a line (table format). The formatting would be something like this one:
Recording a Macro in such circumstances would demand you create a Macro for two conditions. Yes you can do it, but let me ask you a question: is the development time worth the effort? It would be better to delete that row and record a Macro for a version of the report that has one row separation between blocks of data. Some prototyping measures include:
Pasting all the data into the same sheet Leaving the same amount of space between data Get rid of random stuff Any other measure to uniform the data
Tip
Don’ t try to make your Excel Macro EXCESSIVELY universal at least the the development time and effort will pay off. Tip
You can do the prototyping actions with a Macro too.
Henry Ford stated that any task can be done if it is divided in enough doable parts. Plan your keystrokes by dividing them in workable parts. You decide what is doable for you. Here are some examples:
Formatting, editing, etc. Moving cells, deleting rows, writing field headers, etc. You can be as detailed as you prefer
For the case above, you can divide the Macro in two stages:
37
How To Record Excel Macros That Work 1. Arrange data (move cells and delete the inter-block row)
Move cells
Delete row
And…
2. Creating the table headings Write table headers
Don’ t worry about having separate Macros; you can run them separately or merge them very easily. See: How to merge two or more Macros. Another idea is to perform a kind of dress rehearsal, this way you detect bottlenecks; with this information you can decide how to make the Recording Macro process more manageable. It doesn’t hurt to try and make mistakes; given the fact that you create a backup to restore it at any time. Tip
Recording a Macro in a relaxed manner helps you to minimize incidental actions and mistakes.
38
How To Record Excel Macros That Work
If all your tables would have 100 rows and 5 columns, just one Macro would work all the time; but your Excel tables usually come with more or less data. Hopefully, you can record a Macro that runs on variable conditions including variable-size arrays and variable-location. Here’s how to do define a Macro that will work for variable conditions… Imagine you want a Macro that adds field headers (Name and City) to a table. See below…
39
How To Record Excel Macros That Work But the tables are not on the same position, see the tables below…
The relative reference makes your Macro works based on the position of the cursor when you recorded the Macro.
The cursor was here before recording the
The cursor must be here
Macro
before running the Macro
The cursor was here before recording the
The cursor must be here
Macro
before running the Macro
Or this other way…
Choose the location of the cursor carefully so you can remember that position easily in the future when running the Macro.
40
How To Record Excel Macros That Work How do you activate the relative reference parameter? It is very easy…
On Excel 2007/2010, go to: View>Macros>Macros
Activate this option
On Excel 2013 go to Developer>Code>Use Relative References.
On Excel 2003, activate it by using the “Stop Recording” toolbar (displayed while you are recording):
For example: I recorded the process shown below (writing the title, date and table headings) in a Macro with relative references …
The cursor was here before I recorded the Macro
41
How To Record Excel Macros That Work Even I recorded the actions starting on cell “A1”, the Macro will work on any cell from where I run it, see below… The cursor must be here before I run the Macro
The cursor must be here before I run the Macro
Now look at how Excel records a Macro with relative references…
The Macro does not use static ranges like Range (“A1”)
Tip
Absolute or relative reference setting can be changed during the recording If you want to create the same table always at one location, whatever the position of the cursor; you need to use absolute reference…
42
How To Record Excel Macros That Work
Use this option when your Macros will be applied on the s ame location all the time. See below…
Deactivate this option
For example, if you record the actions that produce the table formatting below using absolute reference, the table will be always produced at that location.
This table will be always produced at this location
See how the Macro starts…
Alwa ys starts on A1
43
How To Record Excel Macros That Work
On the example below, you want to rearrange thousands of groups of raw data into table format. You need to plan one block because the rest is the same. The Macro is the processing of one block repeated thousands times.
Focus on having one block right, the rest is just repeating.
When you have thousands of blocks that repeat like the case shown above, you must record a block and finish the Macro at the start of the next block. In other words, the Macro will start on block 1 and will finish on the beginning of the block 2. Don’ t forget to set reference to relative. If you assign a shortcut to a given Macro you can execute it thousands of times with a simple keyboard pressing. This practice is great when you don ’ t want to use loops or have not learned to use them yet. 44
How To Record Excel Macros That Work Tip
Record a Macro at the start of one block and finish it at the start of the next block.
Take into account that the actions are not undoable when you are recording a Macro. In consequence, avoid headaches. Have room for mistakes. Use the Save As command or make a copy using the Windows Explorer. You can also make a copy of the sheet you will apply the Macro on. Now you are ready to learn…
45
How To Record Excel Macros That Work
“ Man is still the most e xtraordinary computer of all” - John F. Kennedy
R
ecording a Macro is a linear process, you cannot move forward/backward and you cannot undo the recorded actions. Assuming you have planned your Macro, here you will learn how to record it.
In a nutshell… To record a Macro, proceed this way…
On Excel 2007 or 2010 go to: View>Record Macro>Macro name:>Ok or click the Macro icon at the status bar…
After you click the Ok button, Excel turns to recording mode. The status bar always indicates that Excel is in recording mode, see below…
On Excel 2003, go to: Tools>Macro>Record New Macro>Macro name:>Ok. Excel 2003 shows “Recording” at the status bar to let you know it is in recording mode…
This is just the beginning of the recording process. Let ’s go into details now… 46
How To Record Excel Macros That Work
This step is critical.
It defines the reusability of the Macro.
The starting location of the cursor does not matter when you are recording Macros that perform operations on the same location on each next time (using absolute references). On the other hand; the location of the cursor is critical when you are recording Macros that perform operations on a different location each next time (using relative references). Before you record a Macro, place the cursor at “the start” of any given sequence of actions. Choose a place that is reproducible later when running the macro. See below…
47
How To Record Excel Macros That Work Always place your cursor at the right place before you launch the Record Macro command. Tip
When you record dynamic macros, place your cursor at a border location you will easily remember later.
The last position of the cursor does not matter when you are recording Macros using absolute reference. On the other hand; the ending location of the cursor is critical when you are recording Macros using relative reference. Before you stop a Macro place the cursor at “the start” of any given NEXT sequence of actions. See below…
48
How To Record Excel Macros That Work What happens when you do this? Your Macro will move across blocks of data on each run. Tip
Assign a shortcut to a Macro to execute it with ease
You should set all the parameters of a Macro: Name, Shortcut, Store Macro in, and Description. Here I will show you how to do it…
You create Macros for reusing them; so a good name increases the usability of a Macro. It allows you to pick the right Macro on the dialog or on the code window. For example: compare these names “Macro1”, “OpenWorkbook”. See below…
You can discern what the Macro does by looking at the name. Additionally, you will remember Macros weeks or months later. A good practice is to start a Macro name with a verb followed by the name of the object it affects (start each section in uppercase), for example:
OpenWorkbook 49
How To Record Excel Macros That Work
CloseExcel DeleteFormat ChangeColorCell ChangeColorFont
This also increases the usability of a Macro. You run a Macro from two keystrokes instead of searching the Macro on the Macro dialog list. On the Record Macro dialog, specify the shortcut key by just typing the letter you want to assign to the Macro. The shortcut key text box is case sensitive…
50
How To Record Excel Macros That Work You can change the shortcut and description later by going to the Macro dialog and click the Options button. See below…
51
How To Record Excel Macros That Work
There are two options:
Storing the Macro on a workbook. This forces you to open the file to run the Macro Storing the Macro on a binary file workbook (PERSONAL workbook). This enables you to run the Macro without opening any file. In other words, a given Macro will be available for all workbooks of a given Excel session
Learn more about where to store your macros on the chapter: How to Integrate an Excel Macro into your Workbooks You forget what a Macro does hours later, l ater, so provide pro vide a description des cription about its purpose, and specify any detail needed for the correct use. This is more important if the Macro will be used by other ot her users. The description can be edited later using the “Options…” button of the Macro
dialog
As explained above, abov e, this must be done when you want w ant the Macro runs r uns on different different positions from where it was w as recorded and for different array sizes. Here’s the step by step procedure… 1. Put your cursor at the starting position of your raw data (Don't 52
How To Record Excel Macros That Work include earlier mouse movements in your Macro ) 2. Launch the Record Macro dialog 3. Assign a shortcut shortc ut to your Macro (so ( so you can repeat re peat it easily easil y - you will wil l do a kind of manual loop) 4. Click Ok on the Record Macro dialog 5. Use relative references. references. Do this before you perform any movement of your cursor 6. Record one instance of the Macro (if you have one thousands t housands blocks blocks of data, record just one) 7. Stop the Macro when your mouse is at the starting position of your next block of data (corresponding position to the location you started on step 1 of this tutorial) Learn more about how to develop adaptable Macros by going to: Make your Macro valid for starting everywhere in the sheet.
As you learned learn ed before, these th ese types of o f macros perform operations op erations on the same location each next time (using absolute reference). Here’s the step by step procedure… 1. Launch the Record Macro dialog (not necessary to put your cursor at any given position in your spreadsheet; spreadsheet; in other ot her words, you can c an include earlier mouse movements in your Macro 2. Assign a shortcut to your Macro (so you can repeat rep eat it easily) 3. Click Ok on the Record Macro dialog 4. Use Absolute references. Perform this before you perform any movement of your cursor. The absolute reference is set by default; in case Relative references are activated, deactivate them this way…
a. On Excel 2003 do it this way: click the Relative Reference button on the Stop Recording toolbar: b. On Excel 2007 do it this way: go to View>Macros> Macros>Use Relative References: 5. Record the keystrokes keystrokes you want to be repeated in your macro 6. Stop the Macro when all the keystrokes are recorded
53
How To Record Excel Macros That Work Tip
You can change reference r eference setting setti ng while recording. recordi ng.
Assuming that your cursor is on o n the correct position (for generally-applicable generall y-applicable Macros) you just need to hit the Ok button and record the actions you have planned.
Relax please ,
if things go wrong, you have a backup copy to try it again.
54
How To Record Excel Macros That Work
Split the windows (Excel VBA editor and Excel) so you know what lines are added as you execute movements on Excel. This way, you get awareness of the way each action is turned into VBA code. See below…
If you commit mistakes or perform incidental actions, you can delete them “on the go” and keep recording. See below…
Delete these lines of code and keep recording
Take care to not delete the last Selection statement. e.g. Range(“A2”).Select ;
when the next instruction depends on it. Take care to not delete the “End Sub” statement. It is required for Excel to
recognize where the macro ends. 55
How To Record Excel Macros That Work Tip
The new Macro code will be always written at the bottom of your last line in the Sub procedure.
Once you have performed the last operation, you are ready to stop the recording of the Macro. Take into account the fact that you can delete instructions in a Macro while you are recording so it is not necessary to stop it each time you make a mistake. Additionally, you can take notes of the portions that need to be deleted/modified and keep going. If you are finished or you want to stop the Macro because you made huge mistakes, do it this way…
By clicking the stop icon on the status bar (Excel 2007 and 2010) Or by going to: View>Macros>Stop Recording
On Excel 2003, the “Stop Recording” toolbar is shown automatically after you start recording. See toolbar below…
Sometimes, you close this toolbar by mistake and don ’ t know how to stop the recording of a Macro; you can do it by going to Tools>Macro>Stop Recording.
56
How To Record Excel Macros That Work
Or you can show the toolbar again by right clicking on the toolbar area and activate the “Stop Recording” toolbar. See below…
If you are not comfortable with the code being created it is time to improve it. To make even minor modifications you need at least a basic foundation of Excel VBA knowledge. See: How Excel VBA works on page 84 for a quick introduction. If the modifications are big enough, there is no alternative than record the Macro again or write it from scratch (out of the scope of this book).
57
How To Record Excel Macros That Work
Not all Macros are recorded in one sitting; you can enhance an existing Macro or record new lines apart and add them to an existing Macro. How do you do it? Just open the module that contains the Sub procedure (Macro), place the cursor on the desired location and paste instructions recorded in other Macros.
Open the module
58
How To Record Excel Macros That Work Here is an example of how to merge code… This Macro writes “Hello world” on cell A1
This other Macro does the same on A1 of the Sheet2
This is a new Macro: Macro 1 + Macro 11
59
How To Record Excel Macros That Work Or macro11 nested in macro1
You can also paste code to the Macro while recording. Tip
Keep aware that the Selection statements instructions of the pasted code are corresponding to the preceding and subsequent lines.
60
How To Record Excel Macros That Work
“I do not fear computers. I fear the lack of them” - Isaac Asimov
W
hen you travel, bringing your camera with you is not enough; if the camera is stored on a bag difficult to open, you will lose important shots. It is better to carry the camera on your hand.
Now your Macro lies dormant in some module. It is of no value to your productivity if you cannot access it easily and at the right time. Here you will learn:
Where to put your recorded Macros (recorded by you or received from others) How to make a Macro available to all workbooks How to make a Macro available to the workbook where it was created
To access a Macro effectively you must first know where it is located. You specify this at the moment of recording. Macros are stored in the same excel file as VBA modules. You can export modules as .bas files. Let’s start…
61
How To Record Excel Macros That Work
Every workbook has its own modules where Macros can be stored. All these Macros can be accessed from the given parent workbook. See below…
How do you make a Macro available to a workbook? You need to put it into a module of the given workbook. How do you do that? You have three options:
62
How To Record Excel Macros That Work 1) Specify the location at the moment of recording Set the field “Store Macro in:” to This Workbook or New Workbook. See below…
What happens when you use this option? Excel creates a module (Module1 by default) with a Sub procedure with the name “Macro13” or the name you specify on the “Macro name:” text box Tip
Changing the name of the module or the Sub won’ t affect their listing on the Macro dialog.
63
How To Record Excel Macros That Work 2) Paste a Macro into a workbook module You can also create your own modules and store Macros there. See below…
All the Macros contained in modules are displayed in the Macro dialog. See below…
64
How To Record Excel Macros That Work For editing and managing purposes, it is a good practice to locate Macros in related modules with meaningful names. Keep in mind that those macros that contain arguments are not displayed on the Macro dialog.
This macro (with arguments) is not listed on the Macro dialog
65
How To Record Excel Macros That Work You can also store your Macros on .txt files. Later, you can copy and paste the code into a module of any given workbook.
66
How To Record Excel Macros That Work 3) Import a module
Another way to bring a Macro into a workbook is by importing a module. On the Visual basic editor, go to: File>Import File… Or right click on the Project Explorer (CTRL + R) and choose Import File…
Once your Macro is on a module of a given workbook you can call it using several methods…
67
How To Record Excel Macros That Work
Launch the Macro dialog by pressing ALT + F8. Then, choose “Macros in:” and select This Workbook (the Macros are listed on the pane below “Macro name:”).
Then select the Macro you want to run and hit Run.
68
How To Record Excel Macros That Work
The above method is not so good because you need to perform some clicks to run a Macro. If you want to run a Macro with a mouse click, then you need to run Macros from graphic Excel objects like: shap es, pictures, graphs. It is very easy…. Insert any of these objects and right click over the object and then click Assign Macro. See below…
On the Assign Macro dialog, choose the desired Macro. Now your button is clickable! Add an extra touch…
69
How To Record Excel Macros That Work Right click over the button and choose “Edit text”…
You can create fancy buttons!
Tip
You can copy and paste a button to other workbook. The path of the Macro will be kept
70
How To Record Excel Macros That Work
Configure the shortcut when you start recording a Macro.
If you forget to specify the shortcut at the moment of the recording, you can specify a shortcut later on the Macro dialog. Do it by going to: ALT + F8>Options>Shortcut key: See below…
71
How To Record Excel Macros That Work
You can also launch a Macro when the user changes a cell, when a book is opened, etc. You can use the events of each object. Here is how you can do it…
On the Project Explorer window (CTRL + R), double click on the object for which you want to specify the Macro…
72
How To Record Excel Macros That Work I used Sheet1 for this example; then, on the code window, choose Worksheet. See below…
Then choose the event…
Then paste the Macro you want to be executed when Sheet1 changes…
73
How To Record Excel Macros That Work Or you can also call the Macro that is located in some module of the current project…
74
How To Record Excel Macros That Work
To make a Macro available to all your workbooks and from any session of Excel you must store it in the Personal workbook. The Personal workbook is a binary file (.xlsb) saved in a central location. The Macros on this workbook are visible to all books in any Excel session. See below…
75
How To Record Excel Macros That Work How do you do that? Specify the location at the moment of recording Set the field “Store Macro in:” to Personal Macro Workbook. See below…
At the moment of running the Macro, it is not necessary you open the Personal Macro Workbook. See below…
This book is automatically shown
Tip
By default the location of the personal workbook is: 76
How To Record Excel Macros That Work
Windows Vista: C:\Users\user name\AppData\Local\Microsoft\Excel\XLStart Windows XP: C:\Documents and Settings\user name\Application Data\Microsoft\Excel\XLStart
Now that your given Macro is properly stored, you can…
77
How To Record Excel Macros That Work
Unfortunately, Excel 2007 does not allow you to customize the Ribbon. The most you can do is to personalize the Quick Access Toolbar (QAT)…
Do it this way…
1. Right click over any area of the Ribbon and choose “Customize Quick Access Toolbar…”
2. Choose Macros from the “Choose commands from:” list…
3. Select the Macro you want to add to the QAT and click on the Add>> button…
78
How To Record Excel Macros That Work 4. Click on “Modify…” and assign a meaningful name:
Your QAT is ready…
79
How To Record Excel Macros That Work
Now that your Macro can be called from any workbook, it is a good idea to create a dedicated Ribbon. Just to refresh your knowledge of the Excel Ribbon, let ’ s familiarize with the components again…
Tab
Group
Commands
Commands
Group
In 2010 you MUST create a new tab to be able to add new commands and macros. The existing tabs can only be modified to remove commands, new commands or macros cannot be added. Create a new tab with groups and commands (Macros) by proceeding this way…
1. Right click over any area of the Ribbon and choose “Customize the Ribbon…”
80
How To Record Excel Macros That Work 2. Click on New Tab
3. Right click on the new tab and choose Rename. Assign a meaningful name
4. Right click on the default group created and choose Rename. Assign a name. See below…
81
How To Record Excel Macros That Work 5. Choose Macros from the “Choose commands from:” list…
6. Select the Macro you want to add to the selected group and click on the Add>> button…
82
How To Record Excel Macros That Work 7. Right click over the recently added Macro and choose Rename. Assign a meaningful name and icon. See below…
Your new Tab is ready to use.
Tip
You can export your Ribbon personal configuration and load it on any other PC.
83
How To Record Excel Macros That Work
Now that your Macro can be called from any workbook, it is a good idea to create a dedicated toolbar. Just to refresh your knowledge of the old Excel toolbar system, let ’ s familiarize with the components again…
Toolbar
Commands
You can create a new toolbar with commands (Macros). Proceed this way…
1. Right click over any toolbar and choose Customize from the contextual menu.
84
How To Record Excel Macros That Work 2. Click on New… in the Toolbars tab and assign a meaningful name. See below…
3. Click on Commands tab>Categories: and go to Macros. Then drag and drop a Custom Button (Commands: area) to the recently created toolbar. See below…
85
How To Record Excel Macros That Work Right click over the recently created button and click “Assign Macro…”.
the Macro to link to the button.
Choose
86
How To Record Excel Macros That Work 5. Modify the appearance of the button by right clicking on it and choosing: Edit Button Image, Name, etc.
Now your new toolbar is ready
You may also place a macro command on an existing toolbar.
87
How To Record Excel Macros That Work
Now that your Macro can be called from any workbook, it is a good idea to create a dedicated menu. Just to refresh your knowledge of the old Excel menu, let ’ s familiarize with the components again…
Menu Command
Command
Proceed this way…
1. Right click over any toolbar and choose Customize from the contextual menu.
2. Click on Commands tab>Categories: and select “New menu”. Then 88
How To Record Excel Macros That Work drag and drop the “New Menu” button (Commands: area) to the desired location in the menu area. See below…
A new menu is created
89
How To Record Excel Macros That Work 3. Click on Macros and then drag and drop a “Custom Button” to the recently created menu.
90
How To Record Excel Macros That Work 4. Right click on the recently created button and then click assign Macro.
91
How To Record Excel Macros That Work Proceed the same way as explained above in Access a Macro from a toolbar (Excel 2003) on page 75. You may also place a macro on an existing menu.
First, open the workbook that contains the Macro, go to the module and copy the procedure, then open the destination workbook and open or create a module and paste the Sub procedure. You can also import any given module.
You know how to run a Macro but what happens when the Macro is taking too much time or the Macro don ’ t do what you want? You can stop a Macro while it is running by pressing the Esc key. And then, by pressing the End button. See below…
Press the End button
If a Macro doesn’ t do what you want, you have three lines of actions:
Recording it again, Fine-tuning it or Writing it from scratch 92
How To Record Excel Macros That Work Writing a Macro from scratch is out of the scope of this book but now I will show you how to improve your Excel Macros.
93
How To Record Excel Macros That Work
“Those parts of the system that you can hit with a hammer (not advised) are called hardware; those program instructions that you can only curse at are called software.” - Unknown
I
magine you are going to spend your next vacation on Japan, you don’ t know Japanese but you equip with a 3-phrase vocabulary:
• Where • How
do I find cheap hotels?
to Record Excel Macros that Work
•How can I reach the airport?
After landing, your trip is going wonderful but suddenly your little son feels sick at the zoo…How do you ask for help? The three phrases serve too little. To
succeed in capricious situations, you need a wider lexicon. Recording Macros without knowing Excel VBA language is t he same situation, you soon face disorientation because you don ’ t know what the VBA code does and how to adapt your script to new situations like making your Macros work for variable-size arrays and workbooks. You can only be efficient on real social environment by understanding the language grammar so you can construct new expressions as new needs arise. At the same time, to get ahead on your automation requirements you must understand the basic principles of Excel VBA so you record Macros with confidence and alter its code to suit your needs. This book enables you to record efficient Macros and to gain a reasonable Excel VBA grammar awareness so you deal with new situations with more confidence. Let’s understand the Excel VBA language better… 94
How To Record Excel Macros That Work Have you played Mario Bros videogame?
I bet you did! If not, you are somehow familiar with it because your children play it or because you have seen some TV commercial. Anyway…
Let’ s imagine for a moment you are a skilled video game developer (a coder) and you are creating the Mario character (the tiny guy on red dress below) for a new version of the game…
As the developer, you must define his behavior and unique characteristics so players can manipulate Mario using a joystick.
So by the means of game designing tools you set all his features… You first define his properties (physical and non-physical): 95
How To Record Excel Macros That Work
Hair color Dress color Height Score
You also define the actions he will perform (methods):
Walk Run Jump
Finally, you define the consequences of the actions Mario executes (events); for example: if an enemy kills Mario, he will die. You cannot create a command to make it die because nobody dies by command. Dying is a consequence of being killed, being ill, etc. The events you would create are:
Height increasing (when Mario eats a mushroom). Mario has two height modes: short (by default) and tall (after he eats a mushroom) Height reducing (when he is hit by an enemy while he is in tall mode) Die (when he is hit by an enemy while he is in short mode)
Mario is ready. He is now an object with behavior and characteristics. By using the same developing means you must specify how the properties, methods and events interact with the user. In other words, how Mario would interact when a user uses a joystick. Any given player can change Mario height property by eating a mushroom or he can make him run, jump, etc. Let’s imagine you write the instructions in plain English… 96
How To Record Excel Macros That Work If Mario eats a mushroom, then change the height of Mario to 5 pixels ,
you can use a more structured syntax:
or
IF Mario eats a mushroom THEN Mario height = 5 pixels In VBA language this would be…
Mario.height = 5 In Excel VBA you do it this way…
Range("A1").ColumnWidth = 30 Range("A1").Font.Size = 12 Worksheets("Sheet2").Name = "Data" Etc
Now let’s talk about the methods… When you give instructions in real life, you provide further specifications so the given action is completed adequately. For example: bring me a hamburger without tomato, stop the car before the white line, etc. For the above case, the arguments for the command “bring me” are: what
(hamburger) and how (without tomato). If a player uses joystick buttons to make Mario run slowly to the left, you would say in plain English…
Run Mario at slow speed to the left. In VBA language this would be…
Mario.Run (slow, left) “slow” and “left” are arguments for the Run method.
Some methods do not require any argument like: jump Mario. Using VBA language this would be…
Mario.Jump In Excel VBA you do it this way…
Range( “A1”).Select
Range(“A1”).ClearComments
97
How To Record Excel Macros That Work
Worksheets(“Sheet1”).Delete
Etc
Now you know the nature of objects and the rudiments of VBA syntax.
So then, what is an Excel Macro? In a nutshell… A Macro is a set of instructions that gets/modifies properties of Excel objects and executes their methods.
It’ s all about that. It is that simple! Tip
You cannot record Macros for object Events but you can use Excel object events when you write Macros from scratch.
To give an instruction in real world you use English, to give an instruction to Excel you use VBA language. And the syntax is as follows… To change an object property, use the following syntax… Objectname.PropertyNameHere
= value assigned to
property To get the value of an object property, use the following syntax…
Value gotten from property = Objectname. PropertyNameHere Now let me show you a real VBA syntax example… I assign 8.5 width to the column A…
Columns("A:A").ColumnWidth = 8.5 To execute an object method, use the following syntax…
(argument1 of the method, argument2 of the method, argumentN of the method) Objectname.MethodNameHere
Here I show you an example that executes the Select method of the range "A1:D1": 98
How To Record Excel Macros That Work Range("A1:D1").Select Where do you find the full syntax for a particular object and their members (properties, methods and events)? Go to: How to find Excel Objects ’ properties and methods? On page 91 This has been a quick and practical introduction to Excel VBA grammar. Do you still find Excel VBA as Greek? You have a hard time because you try to match the VBA syntax to English grammar. Keep in mind that languages are arbitrary assignments of meaning to symbols. Give a look at these representations of a “building” in different
languages:
Building (English)
Edificio (Spanish)
KTÍpio (Greek)
Can you find a trace of a building in the words: edificio or KTÍpio? I bet you didn’t… Human languages work because a group of people accepts a set of symbols and give them unique meaning. So if you want to fully master Excel VBA grammar, you need to accept its arbitrariness the same way you accept the conventions of English. Tip
In English there is no a unique way to convey meaning, for example: “Susan, paint the wall”, “please Susan paint the wall”, etc.
Also, in VBA language, you can convery meaning in several correct ways.
99
How To Record Excel Macros That Work
An Excel Macro is a group of instructions written in VBA language. A Macro modifies properties and executes methods of Excel objects (range, worksheet, workbook, etc.). If you want to alter the code of a Macro to get different results, change the way Excel modifies the properties of objects and the way it executes objects’ methods .
To modify an Excel Macro you need to ask these two questions:
What Excel Object property do I want to change? What Excel Object method do I want to execute?
Now you are wondering what properties and methods you can use to modify Excel programmatically? Let me ask you three more questions…
Have you changed the name of a sheet? Have you opened a book? Have you delete the content of a cell?
You have answered yes to all the above questions so…you are already familiar
with the behavior of many of Excel objects: Cells, Sheets, Columns, Charts, Pivot Tables, etc.
100
How To Record Excel Macros That Work See below an outline of some common properties and methods of common objects…
Now, you might ask…
What happens when you learn how to modify and access properties and methods? You acquire a key VBA competency.
make Macros do what you want.
You need this knowledge to
So then if properties and methods are so important, where do you start? Properties and methods are related to any given object so first identify the object you want to manipulate: 101
How To Record Excel Macros That Work
Range Worksheet Workbook, etc.
The names of the members (properties and methods) are in English and are meaningful . For example:
Borders ClearComments ActiveCell SpellingOptions MergeCells, etc.
Use these handy techniques to find properties and methods…
Use the Macro recorder as a VBA code provider. As simple as it sounds, if you want to add a line of code that write a formula in a given cell, record that action in a Macro and then copy and paste the produced code. If you want to change the font of a cell, record that action and then copy and paste that code.
I love this way of knowing the properties and methods. Avoid writing code from scratch, type CTRL + J to launch the “Auto List Members” feature. You can also launch this feature by using the Edit toolbar…
102
How To Record Excel Macros That Work See below…
Press CTRL + J while you are here
What is shown on the “Auto List Members” list? You see the available members at the current slot. See below… Methods for Range(“A1”)
Properties for Range(“A1”)
Use the up/down arrows to navigate through members and the Tab/Enter key to accept a choice. The Auto List member feature is automatically displayed after entering a point
103
How To Record Excel Macros That Work So you can choose the desired property or method…
And complete the expression…
For any given method, its arguments are provided after you type the space bar or write a parenthesis…
Tip
Identify object methods with this symbol Identify object properties with this symbol Identify object events with this symbol
104
How To Record Excel Macros That Work
For Excel 2007 users…
While you are on the VBA editor, press F1 or go to the Help menu. Then choose: Excel Object Model Reference, then pick the object and then browse the members list…
1) Pick the Excel Object Model
4) Browse the members
2) Pick the object
3) Pick members
105
How To Record Excel Macros That Work For Excel 2003 users…
While you are on the VBA editor, press F1 or go to the Help menu. Then type the name of the object on the search box…
And then choose the desired topic from the results…
106
How To Record Excel Macros That Work Or you can use the help to navigate through…
The object browser is a pane that contains all the objects and their members organized. While you are on the Visual Basic editor, press F2 to launch it. Then, choose the VBA library…
107
How To Record Excel Macros That Work After that, pick any given object on the left pane and explore its members (properties, methods and events) on the right pane…
Objects Members: properties, methods and events
You can copy the object’ s syntax from the pane and paste it on any given code window. Use right click or CTRL + C. See below…
108
How To Record Excel Macros That Work
This is a more advanced technique…
Create this Macro:
And then, to the right of the (=) sign, write the object you want to know more about, for example: a Range object…Now execute the Macro step by step this
way: 1. Place the cursor inside the “storeobject” procedure and then 2. Press F8, each press will run a line, do it until you execute the “Set myobject” line.
3. Then launch the local windows by going to View>Locals Window and explore the members. You can change the properties and see the impact on Excel. Split vertically the VBA editor and the Excel windows for better understanding
Click the object to see its members
Explore or change the properties
109
How To Record Excel Macros That Work The above methods are great to get the full syntax and help about any object property and method. If you want to go deeper in the Excel Objects universe, come with me, I will show you the…
The Excel object model is a necessary conceptual artifact to manage the objects of an application. Now, you will create a new frame of mind to understand this concept. Imagine the earth is composed of one surface and many trees…
Now imagine for a moment you are the creator of this earth. The inventory of everything on it would be this one…
110
How To Record Excel Macros That Work Now, imagine you give a command to a human to collect the fruit 1 from the trees. The human would ask you: the fruit 1 of which tree? So you need to narrow down your instruction. You would say, bring me the fruit 1 of the tree 2. Now the human is enabled to follow your instruction. To identify a fruit you must first identify the tree in the collection of trees. Only after that the fruit “Id” makes sense. In other words, the collection of fruits is
associated to a tree of the collection of trees.
Let’s talk more about collections… The earth has three collections (notice the “s” at the end, collections
are always
plural):
Trees Branches Fruits
111
How To Record Excel Macros That Work The collection of trees would be something like this one…
The collection of fruits would be something like this one…
But associated to any given tree…
112
How To Record Excel Macros That Work And each object in a given collection has its own features. See below…
And some objects don’ t belong to any collection but they also has properties and methods…
113
How To Record Excel Macros That Work An object model is the th e hierarchy hierar chy of collections and objects ob jects of a whole whol e system. Here you have a detailed object model of the earth…
114
How To Record Excel Macros That Work Here is a summarized Excel Object model…
115
How To Record Excel Macros That Work So…
In Excel to access a range object, you must specify which one from which worksheet worksheet and from which workbook. The good news is that you don ’ t need to name the t he whole hierarchy if you are working on a given tree. While you are working on Tree1, you can refer to Fruit1, Fruit2, etc. of that tree without additional identification. On Excel, you don’ t need to use the workbook/sheet qualifier qualifier all the time. t ime. For example, while the Sheet1 is active, the following code write “Hello world”
on the cell A1 of that sheet.
But, if you want to write “Hello world” on the cell A1 of the Sheet2 (while Sheet1 is active), you must write the sheet qualifier. qualifier. See below…
Now let’s explore the…
116
How To Record Excel Macros That Work
Here’ s a list of the most prominent Excel objects and their most used members (properties and methods). This list is not exhaustive (additionally, I have not included events). Here is the list of the 57 (out of 97) most used Range Properties: Name
Activate AddComment Address AutoFilter
Description1
Activates a single cell, which must b e inside the current selection. To select a range of cells, use the Select method. Adds a comment to the rang e. Returns a String value that represents the range reference in the language of the Macro.
AutoFit
Filters a list using the AutoFilter. Changes the width of the columns in the range or the height of the rows in the range to achieve the best fit.
BorderAround
Adds a border to a range and sets t he Color, LineStyle, and Weight properties for the new border. Variant.
1 Source:
Microsoft Excel Help
Borders Cells Clear ClearComments ClearContents ClearFormats
Returns a Borders collection that represents the borders of a style or a range of cells (including a r ange defined as part of a conditional format). Returns a Range object that represents the cells in the specified range. Clears the entire object. Clears all cell comments from the specified range. Clears the formulas from the range. Clears the formatting of the object.
Column
The description for this item will appear in the final release of Office 14. Returns the number of the first column in the first area in the specified range. Read-only Long.
Columns
Returns a Range object that represents the columns in the specified range.
ClearHyperlinks
Returns a Comment object that represents the comment associated
117
How To Record Excel Macros That Work with Comment Copy Count
CurrentRegion Cut Delete
End Find
FindNext Font
FormatConditions
Formula
FormulaArray
FormulaLocal
the cell in the upper-left corner of the range. Copies the ra nge to the specified range or to the Clipb oard. Returns a Long value that represents the number of objects in the collection. Returns a Range object that represents the current region. The current region is a range bounded by a ny combination of blank rows and blank columns. Read-only. Cuts the object to the Clipboard or pastes it into a specified destination. Deletes the object. Returns a Range object that represents the cell at the end of the region that contains the source range. Equivalent to pressing END+UP ARROW, END+DOWN ARROW, END+LEFT ARROW, or END+RIGHT ARROW. Readonly Range object. Finds specific information in a range. Continues a search that was begun with the Find method. Finds the next cell that matches those same conditions and returns a Range object that represents that cell. Doesn’t affect the selection or the active cell. Returns a Font object that represents the font of the specified object. Returns a FormatConditions collection that represents all the conditional formats for the specified range. Read-only. Returns or sets a Variant value that represents the object's formula in A1style notation and in t he language of the Macro. Returns or sets the array formula of a range. Returns (or can be set to) a single formula or a Visual Basic array. If the specified range doesn't contain an array formula, this property returns null. Read/write Variant. Returns or sets the formula for the object, using A1-style references in the language of the user. Read/write Variant.
Returns or sets the formula for the object, using R1C1-style notation
118
How To Record Excel Macros That Work
FormulaR1C1
FormulaR1C1Local
HorizontalAlignment
Hyperlinks
Insert
Interior Item Merge Name
NumberFormat
Offset
Parse PasteSpecial Range RemoveDuplicates
in the language of the Macro. Read/write Variant. Returns or sets the formula for the object, using R1C1-style notation in the language of the us er. Read/write Variant. Returns or sets a Variant value that represents the horizontal alignment for the specified object. Returns a Hyperlinks collection that represents the hyperlinks for the range. Inserts a cell or a range of cells into the worksheet or Macro sheet and shifts other cells away to make space. Returns a n Interior object that represents the interior of the specified object. Returns a Range object that represents a range at an offset to the specified range. Creates a merged cell from the specified Range object. Returns or sets a Variant value that represents the name of the object. Returns or sets a Variant value that r epresents the format code for the object. Returns a Range object that represents a range that’s offset from the specified range. Parses a range of data and breaks it into multiple cells. Distributes the contents of the range to fill several adjacent columns; the range can be no more than one column wide. Pastes a Range from the Clipboard into the specified range. Returns a Range object that represents a cell or a range of cells. Removes duplicate values from a range of values.
Rows
Returns a Boolean indicating characters in cells within the s pecified range. Using this method doesn’t change either the selection or the active cell. Returns the number of the first row of the first area in the range. Readonly Long. Returns a Range object that represents the rows in the specified range. Read-only Range object.
Select
Selects the object.
Replace
Row
119
How To Record Excel Macros That Work Sort
Table Text TextToColumns UnMerge
Value Value2
VerticalAlignment
Sorts a range of values. Creates a data table based on input values a nd formulas that you define on a worksheet. Returns or sets the text for the specified object. Read-only String. Parses a column of cells that contain text into several columns. Separates a merged area into individual cells. Returns or sets a Variant value that r epresents the value of the specified range. Returns or sets the cell value. Read/write Variant. Returns or sets a Variant value that r epresents the vertical alignment of the specified object.
Here are some examples:
120
How To Record Excel Macros That Work Here is the list of the 26 (out of 77) most used Range methods: Name
Activate AddComment AutoFilter Clear ClearComments ClearContents ClearFormats
ClearHyperlinks 2 Source:
Description2
Activates a single cell, which must be inside the current selection. To select a range of cells, use the Select method. Adds a comment to the rang e. Filters a list using the AutoFilter. Clears the entire object. Clears all cell comments from the specified range. Clears the formulas from the range. Clears the formatting of the object. The description for this item will appear in the final release of Office 14.
Microsoft Excel Help
Copy
Cut Delete Find
FindNext
Insert Merge
Parse PasteSpecial RemoveDuplicates
Copies the range to the specified range or to the Clipboard. Cuts the object to the Clipboard or pastes it into a specified destination. Deletes the object. Finds specific information in a range. Continues a search that was begun with the Find method. Finds the next cell that matches those same conditions and returns a Range object that represents that cell. Doesn’t affect the selection or the active cell. Inserts a cell or a range of cells into the worksheet or Macro sheet and shifts other cells away to make space. Creates a merged cell from the specified Range object. Parses a range of data and breaks it into multiple cells. Distributes the contents of the range to fill several adjacent columns; the range can be no more than one column wide. Pastes a Range from the Clipboard into the s pecified range. Removes duplicate values from a range of values. Returns a Boolean indicating characters in cells within the
121
How To Record Excel Macros That Work specified range. Using this method doesn’t change either the selection or the active cell.
Replace Select Sort
Selects the object. Sorts a range of values. Creates a data table based on input values and formulas that you define on a worksheet. Parses a column of cells that contain text into several columns. Separates a merged area into individual cells.
Table TextToColumns UnMerge
Here are some examples…
Here is the list of the 15 (out of 56) most used Worksheet properties:
Name
Desctription3
Columns
Returns a Range object that represents all the cells on t he worksheet (not just the cells that ar e currently in use. Returns a Range object that represents all the columns on the active worksheet. If the active document isn't a worksheet, the Columns property fails.
Comments
Returns a Comments collection that represents all t he comments for the specified worksheet. Read-only.
Cells
122
How To Record Excel Macros That Work
Hyperlinks
Index ListObjects Name
Names Next Previous
ProtectContents
Returns a Hyperlinks collection that represents t he hyperlinks for the worksheet. Returns a Long value that represents the index number of the object within the collection of similar objects. Returns a collection of ListObject objects in the worksheet. Read-only ListObjects collection. Returns or sets a String value representing the name of the object. Returns a Names collection that represents all the worksheetspecific names (names defined with the "WorksheetName!" prefix). Read-only Names object. Returns a Worksheet object that represents the next sheet. Returns a Worksheet object that represents the next sheet. True if the contents of the sheet are pr otected. This protects the individual cells. To turn on content protection, use the Protect method with the Contents argument set to True. Readonly Boolean.
Range
Returns a Protection object that represents the protection options of the worksheet. Returns a Range object that represents a cell or a range of cells.
Rows
Returns a Range object that represents all the rows on the specified worksheet. Read-only Range object.
Visible
Returns or sets an XlSheetVisibility value that determines whether the object is visible.
Protection
3 Source:
Microsoft Excel Help
Here are some examples:
123
How To Record Excel Macros That Work Here is the list of the 15 (out of 30) most used Worksheet methods: Name
Activate
Description4
ChartObjects Copy Delete Move Paste
Makes the current sheet the active sheet. Calculates all open workbooks, a specific worksheet in a workbook, or a specified range of cells on a worksheet, as shown in the following table. Returns an object that represents either a single embedded chart (a ChartObject object) or a collection of all the embedded charts (a ChartObjects object) on the sheet. Copies the sheet to a nother location in the workbook. Deletes the object. Moves the sheet to another location in the workbook. Pastes the contents of the Clipboard onto the sheet.
PasteSpecial
Pastes the contents of the Clipboard onto the sheet, using a specified format. Use this method to paste data from other applications or to paste data in a specific format.
Calculate
PivotTableWizard PrintOut
Returns an object that represents either a single PivotTable report (a PivotTable object) or a collection of all the PivotTable reports (a PivotTables object) on a worksheet. Read-only. Creates a new PivotTable report. This method doesn’t display the PivotTable Wizard. This method isn’t available for OLE DB data sources. Use the Add method to add a PivotTable cache, and then create a PivotTable report based on the cache. Prints the object.
PrintPreview Protect SaveAs
Shows a preview of the object as it would look when printed. Protects a worksheet so that it cannot be modified. Saves changes to the chart or worksheet in a different file.
PivotTables
4 Microsoft Excel Help
Select
Unprotect
Selects the object. Removes protection from a sheet or workbook. This method has no effect if the sheet or workbook isn't protected.
124
How To Record Excel Macros That Work
Here are some examples
125
How To Record Excel Macros That Work
Here is the list of the 14 (out of 108) most used Workbook properties: Name
ActiveChart
ActiveSheet
Charts ForceFullCalculation
FullName
Description
Returns a Chart object that represents the a ctive chart (either an embedded chart or a chart sheet). An embedded chart is considered active when it's either selected or activated. When no chart is active, this property returns Nothing. Returns an object that represents the active sheet (the sheet on top) in the active workbook or in the specified window or workbook. Returns Nothing if no sheet is active. Returns a Sheets collection that represents all the chart sheets in the specified workbook. Forces a full calculation of a workbook. Read/write. Returns the name of the object, including its path on disk, as a string. Read-only String.
Name
Returns a String indicating the name of the object, including its path on disk, as a string. Read-only. Returns a String value that represents the name of the object.
Names
Returns a Names collection that represents all the names in the specified workbook (including all
FullNameURLEncoded
worksheet-specific names). Read-only Names object. Returns a String that represents the complete path to the workbook/file that this workbook object Path respresents. True if personal information can be removed from the specified workbook. The default value is False. RemovePersonalInformation Read/write Boolean. True if no changes have been made to the specified Saved workbook since it was last saved. Read/write
126
How To Record Excel Macros That Work
Sheets
Windows
Worksheets
Boolean. Returns a Sheets collection that represents all the sheets in the specified workbook. Read-only Sheets object. Returns a Windows collection that represents all the windows in the specified workbook. Read-only Windows object. Returns a Sheets collection that represents all the worksheets in the specified workbook. Read-only Sheets object.
Here are some examples:
Here is the list of the 8 (out of 65) most used Workbook methods: Name
Description
Activate Close
Activates the first window associated with the workbook. Closes the object.
RefreshAll
Refreshes all external data ranges and PivotTable reports in the specified workbook. Removes all information of the specified type from
RemoveDocumentInformatio n the workbook.
127
How To Record Excel Macros That Work Save SaveAs
SendForReview SendMail
Saves changes to the specified workbook. Saves changes to the workbook in a different file. Sends a workbook in an e-mail message for review to the specified recipients. Sends the workbook by using the installed mail system.
128
How To Record Excel Macros That Work Here are some examples
Here is the list of the 24 (out of 206) most used Application properties: Name
Description5
ActivePrinter
Returns a Range object that represents the active cell in the active window (the window on top) or in the specified window. If the window isn't displaying a worksheet, this property fails. Read-only. Returns a Chart object that represents the active chart (either an embedded chart or a chart sh eet). An embedded chart is considered active when it's either selected or activated. When no chart is active, this property returns Nothing. Returns or sets the name of the active printer. Read/write String.
ActiveSheet
Returns a n object that represents the ac tive sheet (the sheet on top) in the active workbook or in the specified window or workbook. Returns Nothing if no sheet is active.
ActiveCell
ActiveChart
5 Source:
Microsoft Excel Help
129
How To Record Excel Macros That Work
ActiveWorkbook
Cells Charts
Columns
Range
Rows Selection
Sheets
ThisCell
ThisWorkbook
Visible Workbooks
Returns a Workbook object that represents the workbook in the active window (the window on top). Read-only. Returns Nothing if there are no windows open or if either the Info window or the Clipboard window is the active window. Returns a Range object that represents all the cells on the active worksheet. If the active document isn’t a worksheet, this property fails. Returns a Sheets collection that represents all th e chart sheets in the active workbook. Returns a Range object that represents all the columns on the active worksheet. If the active document isn't a worksheet, the Columns property fails. Returns a Range object that represents a cell or a range of cells. Returns a Range object that represents all the rows on the active worksheet. If the active document isn’t a worksheet, the Rows property fails. Read-only Range object. Returns the selected object in the a ctive window for an Application object. Returns a Sheets collection that represents all the sheets in the active workbook. Read-only Sheets object. Returns the cell in which the user-defined function is being called from as a Range object. Returns a Workbook object that represents the workbook where the current Macro code is running. Read-only. Returns or sets a Boolean value that determines whether the object is visible. Read/write. Returns a Workbooks collection that represents all the open workbooks. Read-only. For an Application object, returns a Sheets collection that represents all the worksheets in the active workbook. For a Workbook object, returns a Sheets collection that represents all the worksheets in the s pecified
130
How To Record Excel Macros That Work
ReferenceStyle
workbook. Read-only Sheets object. Returns a Window object that represents the active window (the window on top). Read-only. Returns Nothing if there are no windows open. Returns a FileDialog object representing an instance of the file dialog. Returns a String value that represents the name of the object. Returns a Names collection that represents all the names in the active workbook. Read-only Names object. Returns or sets how Microsoft Excel displays cell references and row and column headings in either A1 or R1C1 reference style. Read/write XlReferenceStyle.
Windows WorksheetFunction
Returns a Windows c ollection that represents all the windows in all the workbooks. Read-only Windows object. Returns the WorksheetFunction object. Read-only.
Worksheets
ActiveWindow
FileDialog Name
Names
Here are some examples
Here is the list of the 18 (out of 51) most used Application methods: 131
How To Record Excel Macros That Work
Name
Description
Goto
Displays the standard Save As dialog b ox and gets a file name from the user without actually saving any files. Selects any range or Visual Basic procedure in any workbook, and activates that workbook if it’s not already active.
InputBox
Displays a dialog box for user input. Returns the information entered in the dialog box.
GetSaveAsFilename
OnKey
OnTime
OnUndo Quit Repeat Undo
Wait
Calculate CalculateFull CheckSpelling
ConvertFormula DoubleClick Evaluate FindFile
GetOpenFilename
Runs a specified procedure when a particular key or key combination is pressed. Schedules a procedure to be run at a s pecified time in the future (either at a specific time of day or after a specific amount of time has passed). Sets the text of the Undo and the name of the procedure that’s run if you choose the Undo command (Edit menu) after running the procedure that sets this property. Quits Microsoft Excel. Repeats the last user-interface action. Cancels the last user-interface action. Pauses a running Macro until a specified time. Returns True if the specified time has arrived. Calculates all open workbooks, a specific worksheet in a workbook, or a specified range of cells on a worksheet, as shown in the following table. Forces a full calculation of the data in all open workbooks. Checks the spelling of a single word. Converts cell references in a formula between the A1 and R1C1 reference styles, between relative and absolute references, or both. Variant. Equivalent to double-clicking the active cell. Converts a Microsoft Excel name to an object or a value. Displays the Open dialog box. Displays the standard Open dialog box and gets a file name from the user without actually opening any files.
132
How To Record Excel Macros That Work
Here are some examples:
133
How To Record Excel Macros That Work
“The question of whether a computer can think is no more interesting than the question of whether a submarine can swim” - Edsger W. Dijkstra
E
xcel records everything you do: if you scroll, if you shift sheets to give a look, if you minimize a window, etc. All these unnecessary lines of VBA code can be easily detected and deleted without affecting the end result of a macro. Why to have redundant code that does not contribute to the end result of your Macro? So… If you find recorded Macros horrible, here you will learn what to discard and what to keep, and have the same results.
Some of the actions you can delete right away are:
Scrolling Selections of Ranges Selections of Sheets Zooming
Any other action that does not add value to the Macro bottom line 134
How To Record Excel Macros That Work The best way to be aware of how the code is produced is by splitting the Excel VBA editor window and the Excel window. Right click on the Windows task bar and click on Arrange Windows Vertical
135
How To Record Excel Macros That Work Here’s a practical example of Macro fat code… Incidental actions: resizing window
Code that matters
Incidental actions: scrolling, sheet selection, zooming, etc.
The enhanced Macro would be this one:
136
How To Record Excel Macros That Work
When I was learning Macros years ago, I thought I had got it, I said to me: “Excel records each action after you executes it on the frontend interface”…
But I felt disoriented when I performed a single keystroke and Excel wrote a paragraph (not a single line as expected). Try the following: record a Macro that only center-aligns cell A1 using the alignment tab.
You expect to see a single line of code at the module. Something like this one…
Or something similar to this one…
137
How To Record Excel Macros That Work But you get this amount…
This is the action you did on Excel
But Excel recorded this bunch of code
Why did Excel produce more VBA code than the actions I performed? First, let me explain what a “With” structure is…
The concept is very simple, instead of writing all this code: Selection.HorizontalAlignment = xlCenter Selection.WrapText = False Selection.Orientation = 0 Etc… The “With” statement allows you to perform a series of instructions for the given object (“Selection” on this case) without re -qualifying the name of the
object. For the above instructions you would write…
With Selection .HorizontalAlignment = xlCenter .WrapText = False .Orientation = 0 138
How To Record Excel Macros That Work End With When is a “With” structure produced? Excel groups VBA instructions into a “With” structure each time you change
Excel properties that come in groups, for example: the Format Cells dialog. If you change a single parameter of the Number tab, Alignment tab, Font tab, etc. Excel would produce a “With” structure with every parameter configured…
This is also the case of the Page Setup dialog…
139
How To Record Excel Macros That Work See the produced code after I just changed the Paper size to A3…
I just changed this parameter
As you can notice it, Excel set all the parameters under the Page tab. For the case above, leave only the things you are changing. For some cases, the “With” structure is not necessary so you can proceed in two different ways…
140
How To Record Excel Macros That Work
Leave only the instructions that matter and delete all the rest. See below…
Even more efficient, you can delete the with structure (no more necessary)
141
How To Record Excel Macros That Work
Take a look at this phrase: “John and Ana went to Brazil, John and Ana enjoyed the trip”
The phrase is correct but what is in excess? It is not necessary to name John and Ana again, you have pronouns which are quicker as pointers and also as space savers…
This phrase is shorter and equally correct… “John and Ana went to Brazil, they enjoyed the trip”
In Excel this redundancy must be avoided at all cost since it consumes a lot of resources and delay your Macro. Let’s see how you can overcome this…
Any extra selection statement must be deleted. For example, to write “Hello world” on the cell A1 you get an extra selection produced when you hit Enter, see below…
After hitting Enter, Excel records that action too.
Innecesary selection produced when you hit Enter
The Macro shown below consumes when your Macro makes hundreds of selections.…
142
How To Record Excel Macros That Work Don’ t delete selections that are used by your Macro. Keep the last selection statement if it will be used for next instructions. Cells don’ t need to be selected to work with them. So you can also delete selections more intelligently…
The above Macro becomes this shorter/more-efficient one…
You can add new instructions to any part of your recorded Macro. For example to auto fit columns, format a group of cells, etc. Take into account the Selection statements before and after the added code. In other words: if the added code uses Selection, it should be corresponding with the last line of code. At the same time, your added code must end with a selection compatible with the next line of code. To add code you can proceed in two different ways: write it from scratch or just record a macro and merge it to the Macro you are editing.
143
How To Record Excel Macros That Work
Turn long lines into short ones by adding a break. How do you add a break? Place the cursor at the location you want to split, hit the space bar and write the “_” character. See below…
144
How To Record Excel Macros That Work
When you provide a password to your Gmail or Yahoo account, you are asked for a private question; why is that required? You will remember that question decades later. The same way you must provide description to Macros so you remember them even in the years coming. Here are some guidelines…
Describe WHY things are being done, not HOW. Use blank lines to separate blocks of logic, to make the code more readable. Use indentation to identify blocks of code especially in repeating loops like FOR NEXT, IF ELSE END IF
A professional comment must include these elements:
Purpose (what the macro does) Assumptions (external variable, control, file, etc. accessed by the macro) Effects (each affected external variable, control, or file, and the effect it has (only if it is not obvious)) Inputs Returns
For commenting, use the Edit toolbar…
Or simply use an apostrophe („) before a line. By default, comments are turned into green. Here is an example…
145
How To Record Excel Macros That Work
“The computer is a moron” - Peter Drucker
N
ow you will get a quick-start understanding of two basic concepts: variables and branching.
A full understanding of the Excel VBA language is out of the scope of this book but here you will learn the basics to make Macros work for variable conditions. There are many ways of doing a Macro usable for the next time and for the next worksheet, I will expose the three main techniques here:
146
How To Record Excel Macros That Work
Imagine you are programming Mario to climb up a ladder; he climbs up rung 1, then 2, etc. until he reaches the top. Now, what would happen if Mario starts to climb up beginning at the rung 4? If Mario is set to start always at rung 1, he would jump back to step 1 w hen he is at rung 4. If he is on the rung 3, the same would occur. How to fix this problem?
Mario must be able to climb up to the NEXT step wherever he starts in the ladder. The effective programming of this routine should be relative to his current position.
147
How To Record Excel Macros That Work Some Macros must be able to run correctly from different starting cells. In other words you must prepare your Macro to start from a different position from where you recorded it. Hopefully, this is easily achieved by setting the reference to Relative. See how to do it on the picture below… On Excel 2007, do it this way…
148
How To Record Excel Macros That Work On Excel 2003, do it this way…
Tip
When you use relative references, Excel replaces an absolute selection like this one: Range("B3").Select…
For a relative selection like this one: ActiveCell.Select Here’s an example of a Macro that uses absolute reference…
When I run the above Macro, it will always write “Hello world” at the cell A1. Even if the cursor is at B3…
I move the cursor to the cell C7 and run the Macro, guess what?
149
How To Record Excel Macros That Work It writes “Hello world” at the cell A1.
The key design factor is to perform the action based on the actual position. The following Macro uses a relative reference…
When I run the Macro, it will always write “Hello world” at the current cell. I run the Macro at cell C3…
I run it at the cell A7…
150
How To Record Excel Macros That Work Let’ s see a more detailed example… Imagine you have a bunch of raw data in column format (on column A) and you want to lay out it as a table. The sheet contains thousands of those blocks of data. See picture below…
151
How To Record Excel Macros That Work The key strategy is to record the Macro (using relative reference) only for the first block and finish it on the starting cell of the next block…
152
How To Record Excel Macros That Work The Macro will do the same starting on the active cell A2 above To run the Macro efficiently, assign it a shortcut so you execute it again and again. Here is t he Macro…
Try the above macro by yourself. The ColumnToTable.xls file is provided as part of the download .zip file. The final result is this one…
153
How To Record Excel Macros That Work
Replace Ranges by ActiveCell or Offset
All things get better when a Macro takes a decision. There are several condition structures; here you will learn to use the “If Then Else” structure…
The expression: Range(“A1”) = “” can be replaced by any expression that returns TRUE/FALSE, for example:
Range(“A1”) = “” Range(“A1”) < 0 ActiveSheet.Name = “report” And more…
154
How To Record Excel Macros That Work You don’ t want the Macro run if the current cell is empty so copy the “ColumnToTable” Macro (above example) into the IF…THEN…ELSE structure. See below… If the current cell is empty the Macro shows a message: “No data to process”
155
How To Record Excel Macros That Work If I run the Macro from an empty cell; the message is shown…
The PC does not get bored when processes thousands of lines instead of a couple of them. To process all the blocks in the raw report above, you need to press the shortcut each time you want to execute a block. It is fun but you need to keep pressing a couple of keys for a while. This is good because you have control of the process; but sometimes you want the Macro processes thousands of records at once. I will show you how to do it without you further intervene…
You will use two repetition structures (loops)… The following code loops through every cell from row 1 to 65,536 in column 1.
156
How To Record Excel Macros That Work For the above example, if you would have 2000 blocks, you would copy and paste your “ColumnToTable” Macro code into the following loop structure.
See the end result below…
157
How To Record Excel Macros That Work
Imagine Mario must climb up the ladder until he finds a mushroom, you don ’ t know where the mushroom will be. For these cases you create an open loop. This type of loop repeats itself until the given condition occurs. For the above example, if you don ’ t know how many records you have in the sheet, you can create a loop that repeats until the last cell is empty. See below
158
How To Record Excel Macros That Work The end result would be…
Tables contain hundreds and thousands of registers, a key skill is to be able to go row by row and column by column to make any sort of computation. How to process each row/column without effort? The secret is to use the objects: Cells, Offset and collections with counters. What is a counter?
159
How To Record Excel Macros That Work Instead of using a fixed number like Cells(1,1), which always designates the cell of the row 1 and column 1 (A1); you use counters like these ones: Cells(rowcounter,columncounter) Where, rowcounter and columncounter are variables that you can manipulate by using code. In other words, the cell object doesn’ t know what row or column to point, it is up to you to define them programmatically. Here are some examples: The following Macro writes an increasing number on the cells in column 1 from row 1 to the row number 100000…
This counter goes from 1 to 100000 You can replace the “i” variable name for any other valid description: “RowCounter”, “MyCounter”, etc.
The following Macro renames each sheet with the content of its cell A1.
This counter goes from 1 to 7 (number of sheets specified by Sheets.count)
160
How To Record Excel Macros That Work This example hides all the sheets except the current one.
This example shows all the hidden sheets.
This counter goes from 1 to 7 (number of sheets specified by Sheets.count)
161
How To Record Excel Macros That Work
“To err is human--and human--and to blame it on a computer is even more so” so ” Robert Orben
P
roblems in Macros are normal; here I will show you basic tactics that can save your day.
When you check a document to find spelling mistakes you have a quite easy task since the rules are established; and things get easier because you dispose of spelling checking tools. When you use the popular Text processor Microsoft Word, you get a visual aid about where the errors are located. See below…
162
How To Record Excel Macros That Work On the Excel VBA code window you have a similar assistance when you commit a syntax mistake. The syntax errors are shown in red by default. This syntax checking feature can be changed on Tools>Options>Editor Format>Code Colors>Syntax Error Text
VBA syntax errors might mi ght be:
Misspelling of an object name, property, method, argument Lack of arguments
Lack of list separators (,), (“)
Lack of (=) sign
163
How To Record Excel Macros That Work The same way that occurs in MS Word, you are notified of such errors as soon as you finish the writing. This syntax checking feature is active by default on Tools>Options>Editor>Code Settings>Auto Syntax Check. See below…
This option is activated by default
To fix syntax errors you must write VBA instructions correctly; try these tactics when you get errors…
Find help about the right syntax for the objects and members you are writing. Press F1 Replace wrong instructions by right ones, if you can’t do it record the macro again
Use the “Auto List Members” feature to get the right syntax instead of
writing it yourself. Use CTRL + J to launch this feature Follow the instructions of the warning message (error dialog ): “Expected:
list separator or )”, “Expected: Expression”, etc. Press the “Help” button on the warning message and implement the
suggested solution
164
How To Record Excel Macros That Work Here are some examples of syntax mistakes:
Lack of the (“) at the
end of the range denomination “ A1
Here’ s another example:
Lack of the column specification. The correct syntax is: Offset (row,column)
A compilation-time error is only detected when you try to run a Macro. Typical mistakes are incomplete structures. See example below…
Lack of the “Next”
statement
165
How To Record Excel Macros That Work Here’ s another example:
Lack of the “End If”
statement
To fix compilation- time errors try these tactics…
Follow the instructions of the warning message: “For without Next”,
“Block If without End If”, etc. Press the “Help” button on the warning message and implement the
suggested solution
Write the whole VBA code structure first, for example write the “For Next” layout before you write code, things may get worse when you various “For Next”. See example below…
nest
These are the errors that occur during the execution of the Macro; let me explain it to you better with an example…
166
How To Record Excel Macros That Work The Macro below works perfectly: no syntax errors, no compilation-time errors but while running, it gives you an error. See example below… The following Macro deletes the active sheet…
But if the sheet you try to delete is the unique of the workbook, Excel will show you the message…
Other errors are:
Renaming a sheet with an existing name
Deleting a sheet that doesn’t exist
Pasting ranges in different-size array destinations
To fix run- time errors try these tactics…
Now imagine that the “Report” sheet you want to delete with a Macro is already deleted. See below…
167
How To Record Excel Macros That Work You would get this error…
But it doesn’ t matter, either way you wanted to delete the sheet so you can ignore the error message. Include the statement: On Error Resume Next. This statement ignores the line where the error was produced and continues on the next line. See below…
The error produced when you try to delete the unique sheet of a given workbook is predictable, so you must create an error trap routine to manage the situation. In the following example, the error-capture structure shows a warning message. See below…
168
How To Record Excel Macros That Work
“But they are useless. T hey can only give you answers” - Pablo Picasso, about computers
S
adly, recording Macros is not the panacea for your automation requirements. To be aware of the limitations of Macros; take into account that an excavator by itself is only able to dig and discharge soil on trucks.
The same way the excavator needs planning beyond the mere digging command (what to do while the trucks are gone, what to do if the soil gets more compact, what to do if the soil gets softer, etc.); there are Excel activities that definitely cannot be achieved using plain Macros, for example: creating forms, performing advanced analysis, etc. At this point you need to modify and create your own Macros. On one of my surveys to my subscribers, one of them gave me a great answer… In response to this question… “What are the top two questions about recording/fine-tuning I ABSOLUTELY must answer on this program?”
Excel Macros that
He replied: “Nothing with recording...that is a garbage way of doing things...write the VBA code from scratch otherwise this course is a waste of money and time. Any moron can record a Macro!”
I agree that Writing Macros from scratch is the way to go but I disagree about the Excel recorder impractical nature.
169
How To Record Excel Macros That Work Here you have a short list of the pros and cons of the Excel recorder…
Here is a list of the things Excel recorder can do:
Performs repetitive operations Creates Pivot Tables, Charts, Tables Writes formulas Provides you with VBA content otherwise you must write it Teaches you how to put Excel VBA code to work. It is a kind of on-demand VBA example generator
Here is a list of the things Excel recorder cannot do:
It does not create a form It does not create a loop It does not take a decision It does not write custom formulas It does not write advanced applications It does not get rid of fat code It does not record add-ins actions (like Solver)
My final message is: Master your recording Macros skills and you will have a great background and coder-assistant when you write Excel Macros from scratch.
Relax while the PC performs the slave-labor job. That’ s all on this eBook I hope you have enjoyed it!
And remember, you assimilate… 10% of what you hear, 40% of what you see, 90% of what you do! Record Excel Macros NOW! The next couple of minutes are enough to record a single Macro and break the inertia.
170