record excel macros that work

Upload: anonymous-ylppdpw

Post on 07-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Record Excel Macros That Work

    1/152

  • 8/3/2019 Record Excel Macros That Work

    2/152

    How to Record Excel Macros that Work

    P a g e | 2

    Testimonials

    Just wanted to say thanks for putting out such wonderful, helpful, easy-to-

    understand tips and instructions. Youre one of the best resources for

    Excel on the web!I look forward to learning about VBA!

    Will

    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 onlineagain

    Dick

  • 8/3/2019 Record Excel Macros That Work

    3/152

    How to Record Excel Macros that Work

    P a g e | 3

    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 andI

    believe that I can do a lot better with your book.

    Thanks

    Hasan

    Its a wonderful book, helps me to augment my knowledge,

    tx john !

    Dave

    Hi John,

    I downloaded your ebook 'How to record excel macros that work' last night

    andfound the infornmation great. The organisation where I do the course

    through has been very little help in this area and only has information onExcel 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

  • 8/3/2019 Record Excel Macros That Work

    4/152

    How to Record Excel Macros that Work

    P a g e | 4

    How to Record Excel Macros that Work

    By John Franco

    IMPORTANT: As an added bonus for downloading this book, you have

    also access to more free Excel VBA training.

    To access your bonuses go to:

    www.masterofmacros.com/blog

    http://www.masterofmacros.com/bloghttp://www.masterofmacros.com/blog
  • 8/3/2019 Record Excel Macros That Work

    5/152

    How to Record Excel Macros that Work

    P a g e | 5

    How to Record Excel Macros that WorkVersion 1.1 Feb 26, 2011

    John Franco 2010 by excelvba.org

    Notice of Rights

    All rights reserved. No part of this book may be reproduced, stored in aretrieval system, or transmitted in any form or by any means, without the priorwritten permission of the publisher.

    If you want to sell this book, use it for commercial purposes, distribute it in bulkquantities 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 theinformation herein. However, the information contained in this book is soldwithout warranty, either express or implied. Neither the author andexcelvba.org, nor its dealers or distributors, will be held liable for any damagesto be caused either directly or indirectly by the instructions contained in thisbook, or by the software or hardware products described herein.

    Trademark Notice

    Rather than indicating every occurrence of a trademarked name as such, thisbook uses the names only in an editorial fashion and to the benefit of thetrademark owner with no intention of infringement of the trademark.

  • 8/3/2019 Record Excel Macros That Work

    6/152

    How to Record Excel Macros that Work

    P a g e | 6

    Acknowledgement

    You are enjoying a better Excel Macro book because I received the great adviceand suggestions of a spontaneous/welcomed editor.

    Thank you Ron S.Contact him here: [email protected]

  • 8/3/2019 Record Excel Macros That Work

    7/152

    How to Record Excel Macros that Work

    P a g e | 7

    Table of contents

    TESTIMONIAL ...........................................................................................................................2ACKNOWLEDGEMENT .................................................................................................................6TABLE OF CONTENTS ..................................................................................................................7PURPOSE OF THIS BOOK .............................................................................................................9BRIEF TABLE OF CONTENTS ..................................................................................................... 111. INTRODUCTION TO EXCEL MACROS ....... ....... ....... ........ ....... ....... ........ ....... ....... ....... ........ .. 122. WHAT IS AN EXCEL MACRO .............................................................................................. 153. HOW THE EXCEL MACRO RECORDER WORKS ....... ........ ....... ....... ....... ........ ....... ....... ........ .. 22

    3.1. THE EXCEL RECORDER REGISTERS EVERY ACTION YOU PERFORM ON EXCEL....................................... 22

    3.2. THE EXCEL RECORDER GENERATES A VBA INSTRUCTION AFTER THE GIVEN ACTION HAS BEEN PERFORMED

    ON EXCEL 24

    3.3. THE EXCEL RECORDER CHANGES THE PROPERTIES OF EXCEL OBJECTS PROGRAMMATICALLY.............. 253.4. THE EXCEL RECORDER USES THE METHODS OF EXCEL OBJECTS PROGRAMMATICALLY...................... 28

    3.5. USING RELATIVE REFERENCE PRODUCES DIFFERENT VBA CODE.................................................. 29

    4. HOW TO PLAN THE RECORDING OF AN EXCEL MACRO........................................................ 324.1. GET RID OF UNSYSTEMATIC STUFF ............................................................................................ 33

    4.2. BREAK THE MACRO INTO SMALLER CHUNKS ............................................................................... 35

    4.3. DEFINE THE TYPE OF MACRO: SPECIFIC OR GENERALLY-APPLICABLE MACRO...................................... 36

    4.4. PLAN ONLY ONE INSTANCE ...................................................................................................... 40

    4.5. FINISH THE MACRO SMARTLY.................................................................................................. 40

    4.6. BACKUP THE FILE BEFORE RECORDING ...................................................................................... 41

    5. HOW TO RECORD AN EXCEL MACRO ....... ....... ........ ....... ....... ....... ........ ....... ....... ........ ....... . 425.1. WHERE TO PLACE THE CURSOR BEFORE RECORDING A MACRO? ..................................................... 43

    5.2. WHERE TO PLACE THE CURSOR BEFORE STOPPING A MACRO? ........................................................ 44

    5.3. HOW TO SET UP A MACRO ....................................................................................................... 44

    5.4. HOW TO RECORD A DYNAMIC (GENERALLY-APPLICABLE)MACRO ..................................................... 48

    5.5. HOW TO RECORD A SPECIFIC MACRO......................................................................................... 49

    5.6. HOW TO START THE RECORDING ............................................................................................... 50

    5.7. HOW TO MODIFY THE MACRO WHILE YOU RECORD........................................................................ 50

    5.8. HOW TO STOP THE RECORDING OF A MACRO? ............................................................................. 51

    5.9. HOW TO MODIFY THE CODE AFTER YOU RECORD A MACRO ............................................................. 53

    5.10. HOW TO MERGE TWO OR MORE MACROS ................................................................................... 53

    6. HOW TO INTEGRATE AN EXCEL MACRO INTO YOUR WORKBOOKS .... .... ... .... .... ... .... .... ... .... .. 576.1. HOW TO ACCESS A MACRO FROM THE WORKBOOK IT WAS CREATED ................................................. 57

    6.2. HOW TO ACCESS A MACRO FROM ANY WORKBOOK ....................................................................... 67

    6.3. WHERE TO PUT A MACRO YOU RECEIVE FROM OTHERS .................................................................. 82

    6.4. HOW TO STOP THE EXECUTION OF A MACRO ................................................................................ 82

    6.5. WHAT TO DO WHEN YOUR MACRO DONT DO WHAT YOU WANT ........................................................ 83

    7. HOW EXCEL VBA WORKS ................................................................................................. 847.1. VBA SYNTAX ........................................................................................................................ 88

    7.2. EXCEL OBJECTS PROPERTIES AND METHODS .............................................................................. 89

    7.3. HOW TO FIND EXCEL OBJECTS

    PROPERTIES AND METHODS? ......................................................... 917.4. EXCEL OBJECT MODEL REVEALED............................................................................................. 98

    7.5. POPULAR EXCEL VBAOBJECTS.............................................................................................. 104

  • 8/3/2019 Record Excel Macros That Work

    8/152

    How to Record Excel Macros that Work

    P a g e | 8

    8. HOW TO MAKE A MACRO MORE EFFICIENT: SHORTER, FASTER AND SMALLER .................. 1188.1. DELETE INCIDENTAL ACTIONS AND MISTAKES ............................................................................ 118

    8.2. POLISH ALL THE WITH STRUCTURES ..................................................................................... 120

    8.3. GET RID OF FAT CODE (UNNECESSARY SELECTIONS AND REFERENCES) ........................................... 124

    8.4. ADD VBA CODE HERE AND THERE........................................................................................... 126

    8.5. MAKE THE CODE MORE READABLE .......................................................................................... 1268.6. DOCUMENT EVERYMACRO.................................................................................................... 127

    9. HOW TO MAKE AN EXCEL MACRO ADAPTABLE FOR VARIABLE-SIZED ARRAYS..................... 1289.1. MAKE YOUR MACRO VALID FOR STARTING EVERYWHERE IN THE SHEET ........................................... 128

    9.2. HOW TO CHANGE ABSOLUTE REFERENCES INTO RELATIVE ONES .................................................... 135

    9.3. MAKE YOUR MACRO TAKE DECISIONS...................................................................................... 135

    9.4. AVOID REPETITION ............................................................................................................... 138

    10. HOW TO TROUBLESHOOT AN EXCEL MACRO ..... ....... ....... ........ ....... ....... ........ ....... ....... .... 14310.1. FIX VBA SYNTAX ERRORS...................................................................................................... 143

    10.2. FIX COMPILATION-TIME ERRORS ............................................................................................. 146

    10.3. FIX RUN-TIME ERRORS.......................................................................................................... 147

    11. ABILITIES AND WEAKNESSES OF RECORDED MACROS .................................................... 15011.1. WHAT THE EXCEL MACRO RECORDER CAN DO ........................................................................... 151

    11.2. WHAT THE EXCEL MACRO RECORDER CANNOT DO...................................................................... 151

  • 8/3/2019 Record Excel Macros That Work

    9/152

    How to Record Excel Macros that Work

    P a g e | 9

    Purpose of this book

    Hi dear Excel user,

    Welcome to my book: How to RecordExcel Macros that Work: make themshorter, faster, and adaptable to variable-size arrays and workbooks.

    The purpose of this book is empowering you to delegate to the

    machine all the tasks that can be done by it. This way you will save

    tons of hours of tedious work, you will be happier and more efficient

    at work.

    To do that, you will take full control of the recording Macro feature in Excel.

    After reading and practicing the concepts on this volume you will

    Understand what a Macro isUnderstand the approach Excel uses to record MacrosPlan and record Excel Macros efficientlyIncrease your confidence to alter the VBA Macro code that is createdIntegrate your Excel Macros into your workbooks with buttons, menus,ribbons, etc.Get rid of fat code consistently

    Make Excel Macros usable for variable-size arraysAnd more

    Keep in mind that this book does not cover Excel VBA language to its

    fullest. However, I guarantee that you will develop a practical Excel VBAfoundation to move to highest stages with confidence (writing Excel Macrosfrom scratch).

    Get your free Excel VBA bonusBeyond 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 2003directions so both users groups enjoy the book.

    I recommend you start from the chapter one: Introduction to Excel Macros onpage 12; do it even if you are already familiar with recording Excel Macros, thereading 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 thebeginning on page 7 or the brief TOC below

    http://www.masterofmacros.com/bloghttp://www.masterofmacros.com/blog
  • 8/3/2019 Record Excel Macros That Work

    10/152

    How to Record Excel Macros that Work

    P a g e | 10

    All my experience with recording Excel Macros is here, nothing is left behind. Ihope you enjoy the book.

    John Franco

  • 8/3/2019 Record Excel Macros That Work

    11/152

    How to Record Excel Macros that Work

    P a g e | 11

    Brief Table of Contents

    ACKNOWLEDGEMENT .................................................................................................................6TABLE OF CONTENTS ..................................................................................................................7PURPOSE OF THIS BOOK .............................................................................................................9BRIEF TABLE OF CONTENTS ..................................................................................................... 111. INTRODUCTION TO EXCEL MACROS ....... ....... ....... ........ ....... ....... ........ ....... ....... ....... ........ .. 122. WHAT IS AN EXCEL MACRO .............................................................................................. 153. HOW THE EXCEL MACRO RECORDER WORKS ....... ........ ....... ....... ....... ........ ....... ....... ........ .. 224. HOW TO PLAN THE RECORDING OF AN EXCEL MACRO........................................................ 325. HOW TO RECORD AN EXCEL MACRO ....... ....... ........ ....... ....... ....... ........ ....... ....... ........ ....... . 426. HOW TO INTEGRATE AN EXCEL MACRO INTO YOUR WORKBOOKS .... .... ... .... .... ... .... .... ... .... .. 577. HOW EXCEL VBA WORKS ................................................................................................. 848. HOW TO MAKE A MACRO MORE EFFICIENT: SHORTER, FASTER AND SMALLER .................. 1189. HOW TO MAKE AN EXCEL MACRO ADAPTABLE FOR VARIABLE-SIZED ARRAYS..................... 12810. HOW TO TROUBLESHOOT AN EXCEL MACRO ..... ....... ....... ........ ....... ....... ........ ....... ....... .... 14311. ABILITIES AND WEAKNESSES OF RECORDED MACROS .................................................... 150

  • 8/3/2019 Record Excel Macros That Work

    12/152

    How to Record Excel Macros that Work

    P a g e | 12

    1. Introduction to Excel Macros

    acros are for your work on Excel the same thing an Excavator for aBuilding construction project; excavating a given building foundation byhand would take 12 months

    While doing it by machine, would take just 1 month

    M

    =

    Computing is not about

    computers any more. It is

    about living

    Nicholas Negroponte

  • 8/3/2019 Record Excel Macros That Work

    13/152

    How to Record Excel Macros that Work

    P a g e | 13

    When you use manual labor, your productivity is set by your muscle power andthe time you can employ your force decreases as you use it because you getbored.

    Even worst

    All the important tasks (pouring concrete, raising pillars and walls, etc.) arehalted during the excavation process. You cannot pour any drop of concreteuntil you finish the foundation hole, only occurring after 12 months.

    Yes, your goal is finishing the building but you are limited to employ your forceand talent on digging, for 12 bored months.

    On Excel, the time you employ copying/pasting or moving cells using yourmouse is manual labor. While you are doing this industrious work, you cannotemploy your energy on the things that add value to your work andorganization: analyzing data, finding relationships, etc. (in other words,finishing the building).

    Here is the good news

    =

  • 8/3/2019 Record Excel Macros That Work

    14/152

    How to Record Excel Macros that Work

    P a g e | 14

    You can reduce your excavation time by 11 months; yes, from 12 to 1 monthby shifting the use of your hands for an excavator.

    On Excel, you are able to transform your PC from manual to machine mode.

    How do you do it?

    By recording a Macro.

    Would you excavate by hand if you know an excavator can do it?

    Would you do the work with your mouse if you know the computer

    can do it?

    Enough big pictures for now

    Lets get deeper!

  • 8/3/2019 Record Excel Macros That Work

    15/152

    How to Record Excel Macros that Work

    P a g e | 15

    2. What is an Excel Macro

    Have you used a voice recording?

    The main benefit of such device is that everything you spoke once can berepeated over and over again without you physically speak again. Your voice isin the tape.

    You can even be heard without you been there.

    The Excel Macro recorder feature is a similar device. The difference is that youstore Excel actions instead of your voice. These actions can be repeated againand 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 formattingDelete all the empty sheetsDelete all sheets except the current oneArrange cells in a particular layoutAnd more

    An audio tape is a set of recorded sounds.

    A Macro is a set of recorded instructions.

    What kind of instructions? Actions like: changing the color of a cell, renaming asheet, creating a table, sorting, filtering, etc.

    All programmers are

    playwrights and all

    computers are lousy actors

    Author unknown

  • 8/3/2019 Record Excel Macros That Work

    16/152

    How to Record Excel Macros that Work

    P a g e | 16

    To reproduce your voice you hit the Play button on the recording device; on theother hand, to reproduce a set of actions on Excel you run a Macro. At thesame time, your voice is recorded on a magnetic tape, while your Excel actionsare recorded in a text file, specifically in a Sub procedure inside a text window

    called Module. See below

    Here is where your instructions are stored

    Your instructionsare recorded here

  • 8/3/2019 Record Excel Macros That Work

    17/152

    How to Record Excel Macros that Work

    P a g e | 17

    How do you record instructions in a macro?

    If you are using Excel 2007 or 2010, go to: View>Record Macro>Macroname:>Ok

    Or click the status bar. See below

    The Excel 2007/2010 status bar also indicates that Excel is in recording mode

    On Excel 2003

    Go to: Tools>Macro>Record New Macro

    And specify the Macro configuration (name, description, etc.)

    After pressing OK, the status bar indicates that Excel is in recording mode

    While this mode is activated, EVERYTHING you do on Excel will be

    recorded.

    This is not so good as it might appears; the same way your voice recordingdevice registers your hesitations and background noise, the Excel recordercaptures all your mistakes and incidental actions.

    This creates the need to edit recorded actions in Macros.

  • 8/3/2019 Record Excel Macros That Work

    18/152

    How to Record Excel Macros that Work

    P a g e | 18

    Now I will record a simple Macro (Macro1). Proceed as above to put Excel inrecording mode.

    Want to see whats going in the background?

    Split the Excel and the Excel VBA editor windows by right clicking on theWindows task bar (arrange windows vertically).

    See below the code window (Module1) with the SubMacro1before I do myfirst action on Excel

    Tip

    While Excel is on recording mode, its behavior is normal, with oneexception: in the background, Excel creates a Module (Module1,Module2, Module3, ModuleN) and a Sub procedure with the nameyou specify on the Record Macro dialog. By default: Macro1,

    Macro2, Macro3, MacroN.

    Each sub is aMacro

    A module is createdautomatically

  • 8/3/2019 Record Excel Macros That Work

    19/152

    How to Record Excel Macros that Work

    P a g e | 19

    In other words, this is Macro1 before I start any action on Excel.

    This isMacro1after I select the cell A1 on Excel

    No actions

    recorded yet

  • 8/3/2019 Record Excel Macros That Work

    20/152

    How to Record Excel Macros that Work

    P a g e | 20

    This isMacro1after I write the words Hello world on the cell A1 and pressEnter:

    This isMacro1after I select the cell A1 again and delete the content:

  • 8/3/2019 Record Excel Macros That Work

    21/152

    How to Record Excel Macros that Work

    P a g e | 21

    If you have never recorded a Macro, you have understood little of what waswritten on the code windows above. Dont worry; you will learn the Excel VBAbasics on the chapter: How Excel VBA works on page 84. This way you willbetter 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

  • 8/3/2019 Record Excel Macros That Work

    22/152

    How to Record Excel Macros that Work

    P a g e | 22

    3. How the Excel Macro Recorder Works

    he Excel macro recorder is a built-in engine that traces and stores youractions in Excel; its capabilities and features must be understood so yourecord efficient macros.

    Additionally,you will need the Macro recorder even after you learn howto write macros from scratch; I still use it to record simple macros and asan Excel VBA content provider.

    So lets start

    3.1. The Excel recorder registers every action youperform on Excel

    On your audio recording device; while the Record button is pressed,everything is recorded: your voice and the background noise. On Excel; thesame thing happens; while it is in recording mode every action is recorded.

    These actions might be: selecting a cell, writing a formula, scrolling, formattinga cell, zooming, etc.

    And every action is written on a line per line basis.

    Give a look

    Computers have lots of

    memory but no

    imagination

    Author Unknown

  • 8/3/2019 Record Excel Macros That Work

    23/152

    How to Record Excel Macros that Work

    P a g e | 23

    The same way a voice recording captures your hesitations and background

    noise, the Macro recorder captures everything you do, including yourmistakes and incidental actions.

    Tip

    Overlooked actions like: minimizing a window, adding a workbook, closingthe current workbook, zooming, etc. are also recorded

    Action 1

    Action 2

    Action 3

    Action 4

  • 8/3/2019 Record Excel Macros That Work

    24/152

    How to Record Excel Macros that Work

    P a g e | 24

    Look at Macro1 again (below) but now pay attention to some incidental actionsI performed while recording the Macro

    3.2. The Excel recorder generates a VBA instructionafter the given action has been performed on Excel

    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 Excelrecorder registers it. See below

    This is one of the main shortcomings to develop smart applications. A Macrodoes not have flow control, it starts and ends. It has no anticipation, nodecision.

    Selection first

    Recording later

    Incidental action 1.Maximizing the window

    Incidental action 4

    Incidental action 2. SelectingSheet2to make a visual

    check of a given cell

    Incidental action 3.Getting back to

    Sheet1

  • 8/3/2019 Record Excel Macros That Work

    25/152

    How to Record Excel Macros that Work

    P a g e | 25

    The unique way to build smart applications is by improving a Macro or

    by writing it from scratch.

    Get your free Excel VBA bonus Beyond the Excel Recorder by visiting:

    www.masterofmacros.com/blog

    Lets see the next feature

    3.3. The Excel recorder changes thepropertiesofExcel objects programmatically

    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.

    Some properties can be changed, like the color. Yes you can apply a cosmetictreatment 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

    A hair Property is what you hair is: length, color, etc.A hair Method is what you can do with your hair: cut it, change its shapeA hair Event is how it behaves: it grows, it falls, etc.

    Now back to Excel

    Excel has properties and methods too, and you can manipulate them by usingVBA language.

    You are fully aware of the way you change properties of Excel objects, youknow how to change the color of a cell, the font, the name of a sheet, etc. Butyou are not quite aware of how to change them programmatically; a Macropreforms that very easily. Lets see it

    Record a new Macro

    http://www.masterofmacros.com/bloghttp://www.masterofmacros.com/blog
  • 8/3/2019 Record Excel Macros That Work

    26/152

    How to Record Excel Macros that Work

    P a g e | 26

    Then, change the column A width

    On the background, Excel translates that into VBA code. For now, imagine thereis one by one correspondence between everything you do on Excel and the VBAcode.

    So the above action would produce the following code

  • 8/3/2019 Record Excel Macros That Work

    27/152

    How to Record Excel Macros that Work

    P a g e | 27

    Now do this action

    It would produce the following code

    This other action

  • 8/3/2019 Record Excel Macros That Work

    28/152

    How to Record Excel Macros that Work

    P a g e | 28

    Would produce this code

    3.4. The Excel recorder uses themethodsof ExcelObjects programmatically

    The same way you change the properties, you use the methods of Excel objects

    when you cut a cell, delete a sheet, open a workbook, etc.

    Here are some examples of how the Excel recorder uses Excel methods:

    The following action

    Would produce the following code

  • 8/3/2019 Record Excel Macros That Work

    29/152

    How to Record Excel Macros that Work

    P a g e | 29

    Here is another example:

    This action

    Would produce this code

    3.5. Using Relative Reference produces differentVBA code

    These actions

    Cut A1Select B1Paste

    are recorded differently when you set the reference of the Macro to absolute

    Cut

    Paste

  • 8/3/2019 Record Excel Macros That Work

    30/152

    How to Record Excel Macros that Work

    P a g e | 30

    Heres the produced Macro

    How do you set an absolute reference?

    On Excel 2007 go to View>Macros>Click on the drop down arrow; and then

    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 usingrelative reference, you would get a code like this one

    When you run this Macro it willselect the active cell instead of

    Range(A1)

    When you run this Macro it willalways select the Range(A1)

    Dont press it

  • 8/3/2019 Record Excel Macros That Work

    31/152

    How to Record Excel Macros that Work

    P a g e | 31

    Using relative reference is critical if you want to create Macros that

    work for variable-size arrays and workbooks.

    How do you set the reference to Relative? See below

    On Excel 2007 go to View>Macros>Click on the drop down arrow; and then

    On Excel 2003, use theStop Recording toolbar (displayed in recording mode)

    This has been all about how the Excel recorder works.

    Now, let me share to you everything about

    Tip

    You can change the reference from absolute to relative and vice versawhile you record.

    Press it

  • 8/3/2019 Record Excel Macros That Work

    32/152

    How to Record Excel Macros that Work

    P a g e | 32

    4. How to Plan the Recording of an ExcelMacro

    ecording a Macro is very easy from the point of view of the initiationprocess; you launch the Record Macro command and Excel starts torecord everything you do.

    The Excel recorder will also record your mistakes so

    If you want to record Macros that make what you want, you need to do someextra 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 youknow 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.

    R

    Simplicity is the ultimate

    sophistication

    Leonardo Da Vinci

  • 8/3/2019 Record Excel Macros That Work

    33/152

    How to Record Excel Macros that Work

    P a g e | 33

    You can do this by using the Transpose option of the Paste Special commandbut if you dont know this, you would intend to record a Macro.

    It is not good to try to reinvent the wheel.

    Overlooking available Excel commands leads you to record

    unnecessary Macros.

    Now that you are ready to record a Macro, heres the process to make itefficiently

    4.1. Get rid of unsystematic stuffImagine you have a database like the one shown below with thousands ofregisters 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

    Tip

    You will avoid recording unnecessary Macros as long as you know moreabout Excel available features.

  • 8/3/2019 Record Excel Macros That Work

    34/152

    How to Record Excel Macros that Work

    P a g e | 34

    The purpose of your Macro is to turn each block of data into a line (tableformat). The formatting would be something like this one:

    Recording a Macro in such circumstances would demand you create a Macro fortwo conditions. Yes you can do it, but let me ask you a question: is thedevelopment time worth the effort? It would be better to delete that row andrecord a Macro for a version of the report that has one row separation betweenblocks of data.

    Some prototyping measures include:

    Pasting all the data into the same sheetLeaving the same amount of space between dataGet rid of random stuffAny other measure to uniform the data

    Only this group isseparated by two rows

  • 8/3/2019 Record Excel Macros That Work

    35/152

    How to Record Excel Macros that Work

    P a g e | 35

    4.2. Break the Macro into smaller chunksHenry Ford stated that any task can be done if it is divided in enough doableparts.

    Plan your keystrokes by dividing them in workable parts.

    You decide what is doable for you. Here are some examples:

    Formatting, editing, etc.

    Moving cells, deleting rows, writing field headers, etc.You can be as detailed as you prefer

    For the case above, you can divide the Macro in two stages:

    1.Arrange data (move cells and delete the inter-block row)

    And

    Tip

    You can do the prototyping actions with a Macro.

    Tip

    Dont try to make your Excel Macro EXCESSIVELY universal at least thebenefits will a off the develo ment time and effort.

    Delete row

    Move cells

  • 8/3/2019 Record Excel Macros That Work

    36/152

    How to Record Excel Macros that Work

    P a g e | 36

    2. Creating the table headings

    Dont worry about having separate Macros; you can run them separately ormerge them very easily. See: How to merge two or more Macros on page 53.

    Another idea is to perform a kind of dress rehearsal, this way you detectbottlenecks; with this information you can decide how to make the RecordingMacro 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.

    4.3. Define the type of Macro: specific or generally-applicable Macro

    If all your tables would have 100 rows and 5 columns, just one Macro wouldwork 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 includingvariable-size arrays and variable-location.

    Heres how to do define a Macro that will work for variable conditions

    Use relative reference

    Imagine you want a Macro that adds field headers (Name and City) to a table.See below

    But the tables are not on the same position, see tables below

    Tip

    Recording a Macro in a relaxed manner helps you to minimize incidentalactions and mistakes.

    Write table headers

  • 8/3/2019 Record Excel Macros That Work

    37/152

    How to Record Excel Macros that Work

    P a g e | 37

    The relative reference makes your Macro works based on the position

    of the cursor when you recorded the Macro.

    Or this other way

    Choose the location of the cursor carefully so you can remember that

    position easily in the future when running the Macro.

    How do you activate the relative reference parameter?

    It is very easyOn Excel 2007/2010, go to: View>Macros>Macros

    You want to addfield headers here You want to add

    field headers here

    The cursor was herebefore recording the

    MacroThe cursor must be herebefore running the Macro

    The cursor was herebefore recording the

    MacroThe cursor must be herebefore running the Macro

  • 8/3/2019 Record Excel Macros That Work

    38/152

    How to Record Excel Macros that Work

    P a g e | 38

    On Excel 2003, activate it by using the Stop Recording toolbar (displayed

    while you are recording):

    For example: I recorded the process shown below (writing 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 anycell I run it, see below

    Activate this option

    The cursor was here before Irecorded the Macro

    The cursor must be herebefore I run the Macro

    The cursor must be herebefore I run the Macro

  • 8/3/2019 Record Excel Macros That Work

    39/152

    How to Record Excel Macros that Work

    P a g e | 39

    Now look at how Excel records a Macro with relative references

    If you want to create the same table always at one location, whatever theposition of the cursor; you need to use absolute reference

    Use absolute referenceUse this option when your Macros will be applied on the same location all thetime. See below

    For example, if you record the actions that produce the table formatting belowusing absolute reference, the table will be always produced at that location.

    Tip

    Absolute or relative reference setting can be changed during the recording

    Deactivate this option

    The Macro does not use staticranges like Range (A1)

    This table will be alwaysproduced at this location

  • 8/3/2019 Record Excel Macros That Work

    40/152

    How to Record Excel Macros that Work

    P a g e | 40

    See how the Macro starts

    4.4. Plan only one instanceOn 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 theprocessing of one block repeated thousands times.

    Focus on having one block right, the rest is just repeating.

    4.5. Finish the Macro SmartlyWhen you have thousands of blocks that repeat like the case shown above, youmust record a block and finish the Macro at the start of the next block. In otherwords, the Macro will start on block 1 and will finish on the beginning of theblock 2. Dont forget to set reference to relative.

    Always starts on A1

    Plan this blockonly

    These blocks arethe same

  • 8/3/2019 Record Excel Macros That Work

    41/152

    How to Record Excel Macros that Work

    P a g e | 41

    If you assign a shortcut to a given Macro you can execute it thousands of timeswith a simple keyboard pressing. This practice is great when you dont want touse loops or have not learned to use them yet.

    4.6. Backup the file before recordingTake into account that the actions are not undoable when you are recording aMacro. In consequence, avoid headaches.

    Get room for mistakes.

    Use the Save As command or make a copy using the Windows Explorer. Youcan also make a copy of the sheet you will apply the Macro on.

    Now you are ready to learn

    Tip

    Record a Macro at the start of one block and finish it at the start of thenext block.

  • 8/3/2019 Record Excel Macros That Work

    42/152

    How to Record Excel Macros that Work

    P a g e | 42

    5. How to Record an Excel Macro

    ecording a Macro is a linear process, you cannot move forward/backwardand you cannot undo the recorded actions. Assuming you have plannedyour Macro, here you will learn how to record it.

    In a nutshell

    To record a Macro, proceed this way

    On Excel 2007 or 2010 go to: View>Record Macro>Macro name:>Ok or clickthe Macro icon at the status bar

    After you click the Ok button, Excel turns to recording mode. The status baralways indicates that Excel is in recording mode, see below

    On Excel 2003, go to: Tools>Macro>Record New Macro>Macro name:>Ok.

    Excel 2003 shows Recording at the status bar to let you know it is inrecording mode

    This is just the beginning of the recording process. Lets go into details now

    R

    Man is still the most

    extraordinary computer of

    all

    John F. Kennedy

  • 8/3/2019 Record Excel Macros That Work

    43/152

    How to Record Excel Macros that Work

    P a g e | 43

    5.1. Where to place the cursor before recording aMacro?

    This step is critical. It defines the reusability of the Macro.

    The starting location of the cursor does not matter when you are recordingMacros that perform operations on the same location on each next time (usingabsolute references).

    On the other hand; the location of the cursor is critical when you are recordingMacros that perform operations on a different location each next time (usingrelative references). Before you record a Macro, place the cursor at the startof any given sequence of actions. Choosea place that is reproducible laterwhen running the macro. See below

    Always place your cursor at the right place before you launch the

    Record Macro command.

    Tip

    When you record dynamic macros, place your cursor at a border locationyou will easily remember later.

    Place the cursor herebefore recording

  • 8/3/2019 Record Excel Macros That Work

    44/152

    How to Record Excel Macros that Work

    P a g e | 44

    5.2. Where to place the cursor before stopping aMacro?

    The last position of the cursor does not matter when you are recording Macrosusing absolute reference.

    On the other hand; the ending location of the cursor is critical when you arerecording Macros using relative reference. Before you stop a Macro place thecursor 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.

    5.3. How to set up a MacroYou should set all the parameters of a Macro: Name, Shortcut, Store Macro in,and Description. Here I will show you how to do it

    Tip

    Assign a shortcut to a Macro to execute it with ease

    Place the cursor here beforestopping the Macro

  • 8/3/2019 Record Excel Macros That Work

    45/152

    How to Record Excel Macros that Work

    P a g e | 45

    Use a descriptive name

    You create Macros for reusing them; so a good name increases the usability ofa Macro. It allows you to pick the right Macro on the dialog or on the codewindow.

  • 8/3/2019 Record Excel Macros That Work

    46/152

    How to Record Excel Macros that Work

    P a g e | 46

    For example: compare these names Macro1, OpenWorkbook. See below

    You can discern what the Macro does by looking at the name. Additionally, youwill 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:

    OpenWorkbookCloseExcelDeleteFormatChangeColorCellChangeColorFont

    Set a shortcut

    This also increases the usability of a Macro. You run a Macro from twokeystrokes instead of searching the Macro on the Macro dialog list.

    On the Record Macro dialog, specify the shortcut key by just typing the letteryou want to assign to the Macro. The shortcut key text box is case sensitive

  • 8/3/2019 Record Excel Macros That Work

    47/152

    How to Record Excel Macros that Work

    P a g e | 47

    You can change the shortcut and description later by going to the Macro dialogand click the Options button. See below

    Define where to store the Macro

    There are two options

    Storing the Macro on a workbook. This forces you to open the file to runthe Macro

  • 8/3/2019 Record Excel Macros That Work

    48/152

    How to Record Excel Macros that Work

    P a g e | 48

    Storing the Macro on a binary file workbook (PERSONAL workbook). Thisenables you to run the Macro without opening any file. In other words, agiven 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 Integratean Excel Macro into your Workbooks on page 57

    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.This is more important if the Macro will be used by other users.

    The description can be edited later using theOptionsbutton of the Macrodialog

    5.4. How to record a dynamic (generally-applicable)Macro

    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 includeearlier mouse movements in your Macro )

    2. Launch the Record Macro dialog3.Assign a shortcut to your Macro (so you can repeat it easily - you will do

    a kind of manual loop)4. Click Ok on the Record Macro dialog

  • 8/3/2019 Record Excel Macros That Work

    49/152

    How to Record Excel Macros that Work

    P a g e | 49

    5. Use relative references. Do this before you perform any movement ofyour cursor

    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:6. Record one instance of the Macro (if you have one thousands blocks of

    data, record just one)7. Stop the Macro when your mouse is at the starting position of your next

    block of data (corresponding position to the location you started on step1 of this tutorial)

    6.Learn more about how to develop adaptable Macros by going to: Make yourMacro valid for starting everywhere in the sheet on page 128.

    5.5. How to record a specific MacroAs you learn before, these types of macros perform operations on the samelocation on 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 anygiven position in your spreadsheet; in other words, you can includeearlier 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 dialog4. 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 waya. On Excel 2003 do it this way: click the Relative Reference buttonon 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 macro6. Stop the Macro when all the keystrokes are recorded

  • 8/3/2019 Record Excel Macros That Work

    50/152

    How to Record Excel Macros that Work

    P a g e | 50

    5.6. How to start the recordingAssuming that your cursor is on the correct position (for generally-applicableMacros) you just need to hit the Ok button and record the actions you haveplanned.

    Relax please, if things go wrong, you have a backup copy to try it again.

    5.7. How to modify the Macro while you recordSplit 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 theway each action is turned into VBA code.

    See below

    Tip

    You can change reference setting while recording.

  • 8/3/2019 Record Excel Macros That Work

    51/152

    How to Record Excel Macros that Work

    P a g e | 51

    If you commit mistakes or perform incidental actions, you can delete themonthe goand 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 Substatement. It is required for Excel torecognize where the macro ends.

    5.8. How to stop the recording of a Macro?Once you have performed the last operation, you are ready to stop therecording of the Macro.

    Tip

    The new Macro code will be always written at the bottom of your last linein the Sub procedure.

    Delete these linesof code and keeprecording

  • 8/3/2019 Record Excel Macros That Work

    52/152

    How to Record Excel Macros that Work

    P a g e | 52

    Take into account the fact that you can delete instructions in a Macro while youare 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 bedeleted/modified and keep going.

    If you are finished or you want to stop the Macro because you made hugemistakes, do it this way

    By clicking the stop icon on the status bar (Excel 2007 and 2010)

    Or by going to: View>Macros>Stop Recording

    On Excel 2003, the Stop Recordingtoolbar is shown automatically after youstart recording. See toolbar below

    Sometimes, you close this toolbar by mistake and dont know how to stop therecording 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 andactivate theStop Recording toolbar. See below

  • 8/3/2019 Record Excel Macros That Work

    53/152

    How to Record Excel Macros that Work

    P a g e | 53

    5.9. How to modify the code after you record a MacroIf 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 ExcelVBA 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 theMacro 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 MacrosNot 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 thecursor on the desired location and paste instructions recorded in other Macros.

    http://www.masterofmacros.com/bloghttp://www.masterofmacros.com/blog
  • 8/3/2019 Record Excel Macros That Work

    54/152

    How to Record Excel Macros that Work

    P a g e | 54

    Here is an example of how to merge code

    This Macro writesHello world on cell A1

    Open the module

  • 8/3/2019 Record Excel Macros That Work

    55/152

    How to Record Excel Macros that Work

    P a g e | 55

    This other Macro does the same on A1 of the Sheet2

    This is a new Macro: Macro 1 + Macro 11

    Or macro11 nested in macro1

    You can also paste code to the Macro while recording.

  • 8/3/2019 Record Excel Macros That Work

    56/152

    How to Record Excel Macros that Work

    P a g e | 56

    Tip

    Keep aware that the Selection statements instructions of the pasted codeare corresponding to the preceding and subsequent lines.

  • 8/3/2019 Record Excel Macros That Work

    57/152

    How to Record Excel Macros that Work

    P a g e | 57

    6. How to Integrate an Excel Macro intoyour Workbooks

    hen you travel, bringing your camera with you is not enough; if thecamera is stored on a bag difficult to open, you will lose importantshots. It is better to carry the camera on your hand.

    Now your Macro lies dormant in some module. It is of no value to yourproductivity if you cannot access it easily and at the right time.

    Here you will learn:

    Where to put your recorded Macros (recorded by you or received fromothers)How to make a Macro available to all workbooksHow to make a Macro available to the workbook where it was created

    To access a Macro effectively you must first know where it is located. Youspecify this at the moment of recording. Macros are stored in Modules (.bas).

    Lets start

    6.1. How to access a Macro from the workbook it wascreated

    Every workbook has its own modules where Macros can be stored. All theseMacros can be accessed from the given parent workbook. See below

    W

    I do not fear computers. I

    fear the lack of them

    Isaac Asimov

  • 8/3/2019 Record Excel Macros That Work

    58/152

    How to Record Excel Macros that Work

    P a g e | 58

    How do you make a Macro available to a workbook?

    You need to put it into a module of the given workbook.

    How do you do that?

    You have three options:

    1)Specify the location at the moment of recordingSet the field Store Macro in: to This Workbook or New Workbook. See below

    What happens when you use this option?

  • 8/3/2019 Record Excel Macros That Work

    59/152

    How to Record Excel Macros that Work

    P a g e | 59

    Excel creates a module (Module1 by default) with a Sub procedure with thename Macro13 or the name you specify on the Macro name: text box

    2)Paste a Macro into a workbook moduleYou can also create your own modules and store Macros there. See below

    Tip

    Changing the name of the module or the Sub wont affect their listing on

    the Macro dialog.

  • 8/3/2019 Record Excel Macros That Work

    60/152

    How to Record Excel Macros that Work

    P a g e | 60

    All the Macros contained in modules are displayed in the Macro dialog. Seebelow

    For editing and managing purposes, it is a good practice to locate Macros inrelated modules with meaningful names.

  • 8/3/2019 Record Excel Macros That Work

    61/152

    How to Record Excel Macros that Work

    P a g e | 61

    Keep in mind that those macros that contain arguments are not displayed onthe Macro dialog.

    You can also store your Macros on .txt files. Later, you can copy and paste thecode into a module of any given workbook.

    This macro (witharguments) is not listed on

    the Macro dialog

  • 8/3/2019 Record Excel Macros That Work

    62/152

    How to Record Excel Macros that Work

    P a g e | 62

    3)Import a moduleAnother way to bring a Macro into a workbook is by importing a module.

    On the Visual basic editor, go to:

    File>Import File

    Or right click on the Project Explorer (CTRL + R) and choose Import File

    Once your Macro is on a module of a given workbook you can call it usingseveral methods

    Access a Macro from the Macro DialogLaunch the Macro dialog by pressing ALT + F8. Then, chooseMacros in: andselect This Workbook(the Macros are listed on the pane below Macro name:).Then select the Macro you want to run and hit Run.

  • 8/3/2019 Record Excel Macros That Work

    63/152

    How to Record Excel Macros that Work

    P a g e | 63

    Access a Macro from a shape, picture, or graph

    The above method is not so good because you need to perform some clicks torun a Macro.

    If you want to run a Macro with a mouse click, then you need to run Macrosfrom 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 AssignMacro. See below

    On the Assign Macro dialog, choose the desired Macro.

    Now your button is clickable!

    Add an extra touch

    Right click over the button and chooseEdit text

  • 8/3/2019 Record Excel Macros That Work

    64/152

    How to Record Excel Macros that Work

    P a g e | 64

    You can create fancy buttons!

    Tip

    You can copy and paste a button to other workbook. The path of the

    Macro will be kept

  • 8/3/2019 Record Excel Macros That Work

    65/152

    How to Record Excel Macros that Work

    P a g e | 65

    Access a Macro from a shortcut

    Configure the shortcut when you start recording a Macro.

    If you forget to specify the shortcut at the moment of the recording, you canspecify a shortcut later on the Macro dialog. Do it by going to: ALT +F8>Options>Shortcut key:

    See below

  • 8/3/2019 Record Excel Macros That Work

    66/152

    How to Record Excel Macros that Work

    P a g e | 66

    Access a Macro from an Event

    You can also launch a Macro when the user changes a cell, when a book isopened, 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 forwhich you want to specify the Macro

    I used Sheet1 for this example; then, on the code window, choose Worksheet.See below

    Then choose the event

    Choose object

    Choose event

  • 8/3/2019 Record Excel Macros That Work

    67/152

    How to Record Excel Macros that Work

    P a g e | 67

    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 currentproject

    6.2. How to access a Macro from any workbookTo make a Macro available to all your workbooks and from any session of Excelyou must store it in the Personal workbook. The Personal workbook is a binaryfile (.xlsb) saved in a central location. The Macros on this workbook are visibleto all books in any Excel session. See below

  • 8/3/2019 Record Excel Macros That Work

    68/152

    How to Record Excel Macros that Work

    P a g e | 68

    How do you do that?

    Specify the location at the moment of recording

    Set the field Store Macro in: to Personal Macro Workbook. See below

    At the moment of running the Macro, it is not necessary you open the PersonalMacro Workbook. See below

  • 8/3/2019 Record Excel Macros That Work

    69/152

    How to Record Excel Macros that Work

    P a g e | 69

    Now that your given Macro is properly stored, you can

    Access a Macro from the Ribbon (Excel 2007)

    Unfortunately, Excel 2007 does not allow you to customize the Ribbon.

    The most you can do is to personalize the Quick Access Toolbar (QAT)

    Tip

    By default the location of the personal workbook is:

    Windows Vista: C:\Users\user name\AppData\Local\Microsoft\Excel\XLStart

    Windows XP: C:\Documents and Settings\user name\ApplicationData\Microsoft\Excel\XLStart

    This book isautomatically shown

  • 8/3/2019 Record Excel Macros That Work

    70/152

    How to Record Excel Macros that Work

    P a g e | 70

    Do it this way

    1. Right click over any area of the Ribbon and choose Customize QuickAccess Toolbar

    2. Choose Macros from the Choose commands from: list

    3. Select the Macro you want to add to the QAT and click on the Add>>button

  • 8/3/2019 Record Excel Macros That Work

    71/152

    How to Record Excel Macros that Work

    P a g e | 71

    4. Click on Modify and assign a meaningful name:

    Your QAT is ready

    Access a Macro from the Ribbon (Excel 2010)

    Now that your Macro can be called from any workbook, it is a good idea tocreate a dedicated Ribbon.

  • 8/3/2019 Record Excel Macros That Work

    72/152

    How to Record Excel Macros that Work

    P a g e | 72

    Just to refresh your knowledge of the Excel Ribbon, lets familiarize with thecomponents again

    In 2010 you MUST create a new tab to be able to add new commands andmacros. 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 thisway

    5. Right click over any area of the Ribbon and choose Customize theRibbon

    6. Click on New Tab

    Tab

    Group

    GroupCommandsCommands

  • 8/3/2019 Record Excel Macros That Work

    73/152

    How to Record Excel Macros that Work

    P a g e | 73

    7. Right click on the new tab and choose Rename. Assign a meaningfulname

    8. Right click on the default group created and choose Rename. Assign aname. See below

    9. Choose Macros from the Choose commands from: list

  • 8/3/2019 Record Excel Macros That Work

    74/152

    How to Record Excel Macros that Work

    P a g e | 74

    10.Select the Macro you want to add to the selected group and click on theAdd>> button

    11.Right click over the recently added Macro and choose Rename. Assign ameaningful name and icon. See below

    Your new Tab is ready to use.

  • 8/3/2019 Record Excel Macros That Work

    75/152

    How to Record Excel Macros that Work

    P a g e | 75

    Access a Macro from a toolbar (Excel 2003)

    Now that your Macro can be called from any workbook, it is a good idea tocreate a dedicated toolbar.

    Just to refresh your knowledge of the old Excel toolbar system, lets familiarizewith the components again

    You can create a new toolbar with commands (Macros).

    Proceed this way

    1. Right click over any toolbar and choose Customize from the contextualmenu.

    Tip

    You can export your Ribbon personal configuration and load it on any otherPC.

    Toolbar

    Commands

  • 8/3/2019 Record Excel Macros That Work

    76/152

    How to Record Excel Macros that Work

    P a g e | 76

    2. Click on New in the Toolbars tab and assign a meaningful name. Seebelow

    3. Click on Commands tab>Categories: and go to Macros. Then drag anddrop a Custom Button (Commands: area) to the recently created toolbar.See below

  • 8/3/2019 Record Excel Macros That Work

    77/152

    How to Record Excel Macros that Work

    P a g e | 77

    4. Right click over the recently created button and clickAssign Macro.Choose the Macro to link to the button.

  • 8/3/2019 Record Excel Macros That Work

    78/152

    How to Record Excel Macros that Work

    P a g e | 78

    5. Modify the appearance of the button by right clicking on it and choosing:Edit Button Image, Name, etc.

    -

    Now your new toolbar is ready

    You may also place a macro command on an existing toolbar.

    Access a Macro from a menu (Excel 2003)

    Now that your Macro can be called from any workbook, it is a good idea to

    create a dedicated menu.

  • 8/3/2019 Record Excel Macros That Work

    79/152

    How to Record Excel Macros that Work

    P a g e | 79

    Just to refresh your knowledge of the old Excel menu, lets familiarize with the

    components again

    Proceed this way

    1. Right click over any toolbar and choose Customize from the contextualmenu.

    2. Click on Commands tab>Categories: and select New menu. Then dragand drop the New Menu button (Commands: area) to the desiredlocation in the menu area. See below

    Menu

    Command

    Command

  • 8/3/2019 Record Excel Macros That Work

    80/152

    How to Record Excel Macros that Work

    P a g e | 80

    A new menu is created

    3. Click on Macros and then drag and drop a Custom Button to therecently created menu.

  • 8/3/2019 Record Excel Macros That Work

    81/152

    How to Record Excel Macros that Work

    P a g e | 81

    4. Right click on the recently created button and then click assign Macro.

  • 8/3/2019 Record Excel Macros That Work

    82/152

    How to Record Excel Macros that Work

    P a g e | 82

    Proceed the same way as explained above in Access a Macro from a toolbar

    (Excel 2003) on page 75.You may also place a macro on an existing menu.

    6.3. Where to put a Macro you receive from othersFirst, open the workbook that contains the Macro, go to the module and copythe procedure, then open the destination workbook and open or create amodule and paste the Sub procedure.

    You can also import any given module.

    6.4. How to stop the execution of a MacroYou know how to run a Macro but what happens when the Macro is taking toomuch 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

  • 8/3/2019 Record Excel Macros That Work

    83/152

    How to Record Excel Macros that Work

    P a g e | 83

    6.5. What to do when your Macro dont do what youwant

    If a Macro doesnt do what you want, you have three lines of actions:

    Recording it again,Fine-tuning it orWriting it from scratch

    Writing a Macro from scratch is out of the scope of this book but now I willshow you how to improve your Excel Macros.

    Get your free Excel VBA bonus Beyond the Excel Recorder by visiting:

    www.masterofmacros.com/blog

    Press the Endbutton

    http://www.masterofmacros.com/bloghttp://www.masterofmacros.com/bloghttp://www.masterofmacros.com/blog
  • 8/3/2019 Record Excel Macros That Work

    84/152

    How to Record Excel Macros that Work

    P a g e | 84

    7. How Excel VBA works

    magine you are going to spend your next vacation on Japan, you dontknow Japanese but you equip with a 3-phrase vocabulary:

    How much is it?

    Where do I find cheap hotels?

    How can I reach the airport?After landing, your trip is going wonderful but suddenly your little son feels sickat the zooHow 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 dont know what the VBA code does

    and how to adapt your script to new situations like making your Macros workfor variable-size arrays and workbooks.

    You can only be efficient on real social environment by understanding thelanguage grammar so you can construct new expressions as new needs arise.

    At the same time, to get ahead on your automation requirements you mustunderstand the basic principles of Excel VBA so you record Macros withconfidence and alter its code to suit your needs.

    This book enables you to record efficient Macros and to gain a reasonable ExcelVBA grammar awareness so you deal with new situations with more confidence.

    Lets understand the Excel VBA language better

    I

    Those parts of the systemthat you can hit with a

    hammer (not advised) are

    called hardware; those

    program instructions that

    you can only curse at are

    called software.

    Author Unknown

  • 8/3/2019 Record Excel Macros That Work

    85/152

    How to Record Excel Macros that Work

    P a g e | 85

    Have you played Mario Bros videogame?

    I bet you did! If not, you are somehow familiar with it because your childrenplay 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) fora new version of the game

    As the developer, you must define his behavior and unique characteristics soplayers 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):

    Hair colorDress color

    HeightScore

  • 8/3/2019 Record Excel Macros That Work

    86/152

    How to Record Excel Macros that Work

    P a g e | 86

    You also define the actions he will perform (methods):

    WalkRunJump

    Finally, you define the consequences of the actions Mario executes (events); forexample: if an enemy kills Mario, he will die.

    You cannot create a command to make it die because nobody dies bycommand. Dying is a consequence of being killed, being ill, etc. The events youwould create are:

    Height increase (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 samedeveloping means you must specify how the properties, methods and eventsinteract 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 amushroom or he can make him run, jump, etc.

    Lets imagine you write the instructions in plain English

    If Mario eats a mushroom, then change the height of Mario to 5 pixels, or youcan use a more structured syntax:

    IF Mario eats a mushroom THEN Mario height = 5 pixels

    In VBA language this would be

    Mario.height = 5

  • 8/3/2019 Record Excel Macros That Work

    87/152

    How to Record Excel Macros that Work

    P a g e | 87

    In Excel VBA you do it this way

    Range("A1").ColumnWidth = 30Range("A1").Font.Size = 12Worksheets("Sheet2").Name = "Data"Etc

    Now lets talk about the methods

    When you give instructions in real life, you provide further specifications so thegiven action is completed adequately. For example: bring me a hamburgerwithout 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 wouldsay in plain English

    Run Mario at slow speed to the left.

    In VBA language this would be

    Mario.Run (slow, left)

    slowandleftare arguments for the Run method.

    Some methods do not require any argument like: jump Mario.

    Using VBA language this would be

    Mario.Jump

    In Excel VBA you do it this way

    Range(A1).SelectRange(A1).ClearCommentsWorksheets(Sheet1).DeleteEtc

    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.

  • 8/3/2019 Record Excel Macros That Work

    88/152

    How to Record Excel Macros that Work

    P a g e | 88

    Its all about that. It is that simple!

    7.1. VBA syntaxTo give an instruction in real world you use English, to give an instruction toExcel you use VBA language.

    And the syntax is as follows

    To change an object property, use the following syntax

    Objectname.PropertyNameHere = value assigned to property

    To get the value of an object property, use the following syntax

    Value gotten from property = Objectname. PropertyNameHere

    Now let me show you a real VBA syntax example

    I assign 8.5 width to the column A

    Columns("A:A").ColumnWidth = 8.5

    To execute an object method, use the following syntax

    Objectname.MethodNameHere (argument1 of the method, argument2 ofthe method, argumentN of the method)

    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)?

    Go to: How to find Excel Objects properties and methods? On page 91

    This has been a quick and practical introduction to Excel VBA grammar.

    Do you still find Excel VBA as Greek?

    TipYou cannot record Macros for object Events but you can use Excel objectevents when you write Macros from scratch.

  • 8/3/2019 Record Excel Macros That Work

    89/152

    How to Record Excel Macros that Work

    P a g e | 89

    You have a hard time because you try to match the VBA syntax to Englishgrammar. Keep in mind that languages are arbitrary assignments of meaning tosymbols. Give a look at these representations of abuildingin differentlanguages:

    Can you find a trace of a building in the words: edificio or KTpio?

    I bet you didnt

    Human languages work because a group of people accepts a set of symbolsand give them unique meaning.

    So if you want to fully master Excel VBA grammar, you need to accept itsarbitrariness the same way you accept the conventions of English.

    7.2. Excel objects properties and methodsAn Excel Macro is a group of instructions written in VBA language. A Macromodifies properties and executes methods of Excel objects (range, worksheet,workbook, etc.).

    If you want to alter the code of a Macro to get different results, change the

    way Excel modifies the properties of objects and the way it executesobjects methods.

    Tip

    In English there is no a unique way to convey meaning, for exampleSusan, paint the wall, please Susan paint the wall, etc.

    Also, in VBA language, you can convery meaning in several correct ways.

    Building (English)

    Edificio (Spanish)

    KTpio (Greek)

  • 8/3/2019 Record Excel Macros That Work

    90/152

    How to Record Excel Macros that Work

    P a g e | 90

    To modify an Excel Macro you need to ask these two questions:

    What Excel Object property do I want to change?What Excel Object method do I want to execute?

    Now you are wondering what properties and methods you can use to modifyExcel programmatically?

    Let me ask you three more questions

    Have you changed the name of a sheet?Have you opened a book?Have you delete the content of a cell?

    You have answered yes to all the above questions soyou are already familiar

    with the behavior of many of Excel objects: Cells, Sheets, Columns, Charts,Pivot Tables, etc.

    See below an outline of some common properties and methods of commonobjects

    Now, you might me be asking

  • 8/3/2019 Record Excel Macros That Work

    91/152

    How to Record Excel Macros that Work

    P a g e | 91

    7.3. How to find Excel Objects properties andmethods?

    What happens when you learn how to modify and access properties andmethods?

    You acquire a key VBA competency. You need this knowledge to makeMacros do what you want.

    So then if properties and methods are so important, where do I start?

    Properties and methods are related to any given object so first identify theobject you want to manipulate:

    Range

    WorksheetWorkbook, etc.

    The names of the members (properties and methods) are in English

    and are meaningful. For example:

    BordersClearCommentsActiveCellSpellingOptions

    MergeCells, etc.Use these handy techniques to find properties and methods

    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 ina 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 andpaste that code.

    Get assistance from theAuto List Memberscommand while you

    write

    I love this way of knowing the properties and methods.

    Avoid writing code from scratch, type CTRL + J to launch theAuto List

    Membersfeature.You can also launch this feature by using the Edit toolbar

  • 8/3/2019 Record Excel Macros That Work

    92/152

    How to Record Excel Macros that Work

    P a g e | 92

    See below

    What is shown on theAuto List Memberslist?

    You see the available members at the current slot. See below

    Use the up/down arrows to navigate through members and the Tab/Enter keyto accept a choice.

    The Auto List member feature is automatically displayed after entering a point

    So you can choose the desired property or method

    Methods for Range(A1)

    Properties forRange(A1)

    Press CTRL + J whileyou are here

  • 8/3/2019 Record Excel Macros That Work

    93/152

    How to Record Excel Macros that Work

    P a g e | 93

    And complete the expression

    For any given method, its arguments are provided after you type the space baror write a parenthesis

    Use the VBA editor Help section

    For Excel 2007 users

    While you are on the VBA editor, press F1 or go to the Help menu. Thenchoose: Excel Object Model Reference, then pick the object and then browsethe members list

    TipIdentify object methods with this symbol

    Identify object properties with this symbol

    Identify object events with this symbol

  • 8/3/2019 Record Excel Macros That Work

    94/152

    How to Record Excel Macros that Work

    P a g e | 94

    For Excel 2003 users

    While you are on the VBA editor, press F1 or go to the Help menu. Then typethe name of the object on the search box

    And then choose the desired topic from the results

    1) Pick theExcel Object

    Model

    2) Pick theobject

    3) Pickmembers

    4) Browse themembers

  • 8/3/2019 Record Excel Macros That Work

    95/152

    How to Record Excel Macros that Work

    P a g e | 95

    Or you can use the help to navigate through

    Use the Object browser

    The object browser is a pane that contains all the objects and their membersorganized.

    While you are on the Visual Basic editor, press F2 to launch it. Then, choose theVBA library

  • 8/3/2019 Record Excel Macros That Work

    96/152

    How to Record Excel Macros that Work

    P a g e | 96

    After that, pick any given object on the left pane and explore its members(properties, methods and events) on the right pane

    You can copy the objects syntax from the pane and paste it on any given codewindow. Use right click or CTRL + C. See below

    Use the Local Windows

    This is a more advanced technique

    Create this Macro:

    Objects

    Members: properties,methods and events

  • 8/3/2019 Record Excel Macros That Work

    97/152

    How to Record Excel Macros that Work

    P a g e | 97

    And then, to the right of the (=) sign, write the object you want to know moreabout, for example: a Range objectNow execute the Macro step by step thisway:

    1. Place the cursor inside the storeobject procedure and then2. 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 impacton Excel. Split vertically the VBA editor and the Excel windows for betterunderstanding

    The above methods are great to get the full syntax and help about any objectproperty and method.

    If you want to go deeper in the Excel Objects universe, come with me, I willshow you the

    Click the object to see itsmembers Explore or change theproperties

  • 8/3/2019 Record Excel Macros That Work

    98/152

    How to Record Excel Macros that Work

    P a g e | 98

    7.4. Excel Object Model revealedThe Excel object model is a necessary conceptual artifact to manage the objectsof an application. Now, you will create a new frame of mind to understand thisconcept.

    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 ofeverything on it would be this one

    Now, imagine you give a command to a human to collect the fruit 1 from thetrees.

    The human would ask you: the fruit 1 of which tree?

    So you need to narrow down your instruction. You would say, bring me the fruit1 of the tree 2.

    Surface

    Trees

    Fruits

    1 2

    1 2 3

    12

  • 8/3/2019 Record Excel Macros That Work

    99/152

    How to Record Excel Macros that Work

    P a g e | 99

    Now the human is enabled to follow your instruction.

    To identify a fruit you must first identify the tree in the collection of trees. Onlyafter that the fruitIdmakes sense. In other words, the collection of fruits isassociated to a tree of the collection of trees.

    Lets talk more about collections

    The earth has three collections (notice the s at the end, collections are alwaysplural):

    TreesBranchesFruits

    The collection of trees would be something like this one

    The collection of fruits would be something like this one

  • 8/3/2019 Record Excel Macros That Work

    100/152

    How to Record Excel Macros that Work

    P a g e | 100

    But associated to any given tree

    And each object in a given collection has its own features. See below

  • 8/3/2019 Record Excel Macros That Work

    101/152

    How to Record Excel Macros that Work

    P a g e | 101

    And some objects dont belong to any collection but they also has propertiesand methods

    An object model is the hierarchy of collections and objects of a whole system.

    Here you have a detailed object model of the earth

  • 8/3/2019 Record Excel Macros That Work

    102/152

    How to Record Excel Macros that Work

    P a g e | 102

  • 8/3/2019 Record Excel Macros That Work

    103/152

    How to Record Excel Macros that Work

    P a g e | 103

    Here is a summarized Excel Object model

    So

    In Excel to access a range object, you must specify which one from which

    worksheet and from which workbook.

  • 8/3/2019 Record Excel Macros That Work

    104/152

    How to Record Excel Macros that Work

    P a g e | 104

    The good news is that you dont 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 treewithout additional identification.

    On Excel, you dont need to use the workbook/sheet qualifier all the time.

    For example, while the Sheet1 is active, the following code write Hello worldon 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

    Now lets explore the

    7.5. Popular Excel VBA ObjectsHeres 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).

    Range

    Here is the list of the 57 (out of 97) most used Range Properties:

    Name Description1

    Activate

    Activates a single cell, which must be inside the current selection. To

    select a range of cells, use the Select method.

    AddComment Adds a comment to the range.

    Address

    Returns a String value that represents the range reference in the

    language of the Macro.

    AutoFilter Filters a list using the AutoFilter.

    AutoFit

    Changes the width of the columns in the range or the height of the rows

    in the range to achieve the best fit.

    BorderAround

    Adds a border to a range and sets the Color, LineStyle, and Weight

    properties for the new border. Variant.

    1 Source: Microsoft Excel Help

  • 8/3/2019 Record Excel Macros That Work

    105/152

    How to Record Excel Macros that Work

    P a g e | 105

    Borders

    Returns a Borders collection that represents the borders of a style or a

    range of cells (including a range defined as part of a conditional format).

    Cells Returns a Range object that represents the cells in the specified range.

    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.

    ClearHyperlinks The description for this item will appear in the final release of Office 14.

    Column

    Returns the number of the first column in the first area in the specified

    range. Read-only Long.

    Columns

    Returns a Range object that represents the columns in the specified

    range.

    CommentReturns a Comment object that represents the comment associated withthe cell in the upper-left corner of the range.

    Copy Copies the range to the specified range or to the Clipboard.

    Count

    Returns a Long value that represents the number of objects in the

    collection.

    CurrentRegion

    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.

    Cut Cuts the object to the Clipboard or pastes it into a specified destination.

    Delete Deletes the object.

    End

    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-

    only Range object.

    Find Finds specific information in a range.

    FindNext

    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.

    Font Returns a Font object that represents the font of the specified object.

    FormatConditions

    Returns a FormatConditions collection that represents all the conditional

    formats for the specified range. Read-only.

    Formula

    Returns or sets a Variant value that represents the object's formula in A1-

    style notation and in the language of the Macro.

    FormulaArray

    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.

    FormulaLocal

    Returns or sets the formula for the object, using A1-style references in

    the language of the user. Read/write Variant.

  • 8/3/2019 Record Excel Macros That Work

    106/152

    How to Record Excel Macros that Work

    P a g e | 106

    FormulaR1C1

    Returns or sets the formula for the object, using R1C1-style notation in

    the language of the Macro. Read/write Variant.

    FormulaR1C1Local

    Returns or sets the formula for the object, using R1C1-style notation in

    the language of the user. Read/write Variant.

    HorizontalAlignment

    Returns or sets a Variant value that represents the horizontal alignment

    for the specified object.

    Hyperlinks

    Returns a Hyperlinks collection that represents the hyperlinks for the

    range.

    Insert

    Inserts a cell or a range of cells into the worksheet or Macro sheet and

    shifts other cells away to make space.

    Interior

    Returns an Interior object that represents the interior of the specified

    object.

    Item

    Returns a Range object that represents a range at an offset to the

    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.

    NumberFormat

    Returns or sets a Variant value that represents the format code for the

    object.

    Offset

    Returns a Range object that represents a range thats offset from the

    specified range.

    Parse

    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.

    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.

    Replace

    Returns a Boolean indicating characters in cells within the specified

    range. Using this method doesnt change either the selection or the

    active cell.

    Row

    Returns the number of the first row of the first area in the range. Read-

    only Long.

    Rows

    Returns a Range object that represents the rows in the specified range.

    Read-only Range object.

    Select Selects the object.

    Sort Sorts a range of values.

    Table

    Creates a data table based on input values and formulas that you define

    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.

    Value

    Returns or sets a Variant value that represents the value of the specified

    range.

    Value2 Returns or sets the cell value. Read/write Variant.

    VerticalAlignmentReturns or sets a Variant value that represents the vertical alignment ofthe specified object.

  • 8/3/2019 Record Excel Macros That Work