Beruflich Dokumente
Kultur Dokumente
Page | 2
How to Record Excel Macros that Work
www.masterofmacros.com/blog
Page | 3
How to Record Excel Macros that Work
Notice of Rights
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
Notice of Liability
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
without warranty, either express or implied. Neither the author and
excelvba.org, 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 or hardware products described herein.
Trademark Notice
Page | 4
How to Record Excel Macros that Work
Acknowledgement
You are enjoying a better Excel Macro book because I received the great advice
and suggestions of a spontaneous/welcomed editor.
Page | 5
How to Record Excel Macros that Work
Table of contents
ACKNOWLEDGEMENT ....................................................................................................................5
TABLE OF CONTENTS .....................................................................................................................6
PURPOSE OF THIS BOOK ................................................................................................................8
BRIEF TABLE OF CONTENTS ........................................................................................................ 10
1. INTRODUCTION TO EXCEL MACROS ..................................................................................... 11
2. WHAT IS AN EXCEL MACRO ................................................................................................. 14
3. HOW THE EXCEL MACRO RECORDER WORKS ...................................................................... 21
3.1. THE EXCEL RECORDER REGISTERS EVERY ACTION YOU PERFORM ON EXCEL ....................................... 21
3.2. THE EXCEL RECORDER GENERATES A VBA INSTRUCTION AFTER THE GIVEN ACTION HAS BEEN PERFORMED
ON EXCEL 23
3.3. THE EXCEL RECORDER CHANGES THE “PROPERTIES” OF EXCEL OBJECTS PROGRAMMATICALLY .............. 24
3.4. THE EXCEL RECORDER USES THE “METHODS” OF EXCEL OBJECTS PROGRAMMATICALLY....................... 27
3.5. USING “RELATIVE REFERENCE” PRODUCES DIFFERENT VBA CODE................................................... 28
4. HOW TO PLAN THE RECORDING OF AN EXCEL MACRO ......................................................... 31
4.1. GET RID OF UNSYSTEMATIC STUFF .............................................................................................. 32
4.2. BREAK THE MACRO INTO SMALLER CHUNKS ................................................................................ 34
4.3. DEFINE THE TYPE OF MACRO: SPECIFIC OR GENERALLY-APPLICABLE MACRO ...................................... 35
4.4. PLAN ONLY ONE INSTANCE ........................................................................................................ 39
4.5. FINISH THE MACRO SMARTLY.................................................................................................... 39
4.6. BACKUP THE FILE BEFORE RECORDING ........................................................................................ 40
5. HOW TO RECORD AN EXCEL MACRO.................................................................................... 41
5.1. WHERE TO PLACE THE CURSOR BEFORE RECORDING A MACRO? ...................................................... 42
5.2. WHERE TO PLACE THE CURSOR BEFORE STOPPING A MACRO? ......................................................... 42
5.3. HOW TO SET UP A MACRO ......................................................................................................... 43
5.4. HOW TO RECORD A GENERALLY-APPLICABLE MACRO ...................................................................... 46
6. LEARN MORE ABOUT HOW TO DEVELOP ADAPTABLE MACROS BY GOING TO: ............................................ 46
5.5. HOW TO RECORD A SPECIFIC MACRO .......................................................................................... 47
5.6. HOW TO START THE RECORDING................................................................................................. 47
5.7. HOW TO MODIFY THE MACRO WHILE YOU RECORD ......................................................................... 47
5.8. HOW TO STOP THE RECORDING OF A MACRO? .............................................................................. 48
5.9. HOW TO MODIFY THE CODE AFTER YOU RECORD A MACRO .............................................................. 50
5.10. HOW TO MERGE TWO OR MORE MACROS ..................................................................................... 50
6. HOW TO INTEGRATE AN EXCEL MACRO INTO YOUR WORKBOOKS......................................... 54
6.1. HOW TO ACCESS A MACRO FROM THE WORKBOOK IT WAS CREATED.................................................. 54
6.2. HOW TO ACCESS A MACRO FROM ANY WORKBOOK ........................................................................ 64
6.3. WHERE TO PUT A MACRO YOU RECEIVE FROM OTHERS ................................................................... 79
6.4. HOW TO STOP THE EXECUTION OF A MACRO ................................................................................. 79
6.5. WHAT TO DO WHEN YOUR MACRO DON’T DO WHAT YOU WANT ......................................................... 80
7. HOW EXCEL VBA WORKS .................................................................................................... 81
7.1. VBA SYNTAX .......................................................................................................................... 85
7.2. EXCEL OBJECTS’ PROPERTIES AND METHODS ............................................................................... 86
7.3. HOW TO FIND EXCEL OBJECTS’ PROPERTIES AND METHODS? .......................................................... 88
7.4. EXCEL OBJECT MODEL REVEALED .............................................................................................. 95
7.5. POPULAR EXCEL VBA OBJECTS ............................................................................................... 101
Page | 6
How to Record Excel Macros that Work
8. HOW TO MAKE A MACRO MORE EFFICIENT: SHORTER, FASTER AND SMALLER ................... 115
8.1. DELETE INCIDENTAL ACTIONS AND MISTAKES ............................................................................. 115
8.2. POLISH ALL THE “WITH” STRUCTURES ...................................................................................... 117
8.3. GET RID OF FAT CODE (UNNECESSARY SELECTIONS AND REFERENCES) ............................................ 121
8.4. ADD VBA CODE HERE AND THERE ............................................................................................ 123
8.5. MAKE THE CODE MORE READABLE ........................................................................................... 123
8.6. DOCUMENT EVERY MACRO ..................................................................................................... 124
9. HOW TO MAKE AN EXCEL MACRO ADAPTABLE FOR VARIABLE-SIZED ARRAYS ..................... 125
11.1. MAKE YOUR MACRO VALID FOR STARTING EVERYWHERE IN THE SHEET............................................ 125
11.2. HOW TO CHANGE ABSOLUTE REFERENCES INTO RELATIVE ONES ..................................................... 132
11.3. MAKE YOUR MACRO TAKE DECISIONS ....................................................................................... 132
11.4. AVOID REPETITION ................................................................................................................. 135
10. HOW TO TROUBLESHOOT AN EXCEL MACRO...................................................................... 140
12.1. FIX VBA SYNTAX ERRORS ....................................................................................................... 140
12.2. FIX COMPILATION-TIME ERRORS ............................................................................................... 143
12.3. FIX RUN-TIME ERRORS ........................................................................................................... 144
11. ABILITIES AND WEAKNESSES OF RECORDED MACROS ...................................................... 147
11.1. WHAT THE EXCEL MACRO RECORDER CAN DO ............................................................................ 148
11.2. WHAT THE EXCEL MACRO RECORDER CANNOT DO ....................................................................... 148
Page | 7
How to Record Excel Macros that Work
Welcome to my book: “How to Record Excel Macros that Work: make them
shorter, faster, and adaptable to variable-size arrays and workbooks”.
To do that, you will take full control of the recording Macro feature in Excel.
After reading and practicing the concepts on this volume you will…
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).
Get your free Excel VBA bonus “Beyond the Excel Recorder” by visiting:
www.masterofmacros.com/blog
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 enjoy the book.
I recommend you start from the chapter one: Introduction to Excel Macros on
page 11; 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 detailed table of contents at the
beginning on page 6 or the brief TOC below…
Page | 8
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
Page | 9
How to Record Excel Macros that Work
P a g e | 10
How to Record Excel Macros that Work
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 12 months…
P a g e | 11
How to Record Excel Macros that Work
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
bored.
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 12 bored 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 on the things that add value to your work and
organization: analyzing data, finding relationships, etc. (in other words,
finishing the building).
P a g e | 12
How to Record Excel Macros that Work
You can reduce your excavation time by 11 months; yes, from 12 to 1 month
by shifting the use of your hands for an excavator.
On Excel, you are able to transform your PC from manual to machine mode.
By recording a Macro.
Would you do the work with your mouse if you know the computer
can do it?
P a g e | 13
How to Record Excel Macros that Work
Author unknown
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.
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…
What kind of instructions? Actions like: changing the color of a cell, renaming a
sheet, creating a table, sorting, filtering, etc.
P a g e | 14
How to Record Excel Macros that Work
To reproduce your voice you hit the Play button on the 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…
Your instructions
are recorded here
P a g e | 15
How to Record Excel Macros that Work
The Excel 2007/2010 status bar also indicates that Excel is in recording mode…
On Excel 2003
After pressing OK, the status bar indicates that Excel is in recording mode…
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.
P a g e | 16
How to Record Excel Macros that Work
Tip
Each sub is a
Macro
A module is created
automatically
Now I will record a simple Macro (Macro1). Proceed as above to put Excel in
recording mode.
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…
P a g e | 17
How to Record Excel Macros that Work
No actions
recorded yet
P a g e | 18
How to Record Excel Macros that Work
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:
P a g e | 19
How to Record Excel Macros that Work
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 81. This way you will
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…
P a g e | 20
How to Record Excel Macros that Work
Author Unknown
T
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…
These actions might be: selecting a cell, writing a formula, scrolling, formatting
a cell, zooming, etc.
Give a look…
P a g e | 21
How to Record Excel Macros that Work
Action 1
Action 2
Action 3
Action 4
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.
Tip
P a g e | 22
How to Record Excel Macros that Work
Look at Macro1 again (below) but now pay attention to some incidental actions
I performed while recording the Macro…
Incidental action 4
Incidental action 3.
Getting back to
“Sheet1”
You need to perform an action on Excel (see left window below) so the Excel
recorder registers it. See below…
Selection first
Recording later
P a g e | 23
How to Record Excel Macros that Work
Get your free Excel VBA bonus “Beyond the Excel Recorder” by visiting:
www.masterofmacros.com/blog
Let’s see the next feature…
On the real world, your hair has properties: length, color, type; you can cut it,
change its shape, etc. Your hair behaves in specific ways: it grows, it falls, etc.
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 are read-only, you can know them but you can’t change them.
For example: your hair type: curly, straight.
Excel has properties and methods too, and you can manipulate them by using
VBA language.
You are fully aware of the way you change properties of Excel 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…
P a g e | 24
How to Record Excel Macros that Work
On the background, Excel translates that into VBA code. For now, imagine there
is one by one correspondence between everything you do on Excel and the VBA
code.
P a g e | 25
How to Record Excel Macros that Work
P a g e | 26
How to Record Excel Macros that Work
Here are some examples of how the Excel recorder uses Excel methods:
P a g e | 27
How to Record Excel Macros that Work
This action…
• Cut A1
• Select B1
• Paste
Paste
Cut
are recorded differently when you set the reference of the Macro to absolute…
P a g e | 28
How to Record Excel Macros that Work
Don’t press it
On Excel 2003, use the “Stop Recording” toolbar (displayed in recording mode)
Now if you perform the same actions above: cut, select and paste but using
relative reference, you would get a code like this one…
P a g e | 29
How to Record Excel Macros that Work
Press it
On Excel 2003, use the “Stop Recording” toolbar (displayed in recording mode)
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.
P a g e | 30
How to Record Excel Macros that Work
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.
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.
P a g e | 31
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.
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…
P a g e | 32
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.
P a g e | 33
How to Record Excel Macros that Work
Tip
Don’t try to make your Excel Macro EXCESSIVELY universal at least the
benefits will pay off the development time and effort.
Tip
You decide what is doable for you. Here are some examples:
For the case above, you can divide the Macro in two stages:
Move cells
Delete row
And…
P a g e | 34
How to Record Excel Macros that Work
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 on page 50.
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
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…
But the tables are not on the same position, see tables below…
P a g e | 35
How to Record Excel Macros that Work
The relative reference makes your Macro works based on the position
of the cursor when you recorded the Macro.
Choose the location of the cursor carefully so you can remember that
position easily in the future when running the Macro.
It is very easy…
For example: I recorded the process shown below (writing of title, date and
table headings) in a Macro with relative reference…
Even I recorded the actions starting on cell “A1”, the Macro will work on any
cell I run it, see below…
P a g e | 37
How to Record Excel Macros that Work
Tip
If you want to create the same table always at one location, whatever the
position of the cursor; you need to use absolute reference…
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.
You need to plan one block because the rest is the same. The Macro is the
processing of one block repeated thousands times.
P a g e | 39
How to Record Excel Macros that Work
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.
Tip
Record a Macro at the start of one block and finish it at the start of the
next block.
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.
P a g e | 40
How to Record Excel Macros that Work
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…
After you click the Ok button, Excel turns to recording mode. The status bar
always indicates that Excel is in recording mode, see below…
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…
P a g e | 41
How to Record Excel Macros that Work
The starting location of the cursor does not matter when you are recording
Macros using absolute reference.
On the other hand; the location of the cursor is critical when you are recording
Macros using relative reference. 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…
Place the cursor here
before recording
Always place your cursor at the right place before you launch the
Record Macro command.
Tip
Place your cursor at a border location you will easily remember later.
P a g e | 42
How to Record Excel Macros that Work
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…
What happens when you do this? Your Macro will move across blocks
of data on each run.
Tip
P a g e | 43
How to Record Excel Macros that Work
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
• CloseExcel
• DeleteFormat
• ChangeColorCell
• ChangeColorFont
Set a shortcut
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…
P a g e | 44
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…
• Storing the Macro on a workbook. This forces you to open the file to run
the Macro
P a g e | 45
How to Record Excel Macros that Work
Learn more about where to store your macros on the chapter: How to Integrate
an Excel Macro into your Workbooks on page 54
Set a description
You forget what a Macro does hours later, so provide a description about its
purpose, and specify any detail needed for the correct use.
The description can be edited later using the “Options…” button of the Macro
dialog
6. Learn more about how to develop adaptable Macros by going to: Make your
Macro valid for starting everywhere in the sheet on page 125.
Press the toolbar button: Use Relative References. The button is then
highlighted.
P a g e | 46
How to Record Excel Macros that Work
Tip
Relax please, if things go wrong, you have a backup copy to try it again.
P a g e | 47
How to Record Excel Macros that Work
See below…
If you commit mistakes or perform incidental actions, you can delete them “on
the go” and keep recording. See below…
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.
Tip
The new Macro code will be always written at the bottom of your last line
in the Sub procedure.
P a g e | 48
How to Record Excel Macros that Work
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)
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.
Or you can show the toolbar again by right clicking on the toolbar area and
activate the “Stop Recording” toolbar. See below…
P a g e | 49
How to Record Excel Macros that Work
To make even minor modifications you need at least a basic foundation of Excel
VBA knowledge. See: How Excel VBA works on page 81 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).
Get your free Excel VBA bonus “Beyond the Excel Recorder” by visiting:
www.masterofmacros.com/blog
5.10. How to merge two or more Macros
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.
Just open the module that contains the Sub procedure (Macro), place the
cursor on the desired location and paste instructions recorded in other Macros.
P a g e | 50
How to Record Excel Macros that Work
P a g e | 51
How to Record Excel Macros that Work
P a g e | 52
How to Record Excel Macros that Work
Tip
Keep aware that the Selection statements instructions of the pasted code
are corresponding to the preceding and subsequent lines.
P a g e | 53
How to Record Excel Macros that Work
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.
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 Modules (.bas).
Let’s start…
P a g e | 54
How to Record Excel Macros that Work
Set the field “Store Macro in:” to This Workbook or New Workbook. See below…
P a g e | 55
How to Record Excel Macros that Work
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.
You can also create your own modules and store Macros there. See below…
P a g e | 56
How to Record Excel Macros that Work
All the Macros contained in modules are displayed in the Macro dialog. See
below…
P a g e | 57
How to Record Excel Macros that Work
Keep in mind that those macros that contain arguments are not displayed on
the Macro dialog.
You can also store your Macros on .txt files. Later, you can copy and paste the
code into a module of any given workbook.
P a g e | 58
How to Record Excel Macros that Work
3) Import a module
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…
P a g e | 59
How to Record Excel Macros that Work
If you want to run a Macro with a mouse click, then you need to run Macros
from graphic Excel objects like: shapes, pictures, graphs. It is very easy….
Insert any of these objects and right click over the object and then click Assign
Macro. See below…
P a g e | 60
How to Record Excel Macros that Work
Tip
You can copy and paste a button to other workbook. The path of the
Macro will be kept
P a g e | 61
How to Record Excel Macros that Work
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…
P a g e | 62
How to Record Excel Macros that Work
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…
I used Sheet1 for this example; then, on the code window, choose Worksheet.
See below…
Choose object
Choose event
P a g e | 63
How to Record Excel Macros that Work
Then paste the Macro you want to be executed when Sheet1 changes…
Or you can also call the Macro that is located in some module of the current
project…
P a g e | 64
How to Record Excel Macros that Work
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…
P a g e | 65
How to Record Excel Macros that Work
This book is
automatically shown
Tip
The most you can do is to personalize the Quick Access Toolbar (QAT)…
P a g e | 66
How to Record Excel Macros that Work
Do it this way…
1. Right click over any area of the Ribbon and choose “Customize Quick
Access Toolbar…”
3. Select the Macro you want to add to the QAT and click on the Add>>
button…
P a g e | 67
How to Record Excel Macros that Work
P a g e | 68
How to Record Excel Macros that Work
Just to refresh your knowledge of the Excel Ribbon, let’s familiarize with the
components again…
Tab
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…
5. Right click over any area of the Ribbon and choose “Customize the
Ribbon…”
P a g e | 69
How to Record Excel Macros that Work
7. Right click on the new tab and choose Rename. Assign a meaningful
name
8. Right click on the default group created and choose Rename. Assign a
name. See below…
P a g e | 70
How to Record Excel Macros that Work
10. Select the Macro you want to add to the selected group and click on the
Add>> button…
11. Right click over the recently added Macro and choose Rename. Assign a
meaningful name and icon. See below…
P a g e | 71
How to Record Excel Macros that Work
Tip
You can export your Ribbon personal configuration and load it on any other
PC.
Just to refresh your knowledge of the old Excel toolbar system, let’s familiarize
with the components again…
Toolbar
Commands
1. Right click over any toolbar and choose Customize from the contextual
menu.
P a g e | 72
How to Record Excel Macros that Work
2. Click on New… in the Toolbars tab and assign a meaningful name. See
below…
P a g e | 73
How to Record Excel Macros that Work
4. Right click over the recently created button and click “Assign Macro…”.
Choose the Macro to link to the button.
P a g e | 74
How to Record Excel Macros that Work
P a g e | 75
How to Record Excel Macros that Work
Just to refresh your knowledge of the old Excel menu, let’s familiarize with the
components again…
Menu
Command
Command
1. Right click over any toolbar and choose Customize from the contextual
menu.
P a g e | 76
How to Record Excel Macros that Work
3. Click on Macros and then drag and drop a “Custom Button” to the
recently created menu.
P a g e | 77
How to Record Excel Macros that Work
4. Right click on the recently created button and then click assign Macro.
P a g e | 78
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 72.
You can stop a Macro while it is running by pressing the Esc key.
P a g e | 79
How to Record Excel Macros that Work
• Recording it again,
• Fine-tuning it or
• Writing it from scratch
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.
Get your free Excel VBA bonus “Beyond the Excel Recorder” by visiting:
www.masterofmacros.com/blog
P a g e | 80
How to Record Excel Macros that Work
Author 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:
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 the 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.
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.
P a g e | 81
How to Record Excel Macros that Work
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…
• Hair color
• Dress color
• Height
• Score
P a g e | 82
How to Record Excel Macros that Work
• Walk
• Run
• Jump
Finally, you define the consequences of the actions Mario executes (events); for
example: if an enemy kills Mario, he will die.
• Height increase (when Mario eats a mushroom). Mario has two height
Mario is ready.
If Mario eats a mushroom, then change the height of Mario to 5 pixels, or you
can use a more structured syntax:
Mario.height = 5
P a g e | 83
How to Record Excel Macros that Work
• Range("A1").ColumnWidth = 30
• Range("A1").Font.Size = 12
• Worksheets("Sheet2").Name = "Data"
• Etc
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…
Mario.Jump
• Range(“A1”).Select
• Range(“A1”).ClearComments
• Worksheets(“Sheet1”).Delete
• Etc
Now you know the nature of objects and the rudiments of VBA syntax.
In a nutshell…
P a g e | 84
How to Record Excel Macros that Work
Tip
You cannot record Macros for object Events but you can use Excel object
events when you write Macros from scratch.
Columns("A:A").ColumnWidth = 8.5
Here I show you an example that executes the Select method of the range
"A1:D1":
Range("A1:D1").Select
Where do you find the full syntax for a particular object and their members
(properties, methods and events)?
This has been a quick and practical introduction to Excel VBA grammar.
P a g e | 85
How to Record Excel Macros that Work
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)
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
Also, in VBA language, you can convery meaning in several correct ways.
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.
P a g e | 86
How to Record Excel Macros that Work
Now you are wondering what properties and methods you can use to modify
Excel programmatically?
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.
P a g e | 87
How to Record Excel Macros that Work
You acquire a key VBA competency. You need this knowledge to make
Macros do what you want.
Properties and methods are related to any given object so first identify the
object you want to manipulate:
• Range
• Worksheet
• Workbook, etc.
• Borders
• ClearComments
• ActiveCell
• SpellingOptions
• MergeCells, etc.
Record instructions in a new Macro and then copy and paste them on
the Macro you are modifying
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.
Get assistance from the “Auto List Members” command while you
write
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…
P a g e | 88
How to Record Excel Macros that Work
See below…
You see the available members at the current slot. See below…
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
For any given method, its arguments are provided after you type the space bar
or write a parenthesis…
Tip
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…
P a g e | 90
How to Record Excel Macros that Work
1) Pick the
Excel Object
Model
4) Browse the
members
2) Pick the
object
3) Pick
members
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…
P a g e | 91
How to Record Excel Macros that Work
While you are on the Visual Basic editor, press F2 to launch it. Then, choose the
VBA library…
P a g e | 92
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…
P a g e | 93
How to Record Excel Macros that Work
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:
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…
P a g e | 94
How to Record Excel Macros that Work
Trees
Surface
1 2 3
1 2
Fruits
2
1
Now imagine for a moment you are the creator of this earth. The inventory of
everything on it would be this one…
Now, imagine you give a command to a human to collect the fruit 1 from the
trees.
So you need to narrow down your instruction. You would say, bring me the fruit
1 of the tree 2.
P a g e | 95
How to Record Excel Macros that Work
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.
The earth has three collections (notice the “s” at the end, collections are always
plural):
• Trees
• Branches
• Fruits
P a g e | 96
How to Record Excel Macros that Work
And each object in a given collection has its own features. See below…
P a g e | 97
How to Record Excel Macros that Work
And some objects don’t belong to any collection but they also has properties
and methods…
P a g e | 98
How to Record Excel Macros that Work
P a g e | 99
How to Record Excel Macros that Work
So…
In Excel to access a range object, you must specify which one from which
worksheet and from which workbook.
P a g e | 100
How to Record Excel Macros that Work
The good news is that you don’t need to name the 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 all the time.
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. See below…
Range
Here is the list of the 57 (out of 97) most used Range Properties:
Name Description1
Activates a single cell, which must be inside the current selection. To
Activate select a range of cells, use the Select method.
AddComment Adds a comment to the range.
Returns a String value that represents the range reference in the
Address language of the Macro.
AutoFilter Filters a list using the AutoFilter.
Changes the width of the columns in the range or the height of the rows
AutoFit in the range to achieve the best fit.
Adds a border to a range and sets the Color, LineStyle, and Weight
BorderAround properties for the new border. Variant.
1
Source: Microsoft Excel Help
P a g e | 101
How to Record Excel Macros that Work
ClearHyperlinks 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
Column range. Read-only Long.
Returns a Range object that represents the columns in the specified
Columns range.
Returns a Comment object that represents the comment associated with
Comment the cell in the upper-left corner of the range.
Copy Copies the range to the specified range or to the Clipboard.
Returns a Long value that represents the number of objects in the
Count collection.
Returns a Range object that represents the current region. The current
region is a range bounded by any combination of blank rows and blank
CurrentRegion columns. Read-only.
Cut Cuts the object to the Clipboard or pastes it into a specified destination.
Delete 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. Read-
End only Range object.
Find 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
FindNext represents that cell. Doesn’t affect the selection or the active cell.
Font Returns a Font object that represents the font of the specified object.
Returns a FormatConditions collection that represents all the conditional
FormatConditions formats for the specified range. Read-only.
Returns or sets a Variant value that represents the object's formula in A1-
Formula style notation and in the 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
FormulaArray contain an array formula, this property returns null. Read/write Variant.
Returns or sets the formula for the object, using A1-style references in
FormulaLocal the language of the user. Read/write Variant.
P a g e | 102
How to Record Excel Macros that Work
Returns or sets the formula for the object, using R1C1-style notation in
FormulaR1C1 the language of the Macro. Read/write Variant.
Returns or sets the formula for the object, using R1C1-style notation in
FormulaR1C1Local the language of the user. Read/write Variant.
Returns or sets a Variant value that represents the horizontal alignment
HorizontalAlignment for the specified object.
Returns a Hyperlinks collection that represents the hyperlinks for the
Hyperlinks range.
Inserts a cell or a range of cells into the worksheet or Macro sheet and
Insert shifts other cells away to make space.
Returns an Interior object that represents the interior of the specified
Interior object.
Returns a Range object that represents a range at an offset to the
Item specified range.
Merge Creates a merged cell from the specified Range object.
Name Returns or sets a Variant value that represents the name of the object.
Returns or sets a Variant value that represents the format code for the
NumberFormat object.
Returns a Range object that represents a range that’s offset from the
Offset 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
Parse no more than one column wide.
PasteSpecial Pastes a Range from the Clipboard into the specified range.
Range Returns a Range object that represents a cell or a range of cells.
RemoveDuplicates Removes duplicate values from a range of values.
Returns a Boolean indicating characters in cells within the specified
range. Using this method doesn’t change either the selection or the
Replace active cell.
Returns the number of the first row of the first area in the range. Read-
Row only Long.
Returns a Range object that represents the rows in the specified range.
Rows Read-only Range object.
Select Selects the object.
Sort Sorts a range of values.
Creates a data table based on input values and formulas that you define
Table on a worksheet.
Text Returns or sets the text for the specified object. Read-only String.
TextToColumns Parses a column of cells that contain text into several columns.
UnMerge Separates a merged area into individual cells.
Returns or sets a Variant value that represents the value of the specified
Value range.
Value2 Returns or sets the cell value. Read/write Variant.
Returns or sets a Variant value that represents the vertical alignment of
VerticalAlignment the specified object.
P a g e | 103
How to Record Excel Macros that Work
Here is the list of the 26 (out of 77) most used Range methods:
Name Description2
Activates a single cell, which must be inside the current
Activate selection. To select a range of cells, use the Select method.
AddComment Adds a comment to the range.
AutoFilter Filters a list using the AutoFilter.
Clear Clears the entire object.
ClearComments Clears all cell comments from the specified range.
ClearContents Clears the formulas from the range.
ClearFormats Clears the formatting of the object.
The description for this item will appear in the final release
ClearHyperlinks of Office 14.
2
Source: Microsoft Excel Help
P a g e | 104
How to Record Excel Macros that Work
P a g e | 105
How to Record Excel Macros that Work
Worksheet
Here is the list of the 15 (out of 56) most used Worksheet properties:
Name Desctription 3
Returns a Range object that represents all the cells on the
Cells worksheet (not just the cells that are 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 Columns property fails.
Returns a Comments collection that represents all the
Comments comments for the specified worksheet. Read-only.
Returns a Hyperlinks collection that represents the hyperlinks
Hyperlinks for the worksheet.
Returns a Long value that represents the index number of the
Index object within the collection of similar objects.
Returns a collection of ListObject objects in the worksheet.
ListObjects Read-only ListObjects collection.
Returns or sets a String value representing the name of the
Name object.
Returns a Names collection that represents all the worksheet-
specific names (names defined with the "WorksheetName!"
Names prefix). Read-only Names object.
Next Returns a Worksheet object that represents the next sheet.
Previous Returns a Worksheet object that represents the next sheet.
True if the contents of the sheet are protected. This protects
the individual cells. To turn on content protection, use the
Protect method with the Contents argument set to True. Read-
ProtectContents only Boolean.
Returns a Protection object that represents the protection
Protection options of the worksheet.
Range Returns a Range object that represents a cell or a range of cells.
Returns a Range object that represents all the rows on the
Rows specified worksheet. Read-only Range object.
Returns or sets an XlSheetVisibility value that determines
Visible whether the object is visible.
3
Source: Microsoft Excel Help
P a g e | 106
How to Record Excel Macros that Work
Here is the list of the 15 (out of 30) most used Worksheet methods:
Name Description4
Activate 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
Calculate 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
ChartObjects (a ChartObjects object) on the sheet.
Copy Copies the sheet to another location in the workbook.
Delete Deletes the object.
Move Moves the sheet to another location in the workbook.
Paste Pastes the contents of the Clipboard onto the sheet.
Pastes the contents of the Clipboard onto the sheet, using a
specified format. Use this method to paste data from other
PasteSpecial applications or to paste data in a specific format.
Returns an object that represents either a single PivotTable
report (a PivotTable object) or a collection of all the PivotTable
PivotTables 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
PivotTableWizard create a PivotTable report based on the cache.
PrintOut Prints the object.
PrintPreview Shows a preview of the object as it would look when printed.
Protect Protects a worksheet so that it cannot be modified.
SaveAs Saves changes to the chart or worksheet in a different file.
4
Microsoft Excel Help
P a g e | 107
How to Record Excel Macros that Work
Workbook
Here is the list of the 14 (out of 108) most used Workbook properties:
Name Description
Returns a Chart object that represents the active 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
ActiveChart 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
ActiveSheet active.
Returns a Sheets collection that represents all the chart
Charts sheets in the specified workbook.
ForceFullCalculation Forces a full calculation of a workbook. Read/write.
Returns the name of the object, including its path on
FullName disk, as a string. Read-only String.
Returns a String indicating the name of the object,
FullNameURLEncoded including its path on disk, as a string. Read-only.
Returns a String value that represents the name of the
Name object.
Returns a Names collection that represents all the
Names names in the specified workbook (including all
P a g e | 108
How to Record Excel Macros that Work
Here is the list of the 8 (out of 65) most used Workbook methods:
Name Description
Activates the first window associated with the
Activate workbook.
Close Closes the object.
Refreshes all external data ranges and PivotTable
RefreshAll reports in the specified workbook.
P a g e | 109
How to Record Excel Macros that Work
Application
Here is the list of the 24 (out of 206) most used Application properties:
Name Description5
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
ActiveCell property fails. Read-only.
Returns a Chart object that represents the active 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
ActiveChart Nothing.
Returns or sets the name of the active printer. Read/write
ActivePrinter String.
Returns an object that represents the active sheet (the
sheet on top) in the active workbook or in the specified
ActiveSheet window or workbook. Returns Nothing if no sheet is active.
5
Source: Microsoft Excel Help
P a g e | 110
How to Record Excel Macros that Work
P a g e | 111
How to Record Excel Macros that Work
Here is the list of the 18 (out of 51) most used Application methods:
Name Description
Displays the standard Save As dialog box and gets a file name
GetSaveAsFilename from the user without actually saving any files.
Selects any range or Visual Basic procedure in any workbook, and
Goto activates that workbook if it’s not already active.
Displays a dialog box for user input. Returns the information
InputBox entered in the dialog box.
Runs a specified procedure when a particular key or key
OnKey combination is pressed.
Schedules a procedure to be run at a specified time in the future
(either at a specific time of day or after a specific amount of time
OnTime 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
OnUndo the procedure that sets this property.
Quit Quits Microsoft Excel.
Repeat Repeats the last user-interface action.
Undo Cancels the last user-interface action.
Pauses a running Macro until a specified time. Returns True if the
Wait specified time has arrived.
P a g e | 112
How to Record Excel Macros that Work
P a g e | 113
How to Record Excel Macros that Work
P a g e | 114
How to Record Excel Macros that Work
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.
• Scrolling
• Selections of Ranges
• Selections of Sheets
• Zooming
• Any other action that does not add value to the Macro bottom line
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
P a g e | 115
How to Record Excel Macros that Work
Incidental actions:
resizing window
Incidental actions:
scrolling, sheet
selection, zooming,
etc.
P a g e | 116
How to Record Excel Macros that Work
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…
P a g e | 117
How to Record Excel Macros that Work
Why did Excel produce more VBA code than the actions I performed?
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.
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
End With
Excel groups VBA instructions into a “With” structure each time you change
Excel properties that come in groups, for example: the Format Cells dialog.
P a g e | 118
How to Record Excel Macros that Work
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…
See the produced code after I just changed the Paper size to A3…
P a g e | 119
How to Record Excel Macros that Work
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…
P a g e | 120
How to Record Excel Macros that Work
“John and Ana went to Brazil, John and Ana enjoyed the trip”
It is not necessary to name John and Ana again, you have pronouns which are
quicker as pointers and also as space savers…
P a g e | 121
How to Record Excel Macros that Work
In Excel this redundancy must be avoided at all cost since it consumes a lot of
resources and delay your Macro.
Innecesary selection
produced when you hit
Enter
The Macro shown below consumes fewer resources. This is noticeable when
your Macro makes hundreds of selections.…
Don’t delete selections that are used by your Macro. Keep the last selection
statement if it will be used for next instructions.
P a g e | 122
How to Record Excel Macros that Work
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.
Place the cursor at the location you want to split, hit the space bar and write
the “_” character. See below…
P a g e | 123
How to Record Excel Macros that Work
The same way you must provide description to Macros so you remember them
even in the years coming.
Or simply use an apostrophe (‘) before a line. By default, comments are turned
into green. Here is an example…
P a g e | 124
How to Record Excel Macros that Work
Peter Drucker
N
ow you will get a quick-start understanding of two basic concepts:
variables and branching.
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:
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 when he
is at rung 4. If he is on the rung 3, the same would occur.
P a g e | 125
How to Record Excel Macros that Work
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.
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…
P a g e | 126
How to Record Excel Macros that Work
P a g e | 127
How to Record Excel Macros that Work
Tip
When you use relative references, Excel replaces an absolute selection like
this one: Range("B3").Select…
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?
P a g e | 128
How to Record Excel Macros that Work
The key design factor is to perform the action based on the actual position.
When I run the Macro, it will always write “Hello world” at the current cell.
P a g e | 129
How to Record Excel Macros that Work
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…
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…
P a g e | 130
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.
P a g e | 131
How to Record Excel Macros that Work
Try the above macro by yourself. The ColumnToTable.xls file is provided as part
of the download .zip file.
• Range(“A1”) = “”
• Range(“A1”) < 0
• ActiveSheet.Name = “report”
• And more…
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”
P a g e | 133
How to Record Excel Macros that Work
Instructions if
A1 is empty
Instructions
(ColumnToTable)
if A1 is not empty
P a g e | 134
How to Record Excel Macros that Work
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…
For the above example, if you would have 2000 blocks, you would copy and
paste your “ColumnToTable” Macro code into the following loop structure.
Some code to
repeat
See the end result below…
P a g e | 135
How to Record Excel Macros that Work
This code
will be
repeated
2000 times
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
Some code to
repeat
P a g e | 136
How to Record Excel Macros that Work
Use counters
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.
The secret is to use the objects: Cells, Offset and collections with counters.
What is a counter?
Cells(1,1)
P a g e | 137
How to Record Excel Macros that Work
that 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.
The following Macro writes an increasing number on the cells in column 1 from
row 1 to the row number 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.
P a g e | 138
How to Record Excel Macros that Work
This example hides all the sheets except the current one.
P a g e | 139
How to Record Excel Macros that Work
Robert Orben
Problems in Macros are normal; here I will show you basic tactics that can save
your day.
When you use the popular Text processor Microsoft Word, you get a visual aid
about where the errors are located. See below…
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.
P a g e | 140
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…
P a g e | 141
How to Record Excel Macros that Work
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
P a g e | 142
How to Record Excel Macros that Work
P a g e | 143
How to Record Excel Macros that Work
But if the sheet you try to delete is the unique of the workbook, Excel will show
you the message…
P a g e | 144
How to Record Excel Macros that Work
Ignore an error
Now imagine that the “Report” sheet you want to delete with a Macro is already
deleted. See below…
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…
P a g e | 145
How to Record Excel Macros that Work
P a g e | 146
How to Record Excel Macros that Work
S
adly, recording Macros is not the panacea for your automation
requirements.
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.
“What are the top two questions about recording/fine-tuning Excel Macros that
I ABSOLUTELY must answer on this program?”
I agree that Writing Macros from scratch is the way to go but I disagree about
the Excel recorder impractical nature.
Here you have a short list of the pros and cons of the Excel recorder…
P a g e | 147
How to Record Excel Macros that Work
Master your recording Macros skills and you will have a great
background and coder-assistant when you write Excel Macros from
scratch.
The next couple of minutes are enough to record a single Macro and break the
inertia.
P a g e | 148
How to Record Excel Macros that Work
Making mistakes will only make you better and better (if you don’t
give up before)
I am John Franco
P a g e | 149