Professional Documents
Culture Documents
How To Record Excel Macros That Work Make your recorded macros
shorter, faster and adaptable to variable-size arrays and workbooks
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 publisher.
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 without warranty, either express 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 or 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 trademark.
Excel is a registered trademark 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.
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
3.4. THE EXCEL RECORDER USES THE METHODS OF EXCEL OBJECTS PROGRAMMATICALLY ...................................... 30
3.5.
USING RELATIVE REFERENCE PRODUCES DIFFERENT VBA CODE .......................................................... 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 relative references ...................................................................................................................... 39
Use absolute reference ..................................................................................................................... 43
4.4. PLAN ONLY ONE INSTANCE ..................................................................................................................... 44
4.5. FINISH THE MACRO SMARTLY ................................................................................................................. 44
4.6. BACKUP THE FILE BEFORE RECORDING....................................................................................................... 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
Assign a shortcut ............................................................................................................................... 50
Define where to store the Macro ...................................................................................................... 52
Set a description ................................................................................................................................ 52
5.4. HOW TO RECORD A DYNAMIC MACRO ...................................................................................................... 52
5.5. HOW TO RECORD A STATIC MACRO.......................................................................................................... 53
5.6. HOW TO START THE RECORDING.............................................................................................................. 54
5.7. HOW TO MODIFY THE MACRO WHILE YOU RECORD ..................................................................................... 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 MACRO INTO YOUR WORKBOOKS.................................................... 61
6.1. HOW TO ACCESS A MACRO FROM THE WORKBOOK IT WAS CREATED............................................................... 62
Access a Macro from the Macro Dialog ............................................................................................ 68
Dear John,
This is the book I was waiting for! Looking forward to your online
Excel School on VBA
TNX!
Fondest Regards,
Dick
PS: Im verry glad to see you back online again
Dick
Just wanted to say thanks for putting out such wonderful, helpful, easyto-understand tips and instructions. Youre one of the best 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
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
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.
10
Hi dear Excel user, welcome to my book: How to Record Excel Macros that
Work - Make your recorded macros shorter, faster and adaptable to variablesize 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
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
All my experience with recording Excel Macros is here, nothing is left behind. I
hope you enjoy the book.
John Franco
12
Computing is not about computers any more. It is about living Nicholas Negroponte
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
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
15
All programmers are playwrights and all computers are lousy actors
Author unknown
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
16
Your
instructions
are recorded
here
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
18
Now I will record a simple Macro (Macro1). Proceed as above to put Excel in
recording mode.
Want to see whats 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
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. Dont worry; you will learn the Excel VBA
basics on the chapter: How Excel VBA works on page 84. This way you will
20
21
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 lets start
22
23
Incidental action 1.
Maximizing the window
Incidental action 4
Incidental
action 3.
Getting back
to Sheet1
24
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
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 can cut it,
change its shape, etc. Your hair behaves in specific ways: it grows, it falls, etc.
25
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 cant change them.
For example: your hair type: curly, straight.
Lets summarize the features of your hair
26
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.
27
28
29
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
30
These actions
Cut A1
Select B1
Paste
are recorded differently when you set the reference of the Macro to absolute
31
Dont press it
On Excel 2003, use the Stop Recording toolbar (displayed in recording mode)
32
Range(A1)
Press it
On Excel 2003, use the Stop Recording toolbar (displayed in recording mode)
33
34
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.
Heres an example: not many users know how to transpose a column into a row
and vice versa.
35
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
36
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:
Tip
Dont 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:
For the case above, you can divide the Macro in two stages:
37
Move cells
Delete row
And
2. Creating the table headings
Write table headers
Dont 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 doesnt 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
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.
Heres 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
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
Macro
For example: I recorded the process shown below (writing the title, date and
table headings) in a Macro with relative references
41
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
Use this option when your Macros will be applied on the same location all the
time. See below
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.
43
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.
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. Dont 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 dont want to
use loops or have not learned to use them yet.
44
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
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
This is just the beginning of the recording process. Lets go into details now
46
47
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
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
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
51
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, so provide a description about its
purpose, and specify any detail needed for the correct use.
This is more important if the Macro will be used by other users.
The description can be edited later using the Options button of the Macro
dialog
As explained above, this must be done when you want the Macro runs on
different positions from where it was recorded and for different array sizes.
Heres the step by step procedure
1. Put your cursor at the starting position of your raw data (Don't
52
Learn more about how to develop adaptable Macros by going to: Make your
Macro valid for starting everywhere in the sheet.
As you learned before, these types of macros perform operations on the same
location each next time (using absolute reference).
Heres the step by step procedure
1. Launch the Record Macro dialog (not necessary to put your cursor at
any given position in your spreadsheet; in other words, you can
include earlier mouse movements in your Macro
2. Assign a shortcut to your Macro (so you can repeat 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 you want to be repeated in your macro
6. Stop the Macro when all the keystrokes are recorded
53
Relax please, if things go wrong, you have a backup copy to try it again.
54
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
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)
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 dont know how to stop the
recording of a Macro; you can do it by going to Tools>Macro>Stop Recording.
56
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
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.
58
59
60
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 the same excel
file as VBA modules. You can export modules as .bas files.
Lets start
61
Every workbook has its own modules where Macros can be stored. All these
Macros can be accessed from the given parent workbook. See below
62
63
All the Macros contained in modules are displayed in the Macro dialog. See
below
64
65
66
Once your Macro is on a module of a given workbook you can call it using
several methods
67
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
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: 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
69
Tip
You can copy and paste a button to other workbook. The path of the Macro will
be kept
70
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
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
Then paste the Macro you want to be executed when Sheet1 changes
73
74
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
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
77
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
3. Select the Macro you want to add to the QAT and click on the
Add>> button
78
79
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, lets 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
4. Right click on the default group created and choose Rename. Assign
a name. See below
81
6. Select the Macro you want to add to the selected group and click on the
Add>> button
82
Tip
You can export your Ribbon personal configuration and load it on any other PC.
83
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, lets familiarize
with the components again
Toolbar
Commands
84
85
86
87
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, lets familiarize with the
components again
Menu
Command
Command
89
90
91
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 dont 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
If a Macro doesnt do what you want, you have three lines of actions:
Recording it again,
Fine-tuning it or
Writing it from scratch
92
93
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
magine you are going to spend your next vacation on Japan, you dont
know Japanese but you equip with a 3-phrase vocabulary:
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
Lets 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
Hair color
Dress color
Height
Score
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.
Lets imagine you write the instructions in plain English
96
Range("A1").ColumnWidth = 30
Range("A1").Font.Size = 12
Worksheets("Sheet2").Name = "Data"
Etc
Range(A1).Select
Range(A1).ClearComments
97
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.
Its 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.
Building (English)
Edificio (Spanish)
KTpio (Greek)
99
Now you are wondering what properties and methods you can use to modify
Excel programmatically?
Let me ask you three more questions
You have answered yes to all the above questions soyou are already familiar
with the behavior of many of Excel objects: Cells, Sheets, Columns, Charts,
Pivot Tables, etc.
100
What happens when you learn how to modify and access properties and
methods?
You acquire a key VBA competency. You need this knowledge to
make Macros do what you want.
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
Range
Worksheet
Workbook, etc.
Borders
ClearComments
ActiveCell
SpellingOptions
MergeCells, etc.
102
Press CTRL + J
while you
are here
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
For any given method, its arguments are provided after you type the space bar
or write a parenthesis
Tip
104
1) Pick the
Excel Object
Model
4) Browse the
members
2) Pick the
object
3) Pick members
105
106
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
Objects
Members:
properties,
methods and
events
You can copy the objects syntax from the pane and paste it on any given code
window. Use right click or CTRL + C. See below
108
And then, to the right of the (=) sign, write the object you want to know more
about, for example: a Range objectNow 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
109
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
Trees
Branches
Fruits
111
112
And some objects dont belong to any collection but they also has properties
and methods
113
114
115
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
116
Heres 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
AutoFit
BorderAround
Description1
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 range.
Returns a String value that represents the range reference in the
language of the Macro.
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.
Adds a border to a range and sets the Color, LineStyle, and Weight
properties for the new border. Variant.
Borders
Cells
Clear
ClearComments
ClearContents
ClearFormats
ClearHyperlinks
Column
Columns
Comment
Copy
Count
CurrentRegion
Cut
Delete
End
Find
FindNext
Font
FormatConditions
Formula
FormulaArray
FormulaLocal
with
the cell in the upper-left corner of the range.
Copies the range to the specified range or to the Clipboard.
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 any 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. Doesnt 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 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
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
FormulaR1C1
FormulaR1C1Local
HorizontalAlignment
Hyperlinks
Insert
Interior
Item
Merge
Name
NumberFormat
Offset
Parse
PasteSpecial
Range
RemoveDuplicates
Replace
Row
Rows
Select
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 user. 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 an 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 represents the format code for
the
object.
Returns a Range object that represents a range thats 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.
Returns a Boolean indicating characters in cells within the specified
range. Using this method doesnt 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.
Selects the object.
119
Table
Text
TextToColumns
UnMerge
Value
Value2
VerticalAlignment
120
Activate
AddComment
AutoFilter
Clear
ClearComments
ClearContents
ClearFormats
ClearHyperlinks
2
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 range.
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.
Copy
Cut
Delete
Find
FindNext
Insert
Merge
Parse
PasteSpecial
RemoveDuplicates
Replace
Select
Sort
Table
TextToColumns
UnMerge
Here are some examples
Here is the list of the 15 (out of 56) most used Worksheet properties:
Name
Cells
Columns
Comments
Desctription3
Returns a Range object that represents all the cells on the
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 property fails.
Returns a Comments collection that represents all the
comments for the specified worksheet. Read-only.
122
Hyperlinks
Index
ListObjects
Name
Names
Next
Previous
ProtectContents
Protection
Range
Rows
Visible
3
123
ChartObjects
Copy
Delete
Move
Paste
Description4
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 another 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
Name
Activate
Calculate
PivotTables
PivotTableWizard
PrintOut
PrintPreview
Protect
SaveAs
Select
Unprotect
125
Here is the list of the 14 (out of 108) most used Workbook properties:
Name
ActiveChart
ActiveSheet
Charts
ForceFullCalculation
FullName
FullNameURLEncoded
Name
Names
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
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.
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.
Returns a Names collection that represents all the
names in the specified workbook (including all
worksheet-specific names). Read-only Names
object.
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 is the list of the 8 (out of 65) most used Workbook methods:
Name
Activate
Close
RefreshAll
Description
Activates the first window associated with the
workbook.
Closes the object.
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
128
Here is the list of the 24 (out of 206) most used Application properties:
ActivePrinter
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
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
Nothing.
Returns or sets the name of the active printer.
Read/write
String.
ActiveSheet
Name
ActiveCell
ActiveChart
129
ActiveWorkbook
Cells
Charts
Columns
Range
Rows
Selection
Sheets
ThisCell
ThisWorkbook
Visible
Workbooks
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
Worksheets
ActiveWindow
FileDialog
Name
Names
Here is the list of the 18 (out of 51) most used Application methods:
131
Name
GetSaveAsFilename
Goto
InputBox
OnKey
OnTime
OnUndo
Quit
Repeat
Undo
Wait
Calculate
CalculateFull
CheckSpelling
ConvertFormula
DoubleClick
Evaluate
FindFile
GetOpenFilename
Description
Displays the standard Save As dialog box 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 its not already active.
Displays a dialog box for user input. Returns the information
entered in the dialog box.
Runs a specified procedure when a particular key or key
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
has passed).
Sets the text of the Undo and the name of the procedure
thats
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
133
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
134
135
Incidental actions:
resizing window
Incidental actions:
scrolling, sheet
selection, zooming,
etc.
136
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
137
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
139
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
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
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
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
144
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
145
146
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
148
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
Heres 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
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
150
151
152
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
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
Range(A1) =
Range(A1) < 0
ActiveSheet.Name = report
And more
154
155
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
157
Imagine Mario must climb up the ladder until he finds a mushroom, you dont
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 dont 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
159
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.
160
161
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
163
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 cant 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
A1
A compilation-time error is only detected when you try to run a Macro. Typical
mistakes are incomplete structures. See example below
165
These are the errors that occur during the execution of the Macro; let me
explain it to you better with an example
166
But if the sheet you try to delete is the unique of the workbook, Excel will show
you the message
Now imagine that the Report sheet you want to delete with a Macro is already
deleted. See below
167
But it doesnt 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
But they are useless. They can only give you answers - Pablo
Picasso, about computers
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 Excel Macros that
I ABSOLUTELY must answer on this program?
He replied: Nothing with recording...that is a garbage way of doing
169
It
It
It
It
It
It
It
does
does
does
does
does
does
does
not
not
not
not
not
not
not
create a form
create a loop
take a decision
write custom formulas
write advanced applications
get rid of fat code
record add-ins actions (like Solver)
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
171