Ug recording excelmacros

2,812 views

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,812
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
310
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Ug recording excelmacros

  1. 1. VBA HandbookRecordingExcelMacrosLearn to Record and Edit VBA MacrosIn Microsoft ExcelBy Martin Green
  2. 2. Recording Excel Macros Contents About This Book .......................................................................................................... 4 Who is it for?.......................................................................................................... 4 Whats Inside?........................................................................................................ 4 Introducing Recorded Macros........................................................................................ 4 What is a Macro? .................................................................................................... 4 What a Recorded Macro Can Do and What It Cant ...................................................... 4 Visual Basic or VBA?................................................................................................ 5 About Macro Security .............................................................................................. 5University of Greenwich Students Edition Opening Files Containing VBA Code ......................................................................5 Setting the Programs Security Level..................................................................... 6 Emailing Files Containing Code............................................................................. 7 Starting and Stopping the Macro Recorder ................................................................. 7 The Visual Basic Toolbar .......................................................................................... 8 Recording Macros ........................................................................................................ 9 About the Exercises................................................................................................. 9 Step-by-Step: Record a Simple Macro ..................................................................... 10 for Educational Use Only Step-by-Step: Test the Macro................................................................................. 12 Step-by-Step: Record and Test a More Complex Macro.............................................. 13 Tips for Recording Macros ...................................................................................... 16 Get More Familiar with Excel .............................................................................. 16 Plan the Macro ................................................................................................. 16 Generalize Your Commands ............................................................................... 16 Correcting Mistakes .......................................................................................... 16 Relative or Absolute References? ............................................................................ 17 Step-by-Step: Compare Relative and Absolute References ......................................... 18 Running Macros ........................................................................................................ 20 Different Ways to Run a Macro ............................................................................... 20 The Macro Dialog.............................................................................................. 20 Toolbar Button ................................................................................................. 20 Menu Item....................................................................................................... 22 Worksheet Button............................................................................................. 23 Graphic Object ................................................................................................. 24 Assigning a Shortcut Key................................................................................... 24 Automatic Macros ............................................................................................. 25 Which Way is Best? .......................................................................................... 25 Undoing a Macros Actions ..................................................................................... 25 Macro Options........................................................................................................... 26 Macro Names ....................................................................................................... 26 Auto Macros ......................................................................................................... 26 Where Should the Macro be Stored?........................................................................ 26 Personal Macro Workbook.................................................................................. 27 This Workbook ................................................................................................. 27 New Workbook................................................................................................. 27 Summary and Other Options.............................................................................. 27 Changing Macro Options ........................................................................................ 28 Saving and Deleting Macros ................................................................................... 28 Editing Recorded Macros ............................................................................................ 29 Viewing Recorded Code ......................................................................................... 29 The Simple Macro ............................................................................................. 29 The FillEmptyCells Macro ................................................................................... 31 The AbsoluteReferences and RelativeReferences Macros ........................................ 32 The Visual Basic Editor .......................................................................................... 32 Opening the Visual Basic Editor .......................................................................... 32 The Visual Basic Editor Window .......................................................................... 33 The Project Explorer ......................................................................................... 33 Working with VBA Code ......................................................................................... 34 Managing Code Modules .................................................................................... 34 Importing and Exporting Code............................................................................ 35 Running Code from the Visual Basic Editor........................................................... 35 © Martin Green www.fontstuff.com 2
  3. 3. Recording Excel Macros Editing Code .................................................................................................... 36 Getting Help......................................................................................................... 36 Using the Help Menu ......................................................................................... 36 Context Sensitive Help with the F1 Key ............................................................... 36 Editing VBA Code Practical Exercises............................................................................ 38 Step-by-Step: Experiment with Colours ................................................................... 38 Create the Macro .............................................................................................. 38 Summary ........................................................................................................ 44 Step-by-Step: Build a Random Numbers Macro ........................................................ 45 Create the Macro .............................................................................................. 45University of Greenwich Students Edition Summary ........................................................................................................ 50 What Comes Next? .................................................................................................... 51 Where Do I Go from Here?..................................................................................... 51 Recommended Web Sites....................................................................................... 51 Recommended Reading ......................................................................................... 51 Notes and Further Information.................................................................................... 52 About the Author .................................................................................................. 52 Copyright............................................................................................................. 52 for Educational Use Only Limitation of Liability ............................................................................................. 52 First Published in 2005 by Martin Green Web Site: http://www.fontstuff.com e-mail: martin@fontstuff.com © 2005 Martin Green – All rights reserved. © Martin Green www.fontstuff.com 3
  4. 4. Recording Excel Macros About This Book Who is it for? This book is for the Microsoft Excel user who wants to increase their productivity and automate tedious or repetitive tasks with the help of Excel Macros. Anyone thinking about learning Excel VBA (Visual Basic for Applications) programming will also find this a good place to start.University of Greenwich Students Edition To make the most of this book you should have at least a basic working knowledge of Microsoft Excel. You dont need to be an "advanced" or "expert" Excel user. You dont need any prior knowledge of recording or editing macros, nor do you need any knowledge of VBA programming, or any other programming language. Recorded macros are useful to Excel users of all skill levels, from those creating or working with simple spreadsheets to those who use Excels most advanced tools. Even Excel developers, skilled at writing VBA programs, find occasional use for this valuable tool. for Educational Use Only Whats Inside? This document is about recording macros in Microsoft Excel. It describes the process of recording a macro and illustrates different techniques with step-by-step practical exercises. It explains the different ways of running macros and introduces the Visual Basic Editor, Excels tool for editing the programming code behind the macros. It concludes with some step-by-step exercises in editing existing macros and writing VBA code to create new ones. Each section is illustrated with helpful screenshots throughout. The material in this book is relevant to all recent versions of Microsoft Excel from Excel 97 onwards. Introducing Recorded Macros What is a Macro? A macro is a collection of commands written in the Visual Basic programming language. When is macro is run the commands are executed and perform their various tasks. Macros are used to carry out routine, repetitive or laborious tasks automatically and with speed. Macros can be written by hand using the Visual Basic Editor which is included as part of most Microsoft Office programs. Some Microsoft Office programs (Excel, Word, PowerPoint) have a Macro Recorder. This tool lets you create a macro without requiring any knowledge of Visual Basic programming. It works by recording your actions as you perform a task in the program. You can save the recorded macro and play it back to have the same task performed automatically. Although you can record and use macros without any knowledge of Visual Basic programming, with a little skill you can edit or modify recorded macros to improve their power and functionality. This document will show you, with the help of some practical examples, how to record a macro in Microsoft Excel, how to carry out some simple editing of recorded macros using the Visual Basic Editor, and how to assign a macro to a menu item or toolbar button. What a Recorded Macro Can Do and What It Cant A macro records commands. The commands can be made by clicking a button or choosing a menu item with the mouse, or you can use keyboard shortcuts. It makes no difference to what is recorded or how the macro performs. The Macro Recorder can record almost everything you do with the mouse or keyboard but it has its limitations... © Martin Green www.fontstuff.com 4
  5. 5. Recording Excel Macros • It can not create looping code - code which when executed will repeat as many times as is necessary to perform a task. • It can not create conditional code – in Visual Basic conditional statements are used to determine how code is executed. • It can not create code that interacts with the user. The Visual Basic programmer can include messages and dialogs into their programs to provide information to and gather information from the user. But despite its limitations the Macro Recorder is a very useful tool...University of Greenwich Students Edition • The Macro Recorder can be used very successfully without any knowledge of programming. • The Macro Recorder is an excellent learning tool for VBA programming. • Even experienced developers occasionally use the Macro Recorder to quickly create code procedures, especially those that are quick to record but complex to write such as those involving charts or pivot tables. The macro recorder records commands, not the time taken to carry them out so the length for Educational Use Only of time it takes to record a macro is largely irrelevant. Timing can become a factor in hand- written VBA code but you can not record time intervals or pauses. Visual Basic or VBA? Visual Basic is a long-standing and established programming language developed from an early computer programming language called Basic. Visual Basic can be used to create many different types of "standalone" programs which can function independently. There have been many versions of Visual Basic, the last being Visual Basic 6 (VB6). After VB6 Visual Basic became part of Microsofts .NET programming platform in the form of VB.NET although its form is largely unchanged. Visual Basic for Applications (VBA) is a subset of the Visual Basic programming language for use within Microsoft Office applications. Each component of Microsoft Office has its own version of VBA and all are compatible with each other allowing the programmer to control not only the host program but also other Microsoft Office programs from one application. Unlike Visual Basic, VBA can not create standalone programs. VBA code has to run from within a Microsoft Office host application. In practice there is little difference between Visual Basic and VBA. The differences lie in the way that the code is hosted and executed. About Macro Security Opening Files Containing VBA Code Everyone working with macros should be aware of the security implications of working with files containing code. Unscrupulous people can create malicious code such as viruses and distribute it embedded in innocent-looking files such as Word documents and Excel workbooks. For this reason all Microsoft Office programs are equipped with security measures to detect whether or not a file contains programming code at the point at which the file is opened. If the program detects code in a file a warning message is displayed (Fig. 1). The dialog allows you to disable the code before opening the file if you wish. © Martin Green www.fontstuff.com 5
  6. 6. Recording Excel MacrosUniversity of Greenwich Students Edition Fig. 1 A macro security warning message The fact that you see this message does not mean that malicious code has been detected, merely that code is present. If you know that there are macros in the file (perhaps you or a colleague has created it) then it should be safe to enable the macros and proceed with opening the file. If you were not expecting the file to contain macros (perhaps it was sent to you from for Educational Use Only someone else) then you should, at least in the first instance, disable the macros. Disabling safe macros may impair the functioning of the file. If this is the case and you are still unsure of the files safety, have your anti-virus software check the file first. Providing your anti-virus software is up-to-date and it reports that the file is "clean" then it should be safe to open with macros enabled. Setting the Programs Security Level If you regularly record or write and use macros the security level of the program you are working in should be set to Medium. You can find out more about security options and set your chosen security level by visiting the Security dialog (Fig. 2) (Tools > Macro > Security). This offers three levels of security. The highest level will automatically disable "unsigned" macros, only allowing macros from "trusted" sources to be run. A signed macro is one to which an electronic security certificate is attached and you can specify which certificate holders you trust. Certificates are issued by respected IT security organisations such as Verisign™ Fig. 2 The Security dialog The lowest level of macro security is not recommended as it offers no protection from unsafe macros. If you have a brand new installation of Microsoft Office you might find (depending on which version of Microsoft Office you are using) that the default security level is set to High. If this © Martin Green www.fontstuff.com 6
  7. 7. Recording Excel Macros is the case you will see a different message when you attempt to open a file containing macros (Fig. 3).University of Greenwich Students Edition Fig. 3 This message is displayed when the security is set to High. This message does not give you the option to enable the files macros. If you want to make use of the code in the file you must set the programs security level to Medium then close the file. When you reopen the file you will see the usual message (Fig. 1) allowing you to enable its macros. Emailing Files Containing Code The proliferation of viruses in recent times has resulted in increased email security measures for Educational Use Only and you must bear this in mind when sending or receiving files containing macros. Recent versions of email programs such as Microsoft Outlook can detect whether or not files attached to email messages contain code and may strip these attachments from the message. Sometimes these measures are implemented at the email post office. Either way the user usually can not change the built-in security settings. When sending files containing macros it is a wise precaution to pack them into a .zip file. This has the result of effectively "hiding" the code from the email security and also rendering the file "safe" for the recipient at Inbox level. If you are emailing a file containing macros to someone you should always warn them that this is the case. You should always virus-check any file that you receive from someone else which contains macros, even if they are trusted by you. If you find that even "zipping" your code-containing files is not enough (some email security software has the ability to look inside .zip files) make use of your zipping programs option to encrypt the file, then include the password for decrypting the file in the email message. Starting and Stopping the Macro Recorder The Macro Recorder works the same way in all the Microsoft Office programs in which macro recording is available. To start the Macro Recorder open the Tools menu and choose Macro > Record New Macro. This opens the Record Macro dialog box (Fig. 4) where you can choose various macro options. The Macro Recorder does not start recording your actions until you click the OK button on the Record Macro dialog. Fig. 4 The Record Macro dialog box in Microsoft Excel. As soon as recording commences the Stop Recording toolbar (Fig. 5) is displayed. This toolbar carries a button to stop the Macro Recorder when you want to finish recording. If the Stop Recording toolbar is not visible you can stop the Macro Recorder by opening the Tools menu and choosing Macro > Stop Recording. © Martin Green www.fontstuff.com 7
  8. 8. Recording Excel Macros Fig. 5 The Stop Recording toolbar. Although the general principles of macro recording are the same in each of the programs in which it is available there are some differences between them. • The appearance of Record Macro dialog box differs in each program to reflect thatUniversity of Greenwich Students Edition programs abilities and requirements. • The Stop Recording toolbar in Excel displays a button for specifying the recording of relative or absolute cell references. In Word there is a Pause button. PowerPoint has only the Stop button. • In Excel the word Recording is displayed in the Status Bar whilst recording is in progress. Neither Word nor PowerPoint do this but in Word the appearance of the mouse pointer is different during recording. for Educational Use Only The Visual Basic Toolbar If you are a regular user of the Macro Recorder you might find it useful to display the Visual Basic Toolbar (Fig. 6) (open the View menu and choose Toolbars > Visual Basic). This toolbar carries several useful buttons saving the effort of multi-click visits to the Tools menu. Fig. 6 The Visual Basic toolbar © Martin Green www.fontstuff.com 8
  9. 9. Recording Excel Macros Recording Macros In this section the principles of recording and editing macros a illustrated with a few simple examples. NOTE: The VBA code recorded in the following exercises, and how to view and edit it, is explained in the section Editing Recorded Macros later in this document. About the ExercisesUniversity of Greenwich Students Edition My experience of training IT in a classroom has taught me that even the most intelligent of people can get confused when following instructions in a subject new to them. When doing an exercise from a book such as this it can be even more confusing since individual authors have their own way of saying things. So here is an explanation of the conventions I have used for the Step-by-Step exercises in this document. Please take a moment to read it before embarking on the exercises to make sure you understand exactly what Im asking you to do. Follow the instructions exactly. Read the instructions carefully and do exactly what they for Educational Use Only say. Take care when typing. Remember that the computer takes all your instructions literally. Things you have to do are highlighted grey. I explain and illustrate the process as the exercise proceeds so to distinguish my text from your practical instructions everything you need to do has a grey background like this. Instructions are sequentially numbered. So that you can keep track of where you are in an exercise each step is numbered e.g. Step 1, Step 2 and so on. "Click" means on the screen. If you have to "click" something it means with your mouse on the screen, such as a button on a dialog box e.g. Click OK or Click the OK button. Unless otherwise stated, mouse clicks are made with the primary (usually the left) mouse button. If it is required to use the secondary (usually the right) mouse button you will be asked to right-click. "Press" means on the keyboard. If you have to "press" something it means a key on the keyboard e.g. Press [Enter] or Press the Enter key. When Key presses or keyboard shortcuts are required special key names are enclosed in square brackets e.g. [Enter]. When combinations of key presses are required they are written thus [Control]+[Enter]. This means hold down the Control key whilst pressing the Enter key. Function keys are indicated thus: [F8] , [F11] etc. Choosing menu items is usually indicated by Open the Tools menu and choose Macro then Macros. Sometimes this is shortened to Go to... or Choose Tools > Macro > Macros. If you dont understand an instruction dont panic! None of these exercises can harm Excel or your computer. I recommend that, at least to begin with, you always carry out the practice exercises in a new workbook. If things go wrong you can simply stop the exercise, throw away the workbook, and start again. These exercises have been thoroughly checked and tested. If you find an error in one of them please let the author know about it. For contact details see: About the Author on page 52. © Martin Green www.fontstuff.com 9
  10. 10. Recording Excel Macros Step-by-Step: Record a Simple Macro This simple exercise demonstrates how the Macro Recorder works. Later you will find out how you can view and modify the code it creates. Take care to follow the instructions exactly! Step 1: Start Microsoft Excel and in a new, empty workbook type a piece of text (such as your name) in a cell. Any cell will do. Step 2: Press [Enter] to accept your typing then click on the cell to select it.University of Greenwich Students Edition Your worksheet will look something like this: for Educational Use Only A cell containing text is selected Step 3: Open the Tools menu and choose Macro > Record New Macro. Step 4: When the Record Macro dialog box appears click its OK button to dismiss it. When you do so a small toolbar with just two buttons (the Stop Recording toolbar) appears... The Stop Recording toolbar. Step 5: On Excels formatting toolbar click the Bold and Center buttons, then choose a Fill Color and a Font Color. Bold, Center, Fill Color and Font Color toolbar buttons Step 6: Click the Stop button (the one on the left) on the Stop Recording toolbar. The formatted cell Step 7: Save the workbook. This completes this Step-by-Step exercise. The Macro Recorder recorded all your actions within Excel from the point at which you clicked the OK button on the Record Macro dialog box until the point when you clicked the Stop button on the Stop Recording toolbar. © Martin Green www.fontstuff.com 10
  11. 11. Recording Excel Macros Whilst the Macro Recorder was active the word Recording was displayed in the Status Bar at the bottom of the Excel window (Fig. 7). If you can still see this message it means that you did not switch off the Macro Recorder – you may have closed the toolbar by mistake. If this is the case open the Tools menu and choose Macro > Stop Recording.University of Greenwich Students Edition Fig. 7 The Status bar indicates that recording is in progress. The action of saving the workbook in this case also saves the macro, because in the Record Macro dialog box the option was to store the macro in This Workbook. The appropriate place to store macros is covered later (see: Where Should the Macro be Stored? on page 26). In the next exercise you test the macro by playing it back. This is called "running" the macro. for Educational Use Only © Martin Green www.fontstuff.com 11
  12. 12. Recording Excel Macros Step-by-Step: Test the Macro You should always test your macros in several different circumstances to make sure they work as you intended. This exercise tests the macro you recorded in the previous section: Step 1: In the same workbook as you recorded the macro in the previous exercise, select a block of cells and fill them with text. HINT: A quick way to do this is to select the cells and type your text (you will see the text appear in just the "active" cell of the selection) then press [Control]+[Enter]. This is the Block Fill command and will fill all the selected cells with your typing.University of Greenwich Students Edition Step 2: Select a different block of cells, including some of those containing the text you just entered. for Educational Use Only Select a different block of cells Step 3: From the Tools menu choose Macro then Macros to open the Macro dialog box. You will see the name of the macro that you recorded in the previous exercise ("Macro1"). Click on it to select it and click Run. Select the macro name and click Run All the selected cells have now been formatted by the macro. Step 4: Select one of the empty cells that you had selected (you can see that the macro has correctly formatted the cells fill color). Type some text into the cell. This completes this Step-by-Step exercise. The text you type appears bold, centred and coloured showing that the macro has formatted all the selected cells correctly. The macro formatted all the selected cells even though some of the formatting was not evident until the cells contained data (Fig. 8). Fig. 8 The result of running the macro. Since the selection of the cells was not recorded, the macro works on any cell or cells that are selected when it is run. © Martin Green www.fontstuff.com 12
  13. 13. Recording Excel Macros Step-by-Step: Record and Test a More Complex Macro The previous example was a very simple one and intended to show the principles of recording macros. This example is more complex and requires more steps. It shows how useful and time-saving a macro can be. Acknowledgement: This macro was inspired by an example in Excel 97 Visual Basic Step by Step by Reed Jacobson (Microsoft Press ISBN: 1-57231-318-8). I used this excellent book when I started learning VBA and highly recommend it for anyone embarking on this fascinating subject.University of Greenwich Students Edition The data on this worksheet contains a number of empty cells. Whilst the data is easy to read and understand, these cells must be filled before the data can be analysed with Excel. To you and I the figure of £1,949.00 in cell C4 clearly belongs to the South region and is part of the January data. for Educational Use Only But as far a Excel is concerned it is simply a number sitting on its own in row 4. Excel understands that it is probably related to the rest of the numbers in column C but there isnt any other information in the same row to tell Excel how it relates to the rest of the data. The solution is to fill each empty cell with data from the cell above. So each empty cell under January should also contain the text January, the empty cells under South should also contain the text South and so on. Each row of data will then contain all the Fig. 9 Sample data for the More Complex information it needs. Macro The macro you record in this exercise will fill the empty cells in a block of data of any size or shape using the rule that each empty cell should hold the same data as the first non-empty one above it. First, prepare a worksheet containing data similar to that shown in the screenshot above (Fig. 9). You might also find it useful to copy the data on to another sheet so that you can test the macro later. Then follow these step-by-step instructions to record the macro... Step 1: Select any cell that contains some data (i.e. not an empty cell). Step 2: Open the Tools menu and choose Macro > Record New Macro. Step 3: In the Record Macro dialog box enter the name FillEmptyCells in the Macro name text box. Choose Personal Macro Workbook from the Store macro in drop-down list. Type a brief description of the macro in the Description text box, for example: Fills each empty cell in a selection with data from the cell above. © Martin Green www.fontstuff.com 13
  14. 14. Recording Excel MacrosUniversity of Greenwich Students Edition Enter the macro options Step 4: Click the OK button on the Record Macro dialog box to start recording the macro. Step 5: Open the Edit menu and choose Go To. On the Go To dialog box click the button for Educational Use Only marked Special then in the Go To Special dialog choose Current Region and click OK. This selects a rectangle of cells entirely enclosing the data. HINT: You can quickly perform this sequence of actions by using the keyboard shortcut [Control]+* (or [Control]+[Shift]+8). Step 6: Open the Edit menu and choose Go To. In the Go To dialog box click the button marked Special then in the Go To Special dialog choose Blanks and click OK. This creates a multiple selection of just the empty cells within the previous selection. In the next step you will type a formula then use the Block Fill command to enter it into all the empty cells. Step 7: Type an Equals Sign then click the Up Arrow key on your keyboard, then press [Control]+[Enter]. This has the effect of filling each selected cell with a formula which displays the value displayed in the cell above it. Step 8: Press [Control]+[Shift]+8 to select the current region again. Step 9: On the Edit menu choose Copy (or click the Copy button on the toolbar or press [Control]+C). Step 10: On the Edit menu choose Paste Special then in the Paste Special dialog box choose Values and click OK. Step 11: Press the [Escape] key to take Excel out of Copy Mode. Step 12: Click the Stop button on the Stop Recording toolbar. Before testing the macro create another set of data containing gaps, similar to the one you used when recording the macro (NOTE: the block of data should contain no completely empty columns or rows) or switch to the worksheet containing a copy of your test data if you made one). Then proceed to test the macro as follows... Step 13: Select a non-empty cell within the data. Step 14: From the Tools menu choose Macro then Macros to open the Macro dialog box. HINT: You can use the keyboard shortcut [Alt]+[F8] to open the Macro dialog box. Step 15: Select the FillEmptyCells macro from the list. Note that because this macro was stored in a different workbook (the Personal Macro Workbook) the workbooks name is shown in front of the macro name. © Martin Green www.fontstuff.com 14
  15. 15. Recording Excel Macros Select the macro from the list Step 16: Click the Run button on the Macro dialog box.University of Greenwich Students Edition This concludes this Step-by-Step exercise. If you have recorded the macro correctly, all the empty cells in the block of data will now be filled. for Educational Use Only © Martin Green www.fontstuff.com 15
  16. 16. Recording Excel Macros Tips for Recording Macros Get More Familiar with Excel You dont need to be an Excel expert to create useful and time-saving macros, but as you learn more about Excel you will be able to build more powerful macros. The previous exercise used a number of tools that are very handy when recording macros but many users have never come across them. Particularly useful is the Go To Special command (Fig. 10) which lets you select cells according to certain predefined criteria, andUniversity of Greenwich Students Edition the Paste Special command (Fig. 9) which allows you to specify different options for pasting copied data or objects. for Educational Use Only Fig. 11 The Paste Special dialog. Fig. 10 The Go To Special dialog. Plan the Macro Even when recording simple macros it is easy to forget a step or to do things in the wrong order. Before recording a new macro it is a good idea to do a "practice run" first to familiarize yourself with exactly what you have to do. If the macro contains many steps write a list of actions that you can follow when you are recording. Generalize Your Commands Try to generalize your commands wherever possible. This makes the resulting macro flexible and suitable for use in different circumstances. Commands like Go To > Special > Current Region and Go To > Special > Blanks, as used in one of the earlier exercises, are good examples of non-specific commands. If you had manually selected the block of data or the empty cells, that specific selection would have been recorded into the macro (see: Relative or Absolute References? on page 17). Movement keys (the Up, Down, Left and Right Arrow keys) either on their own or in conjunction with the [Control] key (for moving to the end of a row or column of data) and/or the [Shift] key (for selecting cells as you move) are particularly useful in this respect. Correcting Mistakes Remember that the macro recorder does not record time so there is no need to hurry through a procedure when recording a macro. Take your time and try to be as accurate as possible. Nevertheless, it is easy to make a mistake whilst recording a macro. If this happens, don’t panic! If you can immediately undo your mistake (using the Undo button on the toolbar or with the keyboard shortcut [Control]+Z) you should do so and then carry on as normal. If you immediately undo an action this way you will probably find that the Macro Recorder does not include it in the final code. Sometimes it is unable to do this and your resulting © Martin Green www.fontstuff.com 16
  17. 17. Recording Excel Macros macro carries out your mistakes then undoes them just as you did when recording it. If this happens you can edit out the unnecessary lines of code later (see: Editing Recorded Macros on page 29). Sometimes you will just get into a mess and have to stop recording and start again. When you do this, and specify the same name for the macro that you just used, Excel will ask you if you want to replace the existing macro (Fig. 12). Answer Yes to discard the original macro and replace it with the new one.University of Greenwich Students Edition Fig. 12 Excel warns you if a macro name already exists. Relative or Absolute References? for Educational Use Only When recording macros it is usually advisable to generalise commands wherever possible so that they refer, for example, to the selected cell or cells rather than to a specific cell or selection of cells. Doing this means that the macro will behave in a similar way whenever it is used and in different circumstances. But sometimes you will want to specify a particular cell (or range of cells, column, row or worksheet). This distinction between using generalisations or specifics is referred to as using Relative or Absolute references and the principle is similar to that of writing formulas on a worksheet. For example, if you were to write a formula in cell A1 that read: =B1+C3 and then copied that cell and pasted it on to cell D5 you would see that the formula changed automatically to =E5+F7. This is because cell references in formulas are by default relative and change when a formula is moved or copied so that the formula refers to the same cells relative to its new position. What the formula really says is "the cell one column to my right in the same row plus the cell two columns to my right and two rows down". If you want the formula always to refer to the same cells wherever it occurs you must use absolute cell references. When writing formulas absolute cell references are denoted by a dollar sign before the row and/or column part of the reference. So, if you were to write a formula in cell A1 that read: =$B$1+$C$3 it would remain unchanged wherever it was copied or moved to. Often, just part of a formula needs to be "frozen" in this way so writing the formula =$B$1+C3 in cell A1 then copying it to cell D5 would result in =$B$1+F7. This formula really says "the cell B1 plus the cell two columns to my right and two rows down". The same principle applies to recording macros with an important difference. By default all cell references are recorded as absolute unless you tell Excel otherwise. If whilst recording your macro you click on, for example, cell B5 the macro will record that you want cell B5 to be selected. If, however, you have told Excel that you want to record relative references then the macro will record that you wanted to select a cell a certain number of rows and columns away from the current selection. To determine whether or not the macro records relative or absolute references there is a button on the Stop Recording toolbar (Fig. 13). When you start recording your macro the button is not pressed in and the macro is expecting to record absolute references. If you click the button the macro will record relative references until it is clicked again. Sometimes you will want all the macros references to be relative and sometimes only certain ones. Use the Relative References button to switch the feature on and of as required. Fig. 13 The Stop Recording toolbar with the Stop button (left) and Relative References button (right). The next exercise demonstrates the use of this feature when recording a macro. © Martin Green www.fontstuff.com 17
  18. 18. Recording Excel Macros Step-by-Step: Compare Relative and Absolute References The following exercise uses a couple of simple examples to demonstrate how this works... Step 1: Start Excel and open a new, empty workbook. Step 2: Select cell C10. Step 3: From the Tools menu choose Macro then Record New Macro. Step 4: In the Record Macro dialog box enter the name AbsoluteReferences, choose toUniversity of Greenwich Students Edition store the macro in This Workbook and then click the OK button. Step 5: Select cell B5. Step 6: Click the Stop button on the Stop Recording toolbar. Step 7: Select cell C10 again. Step 8: From the Tools menu choose Macro then Record New Macro. Step 9: In the Record Macro dialog box enter the name RelativeReferences, choose to for Educational Use Only store the macro in This Workbook and then click the OK button Step 10: Click the Relative References button on the Stop Recording toolbar. Step 11: Select cell B5. Step 12: Click the Stop button on the Stop Recording toolbar. You now have two macros which recorded identical actions (the selecting of cell C5) but in different ways. The first recorded absolute references and the second recorded relative references. Now test the two macros to see how each works... Step 13: Select cell I15. Step 14: Use the keyboard shortcut [Alt]+[F8] to open the Macro dialog box. Choose the AbsoluteReferences macro and click the Run button. Which cell did the macro select? Step 15: Select cell I15 again. Step 16: Use the keyboard shortcut [Alt]+[F8] to open the Macro dialog box. Choose the RelativeReferences macro and click the Run button. Which cell did the macro select? Step 17: Select cell E2 and run the AbsoluteReferences macro. Which cell did the macro select? Step 18: Select cell E2 again and run the RelativeReferences macro. You got an error! Step 19: Click the End button on the Microsoft Visual Basic error message box. This concludes this Step-by-Step exercise. The way the two macros behaved when they were run demonstrates the difference between recording absolute and relative references. The AbsoluteReferences macro noted the address of the cell B5 when you clicked on it so when you ran that macro it always selected cell B5. But when you clicked on cell B5 when you were recording the RelativeReferences macro it noted the cells location relative to the previous selection (i.e. one column to the left and five rows up) so when you ran this macro from cell I15 it selected cell H10. But when you tried to run the macro from cell E2 there was an Error. Macro errors occur when for some reason a macro can not execute a line of VBA code. The code in this macro told Excel to select a cell five rows above row 2 and since there is only one row above this row Excel couldnt do as it © Martin Green www.fontstuff.com 18
  19. 19. Recording Excel Macros was instructed and an error resulted. Clicking the End button aborted the macro at that point. When writing VBA code conscientious programmers rigorously test their work in an effort to ensure that errors will not occur when the code is being used, and they include error handling procedures to deal with both expected and unforeseen errors.University of Greenwich Students Edition for Educational Use Only © Martin Green www.fontstuff.com 19
  20. 20. Recording Excel Macros Running Macros Different Ways to Run a Macro There are several different ways to run a macro. Choose the method that is the most convenient to you. The Macro Dialog Using the macros dialog requires no prior preparation. Open the Macro dialog (Fig. 14) fromUniversity of Greenwich Students Edition the Tools menu by choosing Macro then Macros (or use the keyboard shortcut [Alt]+[F8]) then select a macro from the list and click the Run button. for Educational Use Only Fig. 14 Running a macro from the Macro dialog box. The Macro dialog box lists all the macros currently available. The names of macros stored in workbooks other than the current one are prefixed by the name of their host workbook. In the illustration above (Fig. 14) you can see that the FillEmptyCells macro is located in the PERSONAL.XLS workbook (the Personal Macro Workbook). If there are a lot of macros in the list, you can refine it by choosing to show Macros in: All Open Workbooks (the default setting), This Workbook or PERSONAL.XLS. Note that The Description area at the bottom of the dialog box displays any description that you might have entered in the Record Macro dialog box prior to recording the macro. If you did not add a description at the time of recording your macro you can do this later (see: Changing Macro Options on page 28). Toolbar Button Excels Customize tool offers the ability to create a custom toolbar button to which you can assign a macro. Access the tool from the Tools menu by choosing Customize or right-click on any existing toolbar and choose Customize from the context menu. In the Customize dialog box select the Commands tab then scroll down the Categories list in the left-hand list box until you find the Macros entry (it is near the bottom - the list items are not in alphabetical order!). Click on Macros to reveal a list of commands on the right- hand list box (Fig. 15). One of the commands is Custom Button. © Martin Green www.fontstuff.com 20
  21. 21. Recording Excel MacrosUniversity of Greenwich Students Edition for Educational Use Only Fig. 15 The Customize dialog box. To add a button drag Custom Button from the dialog box to a position on one of your toolbars then release the mouse button to place the new button on the toolbar (Fig. 16). You can rearrange and edit your toolbars and menus as much as you want when the Customize dialog is open... Fig. 16 Placing a custom button on a toolbar. To remove a custom button from a toolbar open the Customize dialog and simply drag the button off the toolbar. When the mouse pointer displays an X release the mouse to remove the button (Fig. 17). Alternatively right-click on the button you want to remove and choose Delete from the context menu. Fig. 17 Dragging a button off the toolbar. Whilst the Customize dialog is still open right-click on the custom button for a menu of options... Assign Macro: opens the Assign Macro dialog box which is similar in appearance to the Macro dialog box (Fig. 14). Choose a macro from the list and click the OK button to assign the macro to the button. Name: enter a name for the custom button. This text will appear as a tool tip when the user points at the button. © Martin Green www.fontstuff.com 21
  22. 22. Recording Excel Macros Change Button Image: offers a selection of alternative ready-made images to display on the button in place of the default "smiley". Alternatively you can use... Copy Button Image: to copy the image used on an existing button. Right click on that button and choose Copy Button Image then right-click on your custom button and choose Paste Button Image. Edit Button Image: opens the Button Editor tool with which you can design a unique button image yourself (Fig. 18). Choose a colour from the palette by clicking on it then use the mouse as a brush to paint the colour on to the design grid.University of Greenwich Students Edition for Educational Use Only Fig. 18 The Button Editor lets you design your own button images. Having made your changes to the buttons properties click the Close button on the Customize dialog box to take Excel out of customize mode and enable the button. You can return to customize mode at any time to make further changes to this or other toolbar and menu items. You might prefer to create a new toolbar to hold your macro buttons rather than place them on an existing toolbar. You will find the facility to create new toolbars on the Toolbars tab of the Customize dialog box. There is also the facility here to Reset built-in toolbars to their original "factory" condition. Menu Item A macro can be assigned to a menu (either an existing one or a new one) instead of, or in addition to assigning it to a toolbar button. First open the Customize dialog from the Tools menu and click on the Commands tab. If you want to create a new menu choose New Menu from the Categories list. Only one item, New Menu, will appear in the Commands list. Drag New Menu on to the existing menubar or one of your toolbars (Fig. 19) (NOTE: a toolbar, properly called a "command bar", can contain both buttons and menus). Fig. 19 Drag a new menu on to the menubar. Right-click on the new menu and enter a caption in the Name text box. If you want to add an accelerator key to the name (i.e. a letter that appears underlined so the user can open the menu by typing that letter in conjunction with the [Alt] key) place an ampersand before that letter in the name. © Martin Green www.fontstuff.com 22
  23. 23. Recording Excel Macros So, typing &Macros in the Name textbox would produce the caption Macros. The user can then use the keyboard shortcut [Alt]+M to open the Macros menu. To add your macros to the new menu (or any existing menu) return to the Customize dialog and choose Macros from the categories list. Drag Custom Menu Item from the Commands list on to the menu of your choice and wait for a moment whilst the menu opens. You can then place the new menu item where you like on the menu. (NOTE: a new menu without any existing entries opens as a small rectangle. Drop the first menu item on to this to create the menu (Fig. 20)).University of Greenwich Students Edition Fig. 20 Add accustom menu item to the menu The new menu item appears with the caption Custom Menu Item. Right-click on it and use the Name property to add a more suitable caption. Its other properties can be changed for Educational Use Only using the options on the context menu in the same way as for a custom button (see: Toolbar Button on page 20). Close the Customize dialog box to implement your changes and activate the new menu and its contents. Worksheet Button An alternative to using menus and toolbars is to place a button directly on a worksheet. This is particularly advantageous when the macro resides in the same workbook because if you take the workbook to a different computer the button goes with it. Fig. 21 The Forms toolbar. To place a button on a worksheet you first need to open the Forms toolbar (View > Toolbars > Forms)(Fig. 21). Click the Button button then click on the worksheet near where you want to place the button. When you do this the Assign Macro dialog box opens and you can choose the macro that will run when the button is clicked (Fig. 22). Fig. 22 The Assign Macro dialog appears when a button is created. Buttons are automatically named and numbered sequentially. Notice that the default macro assignment for a button is the click event of the button (e.g. for a button named Button1 the default is Button1_Click). This macro event can be used when you are writing your own VBA macros. You can safely ignore this and choose a macro from the list. If you prefer not to assign a macro straight away, or if you change your mind later and want to assign a different macro, the macro assignment can be changed at any time by right- clicking on the button and choosing Assign Macro from the context menu. To make changes to the button it must be selected (when a cross-hatched or dotted border is visible). If the button is not selected, select it by either right-clicking on it or left-clicking on it with the [Control] key held down. Avoid left-clicking the button unless you want to run © Martin Green www.fontstuff.com 23
  24. 24. Recording Excel Macros the macro. A button has two selection modes. When normally selected (Fig. 23 left) it shows a dotted border and the right-click context menu is fully enabled. If you click on the button face the border changes to cross-hatching (Fig. 23 right) and you can type directly on the button to change its caption. In this mode the Assign Macro option of the right-click context menu is disabled.University of Greenwich Students Edition Fig. 23 The two selection modes of a button. You can move a selected button by dragging its border (Fig. 24). To change the size or shape of a button drag one of the resizing handles located around its edge (Fig. 25). Hold the [Alt] key down whilst dragging to "snap" the button on to worksheet gridlines. for Educational Use Only Fig. 24 Moving a button by dragging. Fig. 25 Resizing a button. Graphic Object Most graphic objects (e.g. AutoShapes, inserted images or clip-art) can have a macro assigned to them so that the macro runs when the object is clicked. After placing the object on the worksheet right-click on it and choose Assign Macro from the context menu (Fig. 26). Fig. 26 Assigning a macro to a graphic object. Assigning a Shortcut Key The macro recorder offers you the opportunity to assign a shortcut key to a macro before you record it. If you didnt do that, or change your mind and want to assign one later, open the Macro Options dialog by going to Tools > Macro > Macros then select your macro and click the Options button. In the Macro Options dialog box (Fig. 27) click in the small text box by the heading Shortcut key and type a letter. That letter when typed with the [Control] key held down will then run the macro. Remember that many key combinations are already assigned to routine tasks (e.g. [Control]+P for Print, [Control]+S for Save) and any assignment you make will override these. (NOTE: ask Excel Help about keyboard shortcuts to see a list of the current key assignments.) You can extend the choice of keystrokes by holding down the [Shift] key whilst typing your chosen letter into the dialog box. Your shortcut key for the macro then becomes [Control]+[Shift]+letter. © Martin Green www.fontstuff.com 24
  25. 25. Recording Excel MacrosUniversity of Greenwich Students Edition Fig. 27 The Macro Options dialog box. You can also use the Macro Options dialog to add or change a macros description. Automatic Macros for Educational Use Only Macros can be run automatically when a certain event happens in Excel. The VBA programmer can choose from a wide variety of workbook and worksheet events but unless you are familiar with VBA you are limited to just two, the Auto_Open and Auto_Close macros. How to do this is explained in full below (see: Auto Macros on page 26). Which Way is Best? The most appropriate way to run a macro depends upon where it is located and how convenient it needs to be. All macros are always available from the Macros dialog (Tools > Macro > Macros or [Alt]+[F8]). Assigning macros to toolbar buttons or menu items is user-friendly and very convenient but they do not travel with the workbook when, for example, you email it to another user or access it from a different computer. (NOTE: It is possible to write VBA code which builds menus or toolbars automatically. This code can be embedded in the workbook so that it essentially takes its own toolbars and menus with it wherever it goes. This topic is not within the scope of this document.) Keyboard shortcuts are quick and easy but have to be remembered, and the choice is limited if you dont want to overwrite existing key assignments. Remember that keyboard assignments made in the way shown here are specific to the current computer and do not travel with the workbook. (NOTE: It is possible to write VBA code which assigns a keyboard shortcut to a macro. Developers often use this to temporarily assign a keyboard shortcut whilst the host workbook is open. As with toolbar/menu code this travels with the workbook. This topic is not within the scope of this document.) If it is possible, the most flexible method for the novice programmer is to assign a macro to a button or other graphic object on the worksheet itself. Since this object is part of the workbook it is always available regardless of which computer opens the file. Use the method that is most convenient for you. You can use more than one method if you prefer (e.g. a separate button on each worksheet within a workbook, each running the same macro). Undoing a Macros Actions It is very important to remember that the action of a macro can not be undone by using Excels Undo command. The running of a macro effectively clears the Undo memory and both the Edit > Undo menu option and the Undo toolbar button are disabled immediately following the macro. It is often good practice to save the workbook before running a complex macro so that the macros actions can be undone simply by closing the workbook without saving the changes, then reopening it in its original state. © Martin Green www.fontstuff.com 25

×