Descripción: How to use effectively Macros in Excel...
VBA Handbook
Recording Excel Macros Learn to Record and Edit VBA Macros In Microsoft Excel
By Martin Green
Recording Excel Macros
Contents
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
About This Book......................... Book...................................... ........................... ............................ ............................ .......................... ..........................4 ..............4 Who is it for?................................ for?............................................. ........................... ............................ ............................ .......................... ...................4 .......4 What's Inside?..................... Inside?................................... .......................... .......................... ............................. ........................... .......................... ................ .. 4 Introducing Recorded Macros.................. Macros............................... ........................... ............................ ............................. ........................... .............. .. 4 What is a Macro? ............................. ......................................... .......................... ............................ ............................ .......................... ................. .....4 4 What a Recorded Macro Can Do and What It Can't ......................... ....................................... ............................ ................ 4 Visual Basic or VBA?............................... VBA?............................................ ........................... ............................ .......................... ........................5 ............5 About Macro Security ........................... ........................................ ........................... ............................ ............................ ..........................5 ............5 Opening Files Containing VBA Code ........................... ......................................... ............................ ............................ ................ 5 Setting the Program's Security Level............................... Level............................................. ............................ ........................6 ..........6 Emailing Files Containing Code......................... Code....................................... ............................ ............................ ........................7 ..........7 Starting and Stopping the Macro Recorder ........................... ......................................... ............................ ........................7 ..........7 The Visual Basic Toolbar ........................... ........................................ ........................... ............................ ........................... ......................8 .........8 Recording Macros.............. Macros ............................ .......................... .......................... ............................. ............................. .......................... .....................9 .........9 About the Exercises..................... Exercises................................. .......................... ............................ ............................. ........................... .....................9 .........9 Step-by-Step: Record a Simple Macro .......................... ........................................ ............................ ........................... ............... .. 10 Step-by-Step: Test the Macro........................ Macro...................................... ............................ ............................ .......................... ............... ... 12 Step-by-Step: Record and Test a More Complex Macro...................................... 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............................... Dialog............................................ ........................... ............................ ............................ ...................... ........ 20 Toolbar Button ........................... ........................................ ........................... ............................ ............................ .......................... ............... ... 20 Menu Item.................................. Item.............................................. .......................... ............................ ............................ .......................... ............... ... 22 Worksheet Button................... Button................................. .......................... .......................... ............................ ........................... .................... ....... 23 Graphic Object ........................... ........................................ ........................... ............................ ............................ .......................... ............... ... 24 Assigning a Shortcut Key...................... Key................................... ........................... ............................ ............................ .................... ...... 24 Automatic Macros ............................ ........................................ ........................... ............................. ............................ ........................ .......... 25 Which Way is Best? ........................... ........................................ ........................... ............................ ............................ ...................... ........ 25 Undoing a Macro's Actions .......................... ........................................ ............................ ............................ .......................... ................. ..... 25 Macro Options.......................... Options....................................... .......................... ............................ ............................. .......................... .......................... .............. 26 Macro Names ........................... ........................................ .......................... ........................... ............................ .......................... ...................... .......... 26 Auto Macros ............................. ......................................... .......................... ............................ ............................ .......................... ...................... .......... 26 Where Should the Macro be Stored? .......................... ........................................ ............................. ............................. ................. ... 26 Personal Macro Workbook.......................... Workbook....................................... ........................... ............................ .......................... ............... ... 27 This Workbook ........................... ........................................ ........................... ............................ ............................ .......................... ............... ... 27 New Workbook.................... Workbook.................................. ........................... ........................... ............................ ............................ ...................... ........ 27 Summary and Other Options............................ 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 E ditor .......................... ........................................ ............................ ............................ .................... ...... 32 The Visual Basic Editor Window .......................... ........................................ ............................ ............................ .................... ...... 33 The Project Explorer ............................ ......................................... ........................... ............................ ........................... .................... ....... 33 Working with VBA Code ............................. ......................................... .......................... ............................ ........................... .................... ....... 34 Managing Code Modules ............................ ......................................... ........................... ............................ .......................... ............... ... 34 Importing and Exporting Code...................... Code................................... ........................... ............................ .......................... .............. 35 Running Code from the Visual Basic Editor ........................... ......................................... ............................ .................. .... 35 © Martin Green www.fontstuff.com
2
Recording Excel Macros
Contents
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
About This Book......................... Book...................................... ........................... ............................ ............................ .......................... ..........................4 ..............4 Who is it for?................................ for?............................................. ........................... ............................ ............................ .......................... ...................4 .......4 What's Inside?..................... Inside?................................... .......................... .......................... ............................. ........................... .......................... ................ .. 4 Introducing Recorded Macros.................. Macros............................... ........................... ............................ ............................. ........................... .............. .. 4 What is a Macro? ............................. ......................................... .......................... ............................ ............................ .......................... ................. .....4 4 What a Recorded Macro Can Do and What It Can't ......................... ....................................... ............................ ................ 4 Visual Basic or VBA?............................... VBA?............................................ ........................... ............................ .......................... ........................5 ............5 About Macro Security ........................... ........................................ ........................... ............................ ............................ ..........................5 ............5 Opening Files Containing VBA Code ........................... ......................................... ............................ ............................ ................ 5 Setting the Program's Security Level............................... Level............................................. ............................ ........................6 ..........6 Emailing Files Containing Code......................... Code....................................... ............................ ............................ ........................7 ..........7 Starting and Stopping the Macro Recorder ........................... ......................................... ............................ ........................7 ..........7 The Visual Basic Toolbar ........................... ........................................ ........................... ............................ ........................... ......................8 .........8 Recording Macros.............. Macros ............................ .......................... .......................... ............................. ............................. .......................... .....................9 .........9 About the Exercises..................... Exercises................................. .......................... ............................ ............................. ........................... .....................9 .........9 Step-by-Step: Record a Simple Macro .......................... ........................................ ............................ ........................... ............... .. 10 Step-by-Step: Test the Macro........................ Macro...................................... ............................ ............................ .......................... ............... ... 12 Step-by-Step: Record and Test a More Complex Macro...................................... 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............................... Dialog............................................ ........................... ............................ ............................ ...................... ........ 20 Toolbar Button ........................... ........................................ ........................... ............................ ............................ .......................... ............... ... 20 Menu Item.................................. Item.............................................. .......................... ............................ ............................ .......................... ............... ... 22 Worksheet Button................... Button................................. .......................... .......................... ............................ ........................... .................... ....... 23 Graphic Object ........................... ........................................ ........................... ............................ ............................ .......................... ............... ... 24 Assigning a Shortcut Key...................... Key................................... ........................... ............................ ............................ .................... ...... 24 Automatic Macros ............................ ........................................ ........................... ............................. ............................ ........................ .......... 25 Which Way is Best? ........................... ........................................ ........................... ............................ ............................ ...................... ........ 25 Undoing a Macro's Actions .......................... ........................................ ............................ ............................ .......................... ................. ..... 25 Macro Options.......................... Options....................................... .......................... ............................ ............................. .......................... .......................... .............. 26 Macro Names ........................... ........................................ .......................... ........................... ............................ .......................... ...................... .......... 26 Auto Macros ............................. ......................................... .......................... ............................ ............................ .......................... ...................... .......... 26 Where Should the Macro be Stored? .......................... ........................................ ............................. ............................. ................. ... 26 Personal Macro Workbook.......................... Workbook....................................... ........................... ............................ .......................... ............... ... 27 This Workbook ........................... ........................................ ........................... ............................ ............................ .......................... ............... ... 27 New Workbook.................... Workbook.................................. ........................... ........................... ............................ ............................ ...................... ........ 27 Summary and Other Options............................ 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 E ditor .......................... ........................................ ............................ ............................ .................... ...... 32 The Visual Basic Editor Window .......................... ........................................ ............................ ............................ .................... ...... 33 The Project Explorer ............................ ......................................... ........................... ............................ ........................... .................... ....... 33 Working with VBA Code ............................. ......................................... .......................... ............................ ........................... .................... ....... 34 Managing Code Modules ............................ ......................................... ........................... ............................ .......................... ............... ... 34 Importing and Exporting Code...................... Code................................... ........................... ............................ .......................... .............. 35 Running Code from the Visual Basic Editor ........................... ......................................... ............................ .................. .... 35 © Martin Green www.fontstuff.com
2
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Editing Code ............................ ........................................ ........................... ............................. ............................ .......................... ................. ..... 36 Getting Help................................. Help.............................................. ........................... ............................ ............................ .......................... ................. ..... 36 Using the t he Help Menu ............................ ......................................... ........................... ............................ ............................ .................... ...... 36 Context Sensitive Help with the F1 Key ........................... ......................................... ............................ ...................... ........ 36 Editing VBA Code Practical Exercises........................ Exercises...................................... ............................ ............................ ........................ .......... 38 Step-by-Step: Experiment with Colours .......................... ........................................ ............................ .......................... .............. 38 Create the Macro........................ Macro..................................... ........................... ............................ ............................ .......................... ............... ... 38 Summary ............................ .......................................... .......................... .......................... ............................ ........................... ...................... ......... 44 Step-by-Step: Build a Random Random Numbers Macro ........................... ......................................... ............................ ................ 45 Create the Macro........................ Macro..................................... ........................... ............................ ............................ .......................... ............... ... 45 Summary ............................ .......................................... .......................... .......................... ............................ ........................... ...................... ......... 50 What Comes Next? ............................ ......................................... ........................... ............................ ............................ .......................... ................. ..... 51 Where Do I Go from Here? ........................... ....................................... ........................... ............................. .......................... ................. ..... 51 Recommended Web Sites........................ Sites..................................... ........................... ............................ ............................ ...................... ........ 51 Recommended Reading ............................ ......................................... ........................... ............................ ............................ .................... ...... 51 Notes and Further Information......................... Information....................................... ............................ ............................ .......................... ................. ..... 52 About the Author ............................. ......................................... .......................... ............................ ............................ .......................... ............... ... 52 Copyright............................ Copyright.............. ............................ .......................... ........................... ............................. .......................... .......................... .............. 52 Limitation of Liability ............................ ......................................... ........................... ............................ .......................... ........................ ............ 52
First Published in 2005 by Martin Green Web Site: http://www.fontstuff.com e-mail:
[email protected] © 2005 Martin Green – All rights reserved.
© Martin Green www.fontstuff.com
3
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.
To make the most of this book you should have at least a basic working knowledge of n Microsoft Excel. You don't need to be an "advanced" or "expert" Excel user. You don't need o i any prior knowledge of recording or editing macros, nor do you need any knowledge of VBA t programming, or any other programming language. i Recorded macros are useful to Excel users of all skill levels, from those creating or working d with simple spreadsheets to those who use Excel's most advanced tools. Even Excel E developers, skilled at writing VBA programs, find occasional use for this valuable tool. ' s y What's Inside? t l n n 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. e O d It explains the different ways of r unning macros and introduces the Visual Basic Editor, tool for editing the programming code behind the macros. It concludes with some u e Excel's t s step-by-step exercises in editing existing macros and writing VBA code to create new ones. S U Each section is illustrated with helpful screenshots throughout. l The material in this book is relevant to all recent versions of Microsoft Excel from Excel 97 h onwards. a c i n Introducing Recorded Macros w o i n t What is a Macro? e a e c A macro is a collection of commands written in the Visual Basic programming language. r u When is macro is run the commands are executed and perform their various tasks. Macros G d are used to carry out routine, repetitive or laborious tasks automatically and with speed. can be written by hand using the Visual Basic Editor which is included as part of most f E Macros Office programs. Some Microsoft Office programs (Excel, Word, PowerPoint) have a o r Microsoft 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 o y You can save the recorded macro and play it back to have the same task f program. t performed automatically. i s Although you can record and use macros without any knowledge of Visual Basic r programming, with a little skill you can edit or modify recorded macros to improve their e power and functionality. v This document will show you, with the help of some practical examples, how to record a i macro in Microsoft Excel, how to carry out some simple editing of recorded macros using the n Visual Basic Editor, and how to assign a macro to a menu item or toolbar button. U
What a Recorded Macro Can Do and What It Can't
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 t he 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
Recording Excel Macros •
•
•
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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. T he 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... •
•
•
The Macro Recorder can be used very successfully without any knowledge of programming. The Macro Recorder is an excellent learning t ool 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 t o carry them out so t he length of time it takes to record a macro is largely irrelevant. Timing can become a factor in handwritten 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 t o create many different types of "standalone" programs which can f unction independently. There have been many versions of Visual Basic, the last being Visual Basic 6 (VB6). After VB6 Visual Basic became part of Microsoft's .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 it's 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). 1). The dialog allows you to disable the code before opening the file if you wish.
© Martin Green www.fontstuff.com
5
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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 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 file's 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 Program's Security Level If you regularly record or write and use macros the security level of t he 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 t o 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 bra nd 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
Recording Excel Macros
is the case you will see a different message when you attempt t o open a file containing macros (Fig. 3).
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 3 This message is displayed when the security is set to High.
This message does not give you the option to enable the file's macros. If you want to make use of the code in the file you must set the program's 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 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 program's 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 t o 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
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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
•
•
•
The appearance of Record Macro dialog box differs in each program to reflect that 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.
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
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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
About the Exercises My experience of training IT in a classroom has taught me t hat 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 a s 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 I'm asking you to do. Follow the instructions exactly. Read the instructions carefully and do exactly what they 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 t he 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 don't understand an instruction don't 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
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!
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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.
Your worksheet will look something like this:
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 Excel's 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 E xcel 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
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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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 i n 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.
© Martin Green www.fontstuff.com
11
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:
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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. Step 2:
Select a different block of cells, including some of those containing the text you just entered.
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 cell's 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
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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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. 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 t he 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. 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 isn't 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. Fig. 9 Sample data for the More Complex Macro
Each row of data will then contain all the information it needs.
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 t hat 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
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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 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 t he worksheet containing a copy of your te st 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 workbook's name is shown in front of the macro name.
© Martin Green www.fontstuff.com
14
Recording Excel Macros
Select the macro from the list
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Step 16: Click the Run button on the Macro dialog box. 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.
© Martin Green www.fontstuff.com
15
Recording Excel Macros
Tips for Recording Macros Get More Familiar with Excel You don't 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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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, and the Paste Special command (Fig. 9) which allows you to specify different options for pasting copied data or objects.
Fig. 10 The Go To Special dialog.
Fig. 11 The Paste 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 t he 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 t he Macro Recorder does not include it in t he final code. Sometimes it is unable to do this and your resulting © Martin Green www.fontstuff.com
16
Recording Excel Macros
macro carries out your mistakes then undoes t hem 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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 12 Excel warns you if a macro name already exists.
Relative or Absolute References? 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 t hat 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 macro's 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 b utton (left) and Relative References button (right).
The next exercise demonstrates the use of t his feature when recording a macro.
© Martin Green www.fontstuff.com
17
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...
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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 to 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 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 t o 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 b ehaved 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 cell's 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 couldn't do as it
© Martin Green www.fontstuff.com
18
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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
© Martin Green www.fontstuff.com
19
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
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Using the macros dialog requires no prior preparation. Open the Macro dialog (Fig. 14) from 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.
Fig. 14 Running a macro from the Macro dialog box.
The Macro dialog box lists all t he 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 Excel's 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 righthand list box (Fig. 15 ). One of the commands is Custom Button.
© Martin Green www.fontstuff.com
20
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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
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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 18 The Button Editor lets you design your own button images.
Having made your changes to the button's 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 t oolbars 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
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)).
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
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 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 a ctivate 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 t his 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 rightclicking 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
Recording Excel Macros
the macro. A button has two selection modes. When normally selected (Fig. 23 left) it shows a dotted border and the r ight-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.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 23 The two selection modes of a b utton.
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.
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 t o assign a shortcut key to a macro before you record it. If you didn't 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
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 27 The Macro Options dialog box.
You can also use the Macro Options dialog to add or change a macro's description.
Automatic Macros 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 don't want t o 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 r unning the same macro).
Undoing a Macro's Actions It is very important to remember that the action of a macro can not be undone by using Excel's 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 t he workbook before running a complex macro so that the macro's actions can be undone simply by closing t he workbook without saving the changes, then reopening it in its original state.
© Martin Green www.fontstuff.com
25
Recording Excel Macros
Macro Options Macro Names When naming your macros there are rules that can not be broken, and also some good practice to adhere to. •
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
•
•
•
•
•
Use Meaningful Names: Avoid using cryptic names for your macros. Don't make someone else read through the code or have to run the macro in order to figure out what it does (that person could be you in a few months time). You can give more precise details in the macro's description if necessary. Keep Names Short: The maximum length for a macro name is 255 characters although the macro recorder will only allow you to enter up to 64 characters (the 64 character limit can be exceeded in the Visual Basic Editor). Keep the name as short as is practical. No Spaces Allowed: Macro names can not contain spaces. The name Fill Empty Spaces would not be allowed. Instead, you can obtain a similar effect by capitalizing the first letter of each word (e.g. FillEmptySpaces) and/or using underscores instead of spaces (e.g. Fill_Empty_Spaces). Illegal Characters: You can't use a dot (.), exclamation mark (!), or the characters @, &, $, # in the name. Names Must Start with a Letter: You can mix alphanumeric characters in a name, and it can end with a number, but you can't start a macro name with a number. The name Macro1 is acceptable but not 1Macro. Don't Use Reserved Words: It is good practice, although not forbidden, to give macros names which are the same as VBA function, method or statement names (at this stage you probably don't know what these are but bear it in mind for later!).
Auto Macros There are two macro names which have a special meaning to Excel: Auto_Open and Auto_Close (note the underscore separating the words in each name). If you give a macro the name Auto_Open then Excel runs it automatically when the workbook opens. A macro with the name Auto_Close is run automatically when the workbook closes. These macros run by themselves without having to be called by the user. You can prevent an auto macro from running by holding down the [Shift] key on your keyboard whilst the workbook opens or closes. To be sure of disabling the macro make sure you depress the [Shift] key before giving the command to open or close the workbook and hold it down until t he workbook has finished opening or closing. An auto macro is recorded in the same way as any other macro. They can be run in the normal way just like any other macro if required. In VBA programming these two macro names have been superseded by the Workbook_Open and Workbook_BeforeClose event procedures but Auto_Open and Auto_Close are still supported by Excel. These event procedures, along with several others specific to events in a workbook or on a particular worksheet, are stored in the workbook and worksheet modules of the workbook and must be programmed manually from the Visual Basic Editor. Auto macros will not run if the option to Disable Macros is chosen when the security warning message is displayed when the workbook is opened.
Where Should the Macro be Stored? Excel macros are stored within the workbook file. Their VBA code can be viewed and managed with the aid of the Visual Basic Editor (see: The Visual Basic Editor on page 32). The availability of a macro depends upon where it is stored. When deciding where to store your macro you should consider who will be using the macro and when they will want to use
© Martin Green www.fontstuff.com
26
Recording Excel Macros
it. Will others find this macro useful? Will you want to distribute it to other users or is it solely for your own use? The macro recorder offers three options for storing the recorded macro:
Personal Macro Workbook The Personal Macro Workbook is a file called PERSONAL.XLS. Its location varies according to your versions of Windows and Excel. For example, Excel 2002 running on Windows XP stores it in the folder:
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
C:\Documents and Settings\\Application Data\Microsoft\Excel\XLSTART If you don't know the location of your XLSTART folder right-click on the Windows Start button and choose Search to launch the Windows search tool. A search for "XLStart" will find it for you. (NOTE: The Application Data folder is a normally hidden so you will need to check the option to Show hidden files and folders in the Windows Explorer Folder Options.) The Personal Macro Workbook file exists solely for the purpose of hosting macros and doesn't exist until you record your first macro into it, when Excel creates it automatically if it can't find an existing copy. If you move or delete Personal.xls Excel will simply create another copy when it needs it. Each time you start Excel it looks in the XLStart folder. If it finds a copy of Personal.xls it opens then hides it. A quick way to find out whether or not you already have a copy of Personal.xls is to open Excel's Window menu and choose Unhide. If your computer has a copy of Personal.xls its name will appear listed in the Unhide dialog box. The advantage of storing a macro in Personal.xls is that, since this file is always open (albeit hidden), the macro stored there is always available. You can run it from any workbook. But Personal.xls is not always the most appropriate place to store a macro. If your macro is specific to a particular workbook that is where is should be located. If you want to let other people have copies of your macros it is possible to make copies of Personal . xls and distribute the file but this is not an ideal solution. They might already have their own copies of Personal.xls containing their own macros and, as with any file, you can have only one file named Personal.xls in the XLStart folder. But if your co-workers don't create macros of their own distributing prepared copies of Personal.xls to everyone might be the best option.
This Workbook Store the macro in the current workbook if the macro is specific to that workbook or if it is only likely to be used in that workbook or when that workbook is open. Whilst this seems restricting this is often the best place for a macro. If you are in the habit of using Excel templates (*.xlt files) remember that a macro stored in a template is copied into the workbooks which are b ased on that template. Distributing templates as a source of macros might be a more appropriate solution that using Personal.xls.
New Workbook This option simply allows you to have the macro recorder store the macro in a new workbook instead of the one in which the macro is being recorded.
Summary and Other Options The main reasons for considering where t o store a macro are: •
When are you likely to use the macro?
•
Will you want to distribute it to other users?
On that basis the most appropriate places to store your macros are: •
•
If the macro is specific to one workbook store the macro in that workbook. If the macro is used in a particular kind or workbook consider building a template for the workbook and store the macro in the template.
© Martin Green www.fontstuff.com
27
Recording Excel Macros •
•
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
If the macro will be used widely but only by you store the macro in your Personal Macro Workbook (Personal.xls). If the macro will be used widely by several users consider incorporating the macro into an Excel Add-In or exporting it as a *.bas file, both of which can be distributed and installed on other users' computers.
Some knowledge of VBA is required if you want to create Excel Add-ins but it isn't difficult and is often the best way to distribute macros (and other VBA utilities such as Custom Functions). You can find an on-line tutorial describing in detail how to create an Excel Add-in at: http://www.fontstuff.com/vba/vbatut03.htm You can find out how to distribute macros as *.bas files later in this document (see Importing and Exporting Code on page 35).
Changing Macro Options You can change a macro's description and its shortcut key assignment at any time. Open the Macro dialog box (Fig. 14) (Tools > Macro > Macros or [Alt]+[F8]). Select the macro from the list and click the Options button. This opens the Macro Options dialog (Fig. 27 ). Make whatever changes are necessary then click the OK button to implement them.
Saving and Deleting Macros When you create or change a macro you make a c hange to the workbook file so remember to save your changes when closing the file. Excel will prompt you for changes i n the normal way. If you want to delete a macro open the Macro dialog box, select the macro to be deleted and click the Delete button. Excel will ask you t o confirm the deletion. Again, remember to save the changes when your close the file.
© Martin Green www.fontstuff.com
28
Recording Excel Macros
Editing Recorded Macros Whilst recorded macros are very useful you can often extend their power by modifying their underlying VBA code in the Visual Basic Editor. This section provides a brief introduction to exploring and editing VBA code.
Viewing Recorded Code
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
To view a macro's code open the Macro dialog box (Fig. 14) (Tools > Macro > Macros or [Alt]+[F8]) then select the macro from the list and click the Edit button. Excel opens the Visual Basic Editor window. Here you can view, edit and manage all your Excel VBA macros and also write new ones. Each Microsoft Office program which permits VBA programming has its own Visual Basic Editor similar to this one. (NOTE: You can not use the Edit button to view macros stored in Personal.xls because this is a hidden workbook. To view the code inside a hidden workbook you must open the Visual Basic Editor as described below (see: Opening the Visual Basic Editor on page 32) and locate it using the Project Explorer .) When you open the Visual Basic Editor from the Macro dialog box it takes you direct to the code procedure for the macro that was selected when you clicked the Edit button on the dialog box. More detailed information about using the Visual Basic Editor is given in the section entitled The Visual Basic Editor on page 32. This section examines the code that was recorded in the Step-by-Step exercises earlier in this document... (NOTE: The VBA code shown in the examples below has been given line numbers. Most VBA developers do not bother to number their code like this. It has been done here for clarity and ease of identification in the t ext. The Visual Basic Editor does not automatically number lines of code although numbering can be added manually if required.)
The Simple Macro Here is the code recorded for t he Simple Macro (see: Step-by-Step: Record a Simple Macro on page 10) which contained a number of simple cell formatting commands. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Sub Macro1() ' ' Macro1 Macro ' Macro recorded 30/03/2005 by Martin Green ' ' Selection.Font.Bold = True Selection.Font.Italic = True With Selection .HorizontalAlignment = xlCenter .VerticalAlignment = xlBottom .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With With Selection.Interior .ColorIndex = 6 .Pattern = xlSolid End With Selection.Font.ColorIndex = 3 End Sub
The first line of the macro (Line 1) identifies it by name. All macros start with the keyword Sub (short for Subroutine). After the macro name is a pair of parentheses. These are sometimes used to enclose parameters or arguments (in the case of VBA functions)
© Martin Green www.fontstuff.com
29
Recording Excel Macros
associated with the current procedure. There is a corresponding End Sub line at the end of the macro (Line 25). Lines 2 to 6 are Comments, usually coloured green in the Visual Basic Editor (you can choose your own colour scheme). Comments are pieces of descriptive text or notes. In this instance the comment text has been copied by t he Macro Recorder from the description that was supplied. Comments are always prefixed by an apostrophe ( ') which instructs the code compiler to ignore what follows in that line and not try to execute it as VBA code.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
When the Bold toolbar button was clicked the Macro Recorder wrote Line 7 which tells Excel to apply the Bold property to the Font property of the Selection object. Line 8 is very similar and was written when the Italic button was clicked. It tells Excel to apply the Italic property to the Font property of the Selection object. When the macro was being recorded the next step was to click the Center align button. This resulted in eleven lines of code (Lines 9 to 19). Here is an example of the Macro Recorder generating far more code than is necessary. This often happens when recording macros, especially when you have to visit a dialog box containing many options. Although here only one option was changed (the HorizontalAlignment of the Selection was changed to xlCenter) all the default settings have been recorded as well. The items listed can all be found on the Alignment tab of the Format Cells dialog box (Fig. 28).
Fig. 28 The Macro Recorder records all the defaults from the Alignment tab of the Format Cells dialog box.
The Macro Recorder has used a With Statement to bracket together a number of code lines all of which refer to the same object. This coding technique is used to avoid repetition of the same code statement (in this case the keyword Selection). With Statements start with the keyword With and end with End With. When a Fill Color was chosen the Macro Recorder wrote another With Statement (Lines 20 to 23) defining the ColorIndex of the Interior as well as the type of Pattern. The latter is the default setting and was not changed so it too is superfluous and can be omitted. Finally, when the Font Color was chosen Line 24 res ulted specifying the ColorIndex. Generally speaking, the fewer lines of code that are used to achieve a specific task the better. Concisely written code usually runs faster and more efficiently. Code lines referring to default settings can normally be removed without altering the macro. Also, because the actions were carried out in a particular order which had no special bearing on the macro's outcome, some repetition has resulted (i.e. Font properties specified in different places instead of all together).
© Martin Green www.fontstuff.com
30
Recording Excel Macros
This particular macro could be safely edited to remove the unnecessary code statements and rearranged to reduce the total number of lines considerably. The resulting macro will run faster because the code compiler has less work to do. It is also much easier to read and will carry out all the tasks required of it...
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
1 2 3 4 5 6 7 8 9
Sub Macro1() With Selection .Font.Bold = True .Font.Italic = True .Font.ColorIndex = 3 .HorizontalAlignment = xlCenter .Interior.ColorIndex = 6 End With End Sub
The FillEmptyCells Macro The code listing for the next macro (see: Step-by-Step: Record and Test a More Complex Macro on page 13) was generated much more efficiently by the Macro Recorder... 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Sub FillEmptyCells() ' ' FillEmptyCells Macro ' Fills each empty cell in a selection with data from the cell above. ' ' Selection.CurrentRegion.Select Selection.SpecialCells(xlCellTypeBlanks).Select Selection.FormulaR1C1 = "=R[-1]C" Selection.CurrentRegion.Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False End Sub
The keyboard shortcut [Control]+* was used to Select the CurrentRegion of the Selection in Line 7 and again in Line 10. The command Edit > Go To > Special > Blanks was used to Select the SpecialCells(xlCellTypeBlanks) of the Selection in Line 8. Line 9 shows how, with m ultiple cells selected, the Macro Recorder interpreted the keyboard command of [Equals][Up Arrow] followed by [Control]+[Enter]. The latter is the "block fill" command which tells Excel to enter the typing into all the cells that are currently selected. The VBA simply refers to this as the Selection. Then FormulaR1C1 inserts a formula into the cells using R1C1 (or Row Column) notation. This is a way of referring to cell addresses in a general (i.e. Relative) way. Cell addresses in formulas entered this way get translated as they are written into the cell. The formula is presented as a string (i.e. a piece of text) so must be enclosed between pairs of quote marks: "=R[-1]C". This refers to the cell one row above (R[-1]) in the same column (C) (NOTE: this could have been written "=R[-1]C[0]" but when there is no difference in row or column the zero is usually omitted.) Having selected the CurrentRegion again in Line 10 the instruction is given to Copy the Selection in Line 11 then Paste it using PasteSpecial in Line 12. As in the previous example, some default items have been entered in Line 12 ( Operation, SkipBlanks and Transpose). The only essential item here is Paste:=xlPasteValues. The others can be omitted. Because Line 12 is quite long t he Macro Recorder has broken the code statement i nto a second line after the word SkipBlanks by adding the "line break character" (i.e. a space followed by an underscore). This is done only for the convenience of the person reading or writing the code. It makes no difference to how the code is executed. (NOTE: if you want to break a line of code into one or more lines you must use the line break character so that the code compiler knows the separate lines represent a single code statement.) Finally, in Line 13 Excel is taken out of copy mode and the macro finishes.
© Martin Green www.fontstuff.com
31
Recording Excel Macros
Although it might appear that, since the Selection object is referred to at the beginning of each line from Lines 7 to 12, a With Statement could be used to good effect here. But in this case it would not be appropriate (and the code would not work properly) because although the term Selection is used each time the actual cells it refers to changes several times (i.e. it is a different selection each time). With Statements can only be used to group together commands referring to precisely the same thing.
The AbsoluteReferences and RelativeReferences Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
An earlier exercise (see: Step-by-Step: Compare Relative and Absolute References on page 18) demonstrated the effect of choosing to record Absolute or Relative references. Here you can see the VBA code that was recorded for the two different macros... Sub AbsoluteReferences() Range("B5").Select End Sub Sub RelativeReferences() ActiveCell.Offset(-5, -1).Range("A1").Select End Sub
In the exercise, two macros were recorded. Before each macro was recorded the cell C10 was selected. The operation that was recorded consisted simply of selecting cell B5 . The first macro ( AbsoluteReferences) was recorded without the Relative References button pressed in. In the resulting code the instruction is given to Select the Range("B5"). This is quite specific and refers to an actual cell address. This is why, regardless of which cell is selected when the macro is run, the result is always the selection of cell B5 . The second macro (RelativeReferences) was recorded with the RelativeReferences button pressed in. The resulting code statement did not specify a particular cell to be selected. Instead it used the Offset property of the currently selected cell (t he ActiveCell) to refer to another location relative to the current cell. Offset uses Row Column notation. Negative numbers (i.e. numbers preceded by a minus sign) mean "up" when referring to rows and "to the left" when referring to columns. Positive numbers (no plus sign is necessary) mean "down" when referring to rows and "to the right" when referring to columns. A zero (0) denotes the same row or column as the current cell. The RelativeReferences macro refers to a cell 5 rows above (-5) and one column to the left (-1) of the ActiveCell. At this point the selection is further defined as Range("A1") which might appear rather confusing and really only applies if a block of cells were being selected. The line would normally be written... ActiveCell.Offset(-5, -1).Select
As a result, a single cell would be selected. If instead you wanted to select a block of cells, say three columns wide by five rows high, starting at that cell you would instead write... ActiveCell.Offset(-5, -1).Range("A1:C5").Select
The Visual Basic Editor The Visual Basic Editor is where you create, edit and manage your visual basic code. It opens as a separate window but you can only access it from within the host program. Each Microsoft Office program that supports VBA has its own Visual Basic Editor and all work in the same way. This section is a brief explanation of how to find your macro code in the Visual Basic Editor and carry out basic code editing tasks. NOTE: A full explanation of the Visual Basic Editor, its tools and how to use them can be found in the companion to this document: The Visual Basic Editor by the same author.
Opening the Visual Basic Editor The Visual Basic Editor can be opened directly from the Excel Tools menu by choosing Macro then Visual Basic Editor or by using the keyboard shortcut [Alt]+[F11]. It can also be opened from the Macro dialog box (Tools > Macro > Macros or [Alt]+[F8]) by clicking the dialog's Edit button after first selecting the macro whose code © Martin Green www.fontstuff.com
32
Recording Excel Macros
you want to view. Opening the Visual Basic Editor this way takes you direct to that macro's code.
The Visual Basic Editor Window
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
The illustration below shows the layout of the Visual Basic Editor window (Fig. 29). The main area (on the right) is occupied by the code window where VBA code is displayed. Code writing and editing is done here. On the left are two smaller windows, the Project Explorer and the Properties Window . These smaller windows can be moved around and either docked elsewhere or left floating within the main window. They can also be closed so if they aren't visible go to the Visual Basic Editor's View menu and choose Project Explorer or Properties Window to open them.
Fig. 29 The Visual Basic Editor window.
The Project Explorer VBA code is stored in modules attached to Excel files. Within a workbook each worksheet contains it own dedicated code module and the workbook itself has a dedicated code module. Worksheet and workbook code modules are for holding code that does specific jobs relating to their own worksheet or workbook. Code created by the Macro Recorder is stored in a standard module. When you write macros yourself you can choose to place them in an y of these modules depending on what the code does. If you opened the Visual Basic Editor from the Edit button of the Macro dialog box in Excel your macro's code will already be displayed in the code window. If you opened the Visual Basic Editor another way the code window may be empty or be displaying something else. Use the Project Explorer to locate, display and manage the code currently available to you. The Project Explorer is organized like the familiar Windows Explorer file manager, showing you the various objects, code modules, class modules or UserForms that are currently available. It uses a folder-tree structure to display the various elements. A plus symbol next to an object indicates that it contains other objects. Click the plus symbol to reveal the objects. The symbol then changes to a minus symbol which in turn hides the objects when clicked. Double-click an object in the Properties Window to see its code (if any) displayed in the Code Window. If code is password protected, you will be prompted to enter the password when you click the plus button, before t he code is revealed. Modules created by the macro recorder are numbered sequentially (Module1, Module2 etc.). If you record more than one macro during the same session (i.e. without closing the workbook in which the macros are stored) they will be placed into the same module.
© Martin Green www.fontstuff.com
33
Recording Excel Macros
Otherwise the Macro Recorder will create a new module so, if you have recorded several macros at different times, you will find that you have several code modules. The illustration below (Fig. 30) illustrates a typical view of the Project Explorer window. It shows that an Excel add-in is currently loaded. Third-party add-ins (this one is the Analysis ToolPak from Microsoft) are usually password protected so that you can not view or edit their code. There is also a copy of Personal.xls open in addition to a single workbook (Book1) which has not yet been saved...
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 30 A typical view of the Project Explorer.
In the Project Explorer all the VBA associated with a particular file is referred to as a Project and given the name VBAProject. This name can be changed to something else if required (in the Visual Basic Editor go to Tools > VBAProject Properties > General and change the Project Name). The name of the file to which the project belongs appears in brackets after the project name in the Project Explorer. In the illustration (Fig. 30) the add-in's author has named their project "funcres".
Working with VBA Code The code that you see in a code module in the Visual Basic Editor can be treated like text in a word processor. Navigate around it with the keyboard and mouse as you would in a normal text document. It can be cut, copied and pasted within a module or between modules, even if those modules belong to different files.
Managing Code Modules Code modules are simply containers for VBA code. Apart from worksheet and workbook specific modules which have their own special purpose, it does not matter how many modules you have in a workbook or which macros they contain. Most VBA programmers like to use modules to store their macros is in a logical fashion so they can find them easily when they need to. The modules can then be renamed to reflect their contents. To Add a New Module: In the Project Explorer click on the name of the project to which you want to add a new module then choose Module from the Insert menu; or click the down-arrow next to the Insert Object button on the Visual Basic Editor toolbar (Fig. 31) and click the Module button; or right-click the project name in the Project Explorer and choose Insert > Module from the context menu. To Rename a Module: In the Project Explorer click on the name of the module to select it then in the Properties Window change the Name property and press [Enter]. You must adhere to the standard VBA naming rules (see: Macro Names on page 26). To Delete a Module: In the Project Explorer right-click on the name of the module and choose Remove from the context menu. The Visual Basic Editor will ask if you want to export the module first (see: Importing and Exporting Code on page 35). Click No to complete the process and delete the module.
© Martin Green www.fontstuff.com
34
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 31 Adding a new module.
Importing and Exporting Code A convenient way of exchanging macros with other users is to export a code module from one file and import it into another. For example, you might have a useful collection of macros in your copy of Personal.xls that you would like to share with another user. You can export the module(s) and email the files to the other person who can import them into their copy of Personal.xls. Modules are exported as text files with a .bas extension (they can be read in a simple text editor such as Notepad ). Since *.bas files are known to contain code, they are usually regarded as a potential security hazard by email systems so it is wise to take the precautions outlined earlier (see: Emailing Files Containing Code on page 7). To Export a Module: In the Project Explorer right-click on the module name and choose Export File from the context menu. In the Export File dialog choose a location for the exported file and enter a filename. Click the Save button to complete the process. To Import a Module: In the Project Explorer right-click on the name of the project for the file into which you want to import the module and choose Import File from the context menu. Use the Import File dialog to locate the module's *.bas file then select it and click the Open button to complete the process. When exporting a module the Visual Basic Editor will suggest a filename that matches the module's name. This filename is quite independent of the module name that appears in the Project Explorer. The imported module "remembers" the name of its original module and will assume this name when imported unless there is already a module of that name in the receiving project, in which case the Visual Basic Editor will automatically rename the new module to prevent a naming conflict.
Running Code from the Visual Basic Editor A macro can be run from within the Visual Basic Editor. To do this place your cursor anywhere between the Sub and End Sub lines of the macro. To run the macro press the [F5] key on your keyboard. Alternatively use the toolbar button. There is a Run button as well as ones to Break (i.e. pause) and Stop the macro (Fig. 32). NOTE: macros will stop by themselves when their job is done. The latter two buttons are normally used during testing or when something has gone wrong!
Fig. 32 Toolbar buttons for running a macro from the Visual Basic Editor.
When testing a macro it is useful to observe the action of its code a line at a time. This is achieved by causing the code execution to "break" (pause) before executing each line and wait for your instruction to proceed. To do this place your cursor anywhere between the Sub and End Sub lines of the macro. To start the process press the [F8] key on your keyboard (or open the Visual Basic Editor's Debug menu and choose Step Into). To begin with the macro's Sub line is highlighted with a yellow bar. This yellow bar indicates the line of code that is about to be executed. Press the [F8] key again to start the macro and move to the first line of code which will become highlighted ( Fig. 33). It skips empty © Martin Green www.fontstuff.com
35
Recording Excel Macros
lines and comments. Keep pressing the [F8] key to move through the macro, executing a line at a time, until you reach the End Sub line. Then press the [F8] key to finish the macro, at which point the yellow highlight bar will disappear.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Fig. 33 Stepping through a macro.
When a macro is paused and waiting to execute a line of code it is said to be in Break Mode. If at any time you want to stop the macro before it has reached the last line click the Stop button on the Visual Basic Editor toolbar (or open the Run menu and choose Reset). If you want to stop stepping through the macro but still allow it to finish press the [F5] key (or click the Run button on the Visual Basic Editor toolbar). NOTE: You might have noticed that there is a button marked Step Into on Excel's Macro dialog box. If you select a macro from the list and press the Step Into button Excel opens the Visual Basic Editor and takes you to that macro's code, with the macro in break mode at the first line, ready for you to step through the macro using the [F8] key. Using this technique you can observe the actions of a macro as each line is executed. Minimize any other programs you have open leaving only the Excel and Visual Basic Editor windows maximized. Then right-click on the Windows Taskbar and choose either Tile Windows Horizontally or Tile Windows Vertically so that you can see both windows next to each other on the screen.
Editing Code VBA code can be edited in the code window of the Visual Basic Editor in the same way as you would edit a regular t ext document. Just click and type. You can select, cut, copy, paste or delete code using the same familiar keyboard shortcuts or menu commands as you would use in any other Microsoft Office program. You can change the way that text appears in the code window (go to Tools > Options > Editor Format) but this has no effect on how the code works. The default font is Courier New , chosen because it is clear and easy to read and also because it is a monospaced font (i.e. all the characters are of the same width) and this enables lines of code to be compared easily. Code is automatically formatted into different colours according to its function (general code is black, VBA keywords are blue and commented text is green). You can change the colour scheme (go to Tools > Options > Editor Format) but you can not apply other formatting such as bold, italic or underlining, or mix fonts and point sizes.
Getting Help If you chose the Minimum Install option when loading Microsoft Office or Microsoft Excel on to your computer you will not be able to make use of VBA Help since this is excluded from a Minimum Install . It can, however, be added later so if when following the instructions below you see a message to the effect that VBA Help is not available you should install it from the Microsoft Office/Excel disk.
Using the Help Menu The Visual Basic Editor provides help in the usual way. Choose Help > Microsoft Visual Basic Help to open the familiar Help window with its Contents, Index and Answer Wizard. Use this method to browse the help topics or search for a particular item in the usual way. VBA help is very comprehensive and usually provides examples of code (which you can copy and paste into your own modules) and cross-references to other related topics.
Context Sensitive Help with the F1 Key If you are writing VBA code and find that you need help, the Visual Basic Editor can often take you straight to the correct help topic. To get help about a specific keyword (a VBA © Martin Green www.fontstuff.com
36
Recording Excel Macros
object, property, method or function) place your cursor in the word and press the F1 key. This will open help at the correct location. In the unlikely event that there is not a relevant help topic the message Keyword Not Found will be displayed.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
© Martin Green www.fontstuff.com
37
Recording Excel Macros
Editing VBA Code Practical Exercises The best way to learn about editing and writing VBA code is to do it. In this section are some practical exercises designed to illustrate some basic code-writing techniques.
Step-by-Step: Experiment with Colours
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
In an earlier exercise we used the Macro Recorder to record a macro which formatted the selected cells with a coloured fill and a font colour (see Step-by-Step: Record a Simple Macro on page 10). When we examined the code behind the macro (see: Viewing Recorded Code on page 29) we could see that colour was specified as a number, the ColorIndex. To change the colour used by the macro is simply a matter of changing the number, but what do the numbers mean? How can you find out what colour each ColorIndex number represents. The colour chooser in Excel offers a choice 40 different colours, each displaying a name when the mouse is held over the colour sample (Fig. 34). But it doesn't tell you the index number of the colour and, unfortunately, you can't refer to the colour by that name in VBA.
Fig. 34 The Colour Chooser.
Create the Macro When I find myself in this situation I usually write a short macro to create my own swatch of colours along with their index numbers. Here's how to do it... Step 1:
In Excel open a new, empty workbook then open the Visual Basic Editor by using the keyboard shortcut [Alt]+[F11].
Step 2:
In the Visual Basic Editor right-click on the name VBAProject(Book1) (assuming your new workbook is called Book1, otherwise choose the appropriate entry) and choose Insert > Module.
An empty code module appears in the code window of the Visual Basic Editor. Step 3:
Click in the code window and t ype:
Sub ColorSamples Then press the [Enter] key. The Visual Basic Editor fills in the rest of the Sub line for you and adds the line End Sub, placing your cursor in the empty line between them. Your code should look like this:
In the next step you will add a line of code which will specify a fill colour for a particular cell. Step 4:
Press the [Tab] key to indent your typing then type:
Range( © Martin Green www.fontstuff.com
38
Recording Excel Macros
Indenting code lines makes them easier to r ead (pressing tab indents text in the Visual Basic Editor by 4 spaces). When you type the opening bracket the Visual Basic Editor displays a kind of help called Auto Quick Info which reminds you what pieces of information (called parameters) are needed to complete the code statement...
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
The help is telling you that it needs the address of the first cell ( Cell1) and last cell (Cell2) of the range. The first parameter (Cell1) is in bold, showing you where you are in the code statement and indicating which piece of information the Visual Basic Editor is expecting you to supply. Note that the second parameter is enclosed by square brackets. This means that it is optional. If your range refers to just one cell then you need only supply the first parameter. Cell addresses are supplied as a string (a piece of text) and strings in VBA are always enclosed in quotes. Step 5:
Type:
"A1") When you typed the closing bracket the Visual Basic Editor knew you had finished entering parameters so the help disappeared. Your code should look like this:
You now need to indicate which property of the Range you are referring to. Step 6:
Type a dot.
When you do this the Visual Basic Editor displays another kind of help called Auto List Members. This takes the form of a list of all the items that you can type at this point...
You can, of course, simply continue and type the code if you know it but it is often quicker to let the Visual Basic Editor do it for you (this also helps avoid typos and spelling mistakes). If you want you can use the mouse to scroll down the list, alternatively... Step 7:
Type the letter: i.
The list will scroll down to the first item starting with the letter i . Normally you would continue to type as, with each new letter, the selection moves closer to the item you are looking for (in this case Interior). But it is already in view so... Step 8:
Double-click the word Interior to add it to your code statement.
This also closes the list. © Martin Green www.fontstuff.com
39
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
You now need to indicate which property of the Interior you are referring to. Step 9:
Type a dot.
This displays another list of possibilities. Step 10: Double-click ColorIndex Finally, to indicate which colour you want... Step 11: Type: =1 Your code should now look like this:
Step 12: Make sure your cursor is somewhere within the text of the macro then press the [F5] key to run the macro. Step 13: Use the keyboard shortcut [Alt]+[F11] to switch back to the Excel window. The macro has applied the ColorIndex number 1 (Black) to the interior fill of cell A1...
Step 14: Return to the code window and try a few more colours by changing the ColorIndex number then running the macro. You already know that the colour chooser offers 40 different colours, so try some numbers between 1 and 40. Let's find out if there is a limit to the number of colours available. Step 15: Change the macro to apply the ColorIndex 100 then run it. You will see that immediately you attempt to run the macro an error occurs and a message is displayed. Excel is telling you that it can't apply the colour you specified...
© Martin Green www.fontstuff.com
40
Recording Excel Macros
Step 16: Click the Debug button on the message box. The message disappears and Excel takes you back to the Visual Basic Editor and indicates with a yellow highlight the line of code that it can't execute...
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Take a look the Title Bar of the Visual Basic Editor window. It shows you that Excel is currently in Break Mode which means that the macro is still running but currently paused, waiting for an action from you...
Step 17: Cancel the macro by clicking the Reset button on the Visual Basic Editor toolbar. This stops the macro and takes Excel out of break mode. (NOTE: Whilst a macro is in break mode you can not work in the Excel window).
You need to find out how many colours are available. To do this you will make use of a code loop. Loops are used to repeat sections of code. The sort of loop we will use here is called a For Next Loop and is used to repeat code a specific number of times. You also need to create a Variable to keep track of how many times the loop has run. Variables are used to hold information in the computer's memory. A variable must be declared at the start of a macro so that the code engine recognises it and knows what it is for. Step 18: Place your cursor in front of the word Range and press the [Enter] key to create an empty line. Move your cursor into the empty line and type:
dim i as integer Then press [Enter] to make an empty line underneath. Your code should look like this:
When you move out of a line you have just typed the Visual Basic Editor carries out a number of checks. If you have made an error in your typing an error message is displayed and the offending text coloured red. If the Visual Basic Editor is happy with your typing it will capitalise and format it as appropriate. The next line tells Excel how many times to run the loop. Step 19: Type: For i = 1 to 100 Place your cursor in front of the word Range and press [Tab] to indent it further. Press the [End] key to move to the end of the line of code. Press [Enter] to create a new empty line.
© Martin Green www.fontstuff.com
41
Recording Excel Macros
Press [Backspace] to move the cursor back a tab. Type: Next i Your code should now look like this:
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
As it stands the loop will repeat the line of code 100 times. But in this macro you want the code to do two different things. It must work on a different cell each time, and it must apply a different colour each time. You need to edit the code line that is inside the loop. Step 20: Place your cursor immediately to the right of the closing bracket after "A1" and type a dot. Then type: Offset(i - 1, 0) Then move to the end of the line, delete the number and replace it with i. Your code should now look like this:
The loop starts with the value of i equal to 1. Each time the code reaches the line Next i the value of i is increased by 1 and the loop repeats. This continues until the value of i reaches 100. Then the loop terminates and t he code moves on to the next line (which in this example finishes the macro). The code also makes use of the value of i, in conjunction with the Offset property, to refer to a cell one row further down column A each time. Similarly, the ColorIndex starts at 1 but increases by 1 for each iteration of the loop. The result will be that the code will colour the interior of cell A1 with ColorIndex 1, cell A2 with ColorIndex 2 etc. until it reaches a ColorIndex that does not exist. At that point the code will produce an error. Before running a new macro it is good practice to compile the code to check for any coding errors. Step 21: Open the Debug menu and choose Compile VBAProject.
The compiler looks for incorrect syntax and words it does not know. If nothing h appens then the code compiler has found no errors and you can proceed. If the compiler finds an error it will notify you with a message and highlight the offending text. In this example the word Next has been spelled wrongly...
© Martin Green www.fontstuff.com
42
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
If the compiler finds an err or correct it then compile again. Step 22: Place your cursor anywhere between the Sub and End Sub lines of the macro and press the [F5] key to run the macro. As expected the macro causes an error (because the macro will try to create colours up to 100 and we know that there aren't that many).
Step 23: Click the Debug button on the error message box. The code line that i s causing the problem is highlighted yellow. Step 24: Point at any instance of the variable i to see a box showing its current value.
The value is 57. This is the current value of i which the macro is trying to apply to a cell but is unable to do so. This tells us that the largest number we can use for the ColorIndex property must be 56. Step 25: Click the Reset button on the Visual Basic Editor toolbar to stop the macro. Step 26: Edit the macro to change the statement: 1 To 100 to read: 1 To 56. Step 27: Add a new line to the macro, inside the loop but after the current line, as follows:
Range("A1").Offset(i - 1, 1).Value = i You code should now look like this:
© Martin Green www.fontstuff.com
43
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
The macro is now finished. Step 28: Compile the code as described in Step 22. Then run the macro and switch to Excel to see the result.
Starting with ColorIndex 1 the macro has applied a coloured fill to cell A1 then written the number 1 in the adjacent c ell. It repeated the process increasing the number by 1 each time until it reached the maximum value of 56.
Summary This macro has practical value in that it very quickly creates a colour swatch of the current Excel colour palette (palettes can be modified – in Excel go to Tools > Options > Color). It is typical of the sort of macro a VBA developer might write to provide information to help with writing a program. The main reason for using it as an example here is that it illustrates several of the Visual Basic Editor's code writing tools... •
•
•
•
•
•
[Alt]+[F11] is a useful keyboard shortcut to switch between the Excel window and the Visual Basic Editor window and vice versa. Auto Quick Info provides help about any parameters that might be required in the code statement. Auto List Members shows a list of the various options available when choosing a property, method or constant as you are typing. [F5] is a useful keyboard shortcut to run a macro from the Visual Basic Editor. Errors occur when macros can't execute their code properly. When an error occurs Excel displays an Error Message. Clicking the Debug button on an error message box takes you to the line of code that Excel is trying to execute. The offending line of code is highlighted in yellow.
•
When you pause a macro in this way it goes into Break Mode.
•
To stop a macro and take it out of break mode you click the Reset button.
•
•
A Variable is used to hold a piece of information during a macro. That information can be changed as the macro runs. You can read the value of a variable when the macro is in break mode by pointing at it.
© Martin Green www.fontstuff.com
44
Recording Excel Macros •
Code loops make code repeat within t he macro.
•
A For...Next loop cycles a specific number of times which you define in the code.
•
Compile code before running it to check for coding errors.
Step-by-Step: Build a Random Numbers Macro
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
When you create a new workbook in Excel the need often arises to test your work with some sample data. If real data isn't available you have to create some. I find making up and entering sample data into a worksheet extremely tedious so I built a macro like this one to do it for me. The macro enters random numbers into the selected cells by making use of Excel's RAND() function.
Create the Macro In this exercise you will start by recording a macro that enters random numbers into the selected cells. You will then edit the macro to refine it and add additional features. Step 1:
Start Excel and open a new empty workbook.
Step 2:
Select a block of cells (anything will do).
Step 3:
Open the Tools menu and choose Macro then Record New Macro.
Step 4:
In the Record Macro dialog enter the Macro name RandomNumbers and choose to Store macro in the Personal Macro Workbook . Add a short Description such as Fills the selected cells with random numbers.
Do not click on the worksheet! Step 5:
Type: =int(rand()*100) Then hold down the [Control] key while you press [Enter].
This command ([Control]+[Enter]) is known as "block fill" and causes your typing to be entered simultaneously into all the selected cells. Each cell in your selection now contains a formula that will display a random number in the range 0 to 99. Step 6:
Press [Control]+C (or click the Copy button on the toolbar).
© Martin Green www.fontstuff.com
45
Recording Excel Macros
Step 7:
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Open the Edit menu and choose Paste Special. In the Paste Special dialog box choose Values then click the OK button.
This action copied the selected cells then pasted just the displayed values down into the same cells, discarding the underlying formulas. Step 8:
Press the [Escape] key to take Excel out of copy mode.
Step 9:
Press the Stop button on the Stop Recording toolbar.
The recording process is now finished. Now it's time to test the macro... Step 10: Select a block of cells and press [Alt]+[F8] (or go to Tools > Macro > Macros) to open the Macros dialog box. Choose the RandomNumbers macro and click the Run button.
Each of the selected cells should now contain a number between zero and 99. If it does not, of if you see an error message (click the End button on the error message box), check your code in the next step. Now it's time to edit the code and make some improvements to the macro. Step 11: Press [Alt]+[F11] to open the Visual Basic Editor. In the Project Explorer locate the Modules folder for VBAProject (Personal.xls) and if necessary click the sign next to it to display the modules within. The macro you just recorded should be in a module named ModuleX where X is the highest number. Step 12: Double-click the module name to display its code in the code window of the Visual Basic Editor.
Find the code for the RandomNumbers macro. It should look like this:
The PasteSpecial statement contains more information than is necessary. © Martin Green www.fontstuff.com
46
Recording Excel Macros
Step 13: Delete the code starting with the comma after xlPasteValues until the end of the second False as shown below (select the text and press the [Delete] key).
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Your code should now look like this:
Note that the keyword Selection is repeated several times on consecutive lines. Since each of these refers to the same selection you can improve the code by changing it into a With Statement. Step 14: Insert an empty line above the first Selection... line and type:
With Selection Step 15: Replace each of the three existing Selection keywords with a tab (an easy way to do this is to double-click on the word to select it then press the [Tab] key). Step 16: Now insert an empty line above t he line starting Application... and type:
End With Your code should now look like this:
The macro can be enhanced by offering the user the opportunity to set a maximum value for the random numbers generated. For this you will use an Input Box. The user's choice will be stored in a variable which must be declared first. Step 17: Insert an empty line above the line starting With... and type:
Dim lngMax as Long Step 18: Press [Enter] to make another empty line and type:
lngMax = InputBox("Enter a whole number.", "Maximum Number", "100") This line shows a message to the user which invites them to supply a number. Their entry is passed to the variable lngMax. It now has to be written into the random number formula.
© Martin Green www.fontstuff.com
47
Recording Excel Macros
Step 19: In the random number formula replace 100 with:
" & lngMax & " The code should now look like this:
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
It's time to test the macro... Step 20: Open the Debug menu and choose Compile VBAProject. Step 21: Press [Alt]+[F11] to switch to Excel and select a block of cells. Step 22: Press [Alt]+[F8] to open the Macro dialog box then choose the RandomNumbers macro and click Run. When you run the macro the Input Box you programmed is displayed. Note how the box title and its message (called the "prompt") correspond to your code and that a default entry of 100 is already entered...
So far, the random numbers have been supplied as whole numbers because the INT() function has been used in conjunction with the RAND() function to create an integer (a whole number). But the user might not want whole numbers. The macro can be further modified to allow decimal places. For this you will use another Input Box to prompt the user for the number of decimal places they require. This also needs a variable to hold their response. Step 23: Make a new line underneath the line starting Dim... and type:
Dim intDecimals As Integer Step 24: Make another new line underneath the line starting lngMax... and type:
intDecimals = InputBox("Enter a whole number.", "Decimals?", "0") The formula now has t o be modified to allow decimal places if required. To do this the INT() function will be replaced by the ROUND() function. Step 25: Replace the formula as follows:
"=ROUND(RAND()*" & lngMax & ", " & intDecimals & ")" Your code should now look like this:
© Martin Green www.fontstuff.com
48
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Step 26: Compile and test the macro again as described in Steps 20-22. This time a second Input B ox is displayed asking the user to specify how many decimal places they require, the default being zero...
The macro is almost finished. But what happens if the user makes a mistake? If they fail to enter a number in one of the Input Boxes the default value is used. But if they leave the input box completely empty, enter a piece of text, or enter anything that can no t be interpreted as a whole number an error will occur...
To prevent error messages like this from causing problems for the user VBA the usual practice is to include code in a macro which takes charge of the error, tries to rescue the situation, and prevents the macro from "crashing". This code is called an "error handler". The simplest way of handling an error is to ignore it, abandon the line of code that is causing the error, and move on to the next job. This method should be used with caution, but since nothing disastrous can happen if that approach is used in this example, this is the method we'll use here... Step 27: Make an empty line at the start of the macro, immediately after the line starting Sub... and type:
On Error Resume Next The completed code for the finished macro should look like this:
© Martin Green www.fontstuff.com
49
Recording Excel Macros
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
Step 28: Finally, compile and test the macro again as described in Steps 20-22. This completes this Step-by-Step exercise.
Summary This is a very useful macro. It was one of the first macros I recorded and I still use it when building and testing spreadsheets. It illustrates several techniques commonly used in VBA programming: •
•
•
•
•
•
•
•
•
Information is held temporarily in Variables. The variables are declared at the start of the macro so that the Excel can set aside an appropriate amount of memory to hold the data when it arrives. The variables are defined with a specific data type reflecting the type of data they will be used for. Programmers usually add a prefix (such as int for Integer or lng for Long) to the name of the variable to indicate the data type (a handy reminder when reading the code later). An Input Box is a kind of message box that can be used to gather input from the user. The input is usually placed into a variable. As well as a message and title, an Input Box can be given a Default value. This serves to assist the user and helps avoid them closing it without making an entry. A With Statement can often be used to replace repeated references to an object that occur on consecutive code lines. They also help speed up code and reduce the amount of typing necessary. Formulas can be written directly into cells by using their FormulaR1C1 property. The formula is entered as a text string, enclosed in quotes. A values held in a Variable can be written into a formula and replace "hard-coded" numbers. This is done by concatenating (joining together) the string and the variable using an ampersand ("and") character (& ).
© Martin Green www.fontstuff.com
50
Recording Excel Macros
What Comes Next? Where Do I Go from Here? A great deal can be achieved by recording macros. Even simple macros can increase your productivity and that of your co-workers dramatically. Using macros to perform routine or repetitive tasks saves time, helps avoid mistakes and ensures uniformity.
n o i t i d E ' s y t l n n e O d u e t s S U l h c a i n w o i n t e a e c r u G d f E o r o y f t i s r e v i n U
If you have followed the tut orials in this document you will have discovered that recording macros and carrying out simple editing tasks is easy. Many Excel users routinely record and use macros and never feel the need to move any further with VBA. But if you really want to unleash the power of macros and exploit Excel to the full you should consider learning VBA. So where should you start? Well, you already have! The Macro Recorder is an excellent learning tool for the person wanting to learn Excel VBA. Even experienced VBA developers occasionally use it to save time or remind themselves how something should be done. Record lots of macros and then look at the VBA code that the Macro Recorder generated. As with the exercises in this document, experiment with editing the code and see if you can improve it, or get it to perform tasks that you couldn't achieve with recording. There are many internet web sites offering help with Excel VBA. Read all the available tutorials you can find and work through the practical exercises. Don't ignore a tutorial because you think you will never use that particular tool or technique. They will all help further your knowledge of VBA.
Recommended Web Sites Martin Green's Office Tips The author's own web site offers a wealth of step-by-step tutorials on VBA in Excel and other Microsoft Office programs. http://www.fontstuff.com The Spreadsheet Page The web site of Excel and VBA guru John Walkenbach has lots of information about Excel and Excel VBA. For macros and VBA follow the link to Excel Developer Tips. http://www.j-walk.com/ss
Recommended Reading If you enjoyed using this book visit the author's web site (http://www.fontstuff.com) for more publications in the series. Microsoft Excel 97 Visual Basic Step by Step by: Reed Jacobson published by: Microsoft Press (ISBN: 1572313188) Although written for Excel 97 the topics covered by this book are applicable to users of all subsequent versions. An excellent starting place for learning Excel VBA this book is full of practical exercises. When you come to require a more comprehensive reference manual you can't do better than one of John Walkenbach's... Microsoft Excel 2000 Power Programming with VBA by: John Walkenbach published by: IDG Books (ISBN: 0764532634) Microsoft Excel 2002 Power Programming with VBA by John Walkenbach published by: M & T Books (ISBN: 0764547992) Microsoft Excel 2003 Power Programming with VBA by John Walkenbach published by: Wiley (ISBN: 0764540726)
© Martin Green www.fontstuff.com
51