Macros Word Excel
Macros Word Excel
www.intranet.birmingham.ac.uk/itskills
Version: 1, October 2012 2012 The University of Birmingham All rights reserved; no part of this publication may be photocopied, recorded or otherwise reproduced, stored in a retrieval system or transmitted in any form by any electrical or mechanical means without permission of the copyright holder.
Trademarks: Microsoft Windows is a registered trademark of Microsoft Corporation. All brand names and product names used in this handbook are trademarks, registered trademarks, or trade names of their respective holders.
Contents
Page No.
ABOUT THE WORKBOOK....................................................................................................................................1 INTRODUCTION ...................................................................................................................................... 2 VISUAL BASIC PROGRAMS (MACROS) ..................................................................................................... 2 THE MACRO RECORDER .......................................................................................................................... 2 EXAMPLES OF MACROS IN WORD ........................................................................................................... 3 STARTING THE MACRO RECORDER ......................................................................................................................3 MACRO TO WRITE FRACTIONS IN TEXT .................................................................................................................3 SHORTCUT FOR RECORDING A NEW MACRO .........................................................................................................6 MACRO TO NUMBER HEADINGS IN A DOCUMENT IN WHICH HEADING LEVELS HAVE BEEN ASSIGNED ..................................7 MACRO TO INSERT THE FILENAME IN FOOTER .......................................................................................................7 RUNNING WORD MACROS................................................................................................................................9 Using the Developer tab .........................................................................................................................9 Assigning a Macro to a shortcut key ......................................................................................................9 EDIT A MACRO IN WORD.................................................................................................................................10 STORING MACROS TEMPLATE IN WORD .............................................................................................................11 COPYING MACROS FROM ONE TEMPLATE TO ANOTHER ..........................................................................................11 EXAMPLES OF MACROS IN EXCEL .......................................................................................................... 12 MACRO TO PUT A BULLET IN A CELL IN A WORKSHEET ............................................................................................12 FORM CONTROLS .................................................................................................................................. 13 MACRO TO GO TO THE BEGINNING OF THE NEXT LINE WHEN ENTERING DATA IN A FLAT-FILE DATABASE ...........................14 THE VISUAL BASIC EDITOR .................................................................................................................... 16 OPEN THE VISUAL BASIC EDITOR (VBE) .............................................................................................................16 CODE WINDOW ............................................................................................................................................17 PROJECT EXPLORER........................................................................................................................................17 PROPERTIES WINDOW....................................................................................................................................18 CUSTOMISING THE VBA ENVIRONMENT ............................................................................................................19 OBJECT BROWSER .........................................................................................................................................20 CREATING A MACRO BY TYPING IT INTO THE VISUAL BASIC EDITOR ..........................................................................21 OPEN THE VISUAL BASIC EDITOR (VBE) .............................................................................................................21 EDIT A MACRO OR USER-DEFINED FUNCTION IN EXCEL ..........................................................................................22 RUNNING MACROS IN EXCEL ............................................................................................................................23 ADDING MACROS TO THE QUICK ACCESS TOOLBAR ...............................................................................................23 ATTACHING A MACRO TO A BUTTON ON A WORKSHEET .........................................................................................25 ASSIGNING A SHORTCUT KEY TO A MACRO IN EXCEL ..............................................................................................26 CREATING A MACRO TO RESIZE A GRAPH.............................................................................................................26 STORING MACROS IN EXCEL ............................................................................................................................27 Where to Store the Modules ................................................................................................................28 The Personal.xlsb Workbook ................................................................................................................28 DELETING MACROS IN WORD AND EXCEL ............................................................................................. 28 DELETING A MACRO IN WORD .........................................................................................................................28 DELETING A MACRO IN EXCEL ..........................................................................................................................29 USER-DEFINED FUNCTIONS IN EXCEL .................................................................................................... 29 USER-DEFINED FUNCTION TO CALCULATE THE AREA OF A TRIANGLE..........................................................................30 Add a Description to Function Arguments Dialogue box ......................................................................33 USER-DEFINED FUNCTIONS TO CONVERT DEGREES FAHRENHEIT TO CELSIUS AND VICE VERSA ........................................34 FUNCTIONS AVAILABLE IN VBA ........................................................................................................................35
MS Word and MS Excel: Macro Recorder and User-defined Functions (MWX2101) i
USING FUNCTIONS IN OTHER WORKBOOKS ........................................................................................................ 35 A USER-DEFINED WORKBOOK ......................................................................................................................... 36 MACRO VIRUS PROTECTION .................................................................................................................. 36 REFERENCES .......................................................................................................................................... 37
ii
How to do something
Do this first. Then do this. Then do this to finish.
There are also a number of text boxes to watch out for throughout the workbook. These will help you to get the most out of the course.
Tip The thumbs-up symbol in the margin indicates a tip. These tips will help you work more effectively.
Danger! The thumbs-down picture in the margin indicates common mistakes or pitfalls to be avoided.
Introduction
This course is designed to introduce the use of Macros in Word and Macros and User-Defined Functions in Excel (all Visual Basic Programs) to those who use Word and Excel quite a lot but have never got round to using them. In particular, the issues relating to the storing of modules macros and user-defined functions so that they are always available when needed will be discussed. The use of the Macro Recorder to record simple macros in Word and Excel will be covered. We will look at the code produced by the recorder and indicate how it can be modified to be more efficient. This is an effective way of not only learning some Visual Basic for Applications but also of learning how Word and Excel actually do the things they do; the instructions that Word and Excel give themselves! Why might we want to record or write macros? Because if there are sequences of instructions that we repeat over and over again in exactly the same way every time we perform them it is advantageous to record the entire sequence so that Word or Excel can do them by carrying out a single instruction from us rather than several instructions. It might also be useful if a procedure is long and/or complicated and you dont want to have to remember it every time.
Or
Click on the Developer tab, (to display the Developer tab if its not visible on the ribbon) Click on the File tab, click on the Options button (the Word Options dialogue box appears). Click on Customize Ribbon and on the right under Main tab, select Developer tab Click on the OK button to display the Developer tab on the ribbon. Click on the Developer tab and in the Code group, click on the Record Macro.button.
Tip - Rehearse! Before recording a macro using the Macro Recorder, it is as well to practise what you are going to do a couple of times before setting out to record it: first to make sure that it works (that the macro does what you want it to do), and secondly so that when you come to record you go through the instructions correctly in the most efficient way possible.
Under Macro name: in the text box Macro1 is the default name, type a name - e.g. Fractions no spaces allowed in macro names (dont worry at this stage about a Keyboard shortcut key). Click on the OK button. Notice that the cursor changes to and any thing you do will be recorded. The Macro button on the Status Bar at the bottom left of the screen gives you information about the macro.
Press Ctrl Left Arrow three times, to move to the beginning of the fractions. Press Shift Ctrl Right Arrow once to select the numerator (which may be more than one digit). Click on the Home tab, in the Font group, click on the Font launcher to display the Font dialogue box.
Click on the Advanced tab, under Character Spacing tab, click on the arrowhead to the right of Position: select Raised and raise the number by 1 pt. Click on the OK button to go back to the document. Press Right Arrow once to get past the first number. Press Shift Right Arrow to select the slash. Click on the Insert tab, in the Symbols group, click on Symbol and select More Symbols... (the Symbols dialogue box appears). Select the Symbols font, scroll down and Select the forward slash shown below:
Click on the Insert button or double-click on the slash to insert it into the document. Click on the Close button to go back to the document. Press Shift Ctrl Right Arrow to select the second number denominator. Click on the Home tab, in the Font group change the font size to make the denominator 8pt or 9pt depending on the size of your text. Press Right Arrow.to cancel the highlight. Click on the Home tab, in the Font group change the font size back to 12 pt. Stop the recorder by clicking on the Developer tab, in the Code group, click on Stop Recording.
The Visual Basic code as created by the Macro Recorder to write fractions in text is shown below:
Macro to number headings in a document in which heading levels have been assigned
It might be quite useful to have a macro to insert heading numbering in a document for two reasons: first because Word has a habit of not remembering to number headings when a document has been saved and closed and then opened again, and secondly if you like to have customised heading numbering rather than one of the built-in default styles. You need to have already assigned heading levels 1,2,3 etc. to the text (paragraphs) that make up your headings. Also it works better if you are actually in a Level 1 heading when you do this.
The Macros dialogue box appears type a macro name; e.g. Custom_Footer, (dont worry at this stage about a shortcut key) Click on the OK button, everything you do is being recorded. Click on Insert tab, in the Header & Footer group, click on Footer and select Edit Footer. The cursor should now be on the left-hand side in the Footer. Click on the Insert tab, in the Text group, click on Quick Parts
Under Categories: click on the arrowhead and select Document Information Under Field names: select FileName, you can also select a format if you wish and Add the path to the filename. Click on the OK button to go back to the footer area. If you want a border above the entire footer, click on the Home tab, in the Paragraph group, click on the arrowhead to the right of the Borders button and select Top Border
Using the Developer tab To run the macro to insert a filename in the footer:
Place the cursor in the footer and then run the macro.(click on the Insert tab, click on Footer and select Edit Footer) Click on the Developer tab, in the Code group, click on the Macros button alternatively, press Alt F8, (the Macros dialogue box appears):
Under Macro name: any macros you have created will be listed, scroll down the list until you come to the Macro you want to run, select it. Click on the Run button
Click on the Options button to display the Word Options window. Click on Customize Ribbon on the left and under Choose commands from: click on the arrowhead and select Macros, a list of existing macros are displayed.
Click on the Customize button at the bottom of the window, (the Customize Keyboard dialogue box appears). Type a shortcut key combination in the Press new shortcut key: text box. Click on the Assign button and then Close.
Danger! Do not overwrite an existing shortcut key combination and BEWARE OF COMBINATIONS SUCH AS ALT+F because Word will tell you this is UNASSIGNED but in fact it is the Windows shortcut key for the Office menu Also be aware that other applications you may have open while using Word, such as Hypersnap, also respond to keyboard shortcuts and you may not want to clash with these.
10
To close the VBE screen and go back to the Word document, click on the Close button alternatively, press Alt F11. at the top right of the screen,
Click on the Macro Project Items tab, you will need to specify the document template you want to copy the macro to. If the template you want is not showing in the Organizer dialogue box. Click on the Close File button. The Close File button will then be replaced by an Open File button, which automatically opens the template folder C:\Documents and Settings\your username\Applications Data\Microsoft\Templates and you can select the template you want.
11
Select the source template on one side of the screen and destination template on the other side Click on the Copy button. This will put a copy of the macro onto the destination template. Click on the Close button.
In the Macro name: text box type the macro name; e.g. bullet no spaces are allowed in the macro name. Dont worry at this point about a shortcut key unless you want to. Click OK. The recorder is now running and everything you do will be recorded. Press and hold down the Alt key type 0149 on the numeric keypad (Num Lock must be on). A bullet should appear both in the cell and in the Formula bar
12
Click on the Enter button (the tick) to the left of the Formula bar or press Enter. The bullet is inserted the cell. To stop the Recorder. Click on the Developer tab, in the Code group, click on Stop Recording, alternatively click on the Macro button at the bottom left of the screen
Relative or absolute references? An absolute reference always refers to the same location, while a relative reference works relative to where the cursor is currently positioned. Suppose we place the cursor in the cell A4 and record a macro to move to D4. If the macro is recorded with absolute references then we will always return to D4 when we run the macro. If we record the macro with relative references the cursor will move four cells to the right from the starting cell.
Form controls
Excel allows us to add form controls to a worksheet. By form controls, we mean elements such as tick boxes, buttons to click on, spinners, scroll bars, and lists to pick from. We can have elements on the worksheet that we are more used to seeing as part of a dialogue box. To create the form controls we need to have the forms toolbar displayed on screen.
Check box Spin button Combo Box Button Option Group Label Scroll bar Text Field Combo List List box Option button Combo Drop-Down - Edit
13
We can also connect the control to a cell on the spreadsheet so that we can use the control to enter a range of data.
Set any properties required. This screenshot shows the options for a spin button control.
My option buttons dont work properly To create option buttons successfully, we first need to create an option group. Then we create the option buttons within the option group. If we just create the buttons on the worksheet without an option group (or outside its border) then Excel doesnt know which set of options the button is supposed to relate to.
Macro to go to the beginning of the next line when entering data in a flat-file database
When entering data in what is effectively a flat-file database in Excel it is something of a nuisance to have to make several key presses to get to the beginning of the next line each time you wish to enter a new record. You can automate this and make the entire move with one click of the mouse or a keyboard shortcut combination by recording the moves in a macro.
14 MS Word and MS Excel: Macro Recorder and User-defined Functions (MWX2101)
It is probably best to change the way in which Excel behaves when editing and entering data and make the use of the Enter key behave in the same way as clicking on the tick in the formula bar; that is, the cursor remains in the cell which you were editing.
To create a macro to go to the beginning of the next line when entering data in a flat-file database:
Click on the File tab, click on the Options button to display the Excel Options window, click on Advanced and under Editing options deselect After pressing Enter, move selection
Make sure you are in the last cell of one of your data records having entered the data in the cell. Click on the Macro button at the bottom left of the Status bar Give macro a name; e.g. down_left, click OK. You are now recording. Click on Relative Reference button. Press the down arrow, then left arrow as many times as you need to get to the first cell of the next record Stop the recorder by clicking on Stop Recording button at the bottom left of the Status bar.
15
If the two sections are not visible, follow the instructions for the individual sections.
16
Code Window
The code window is obviously the most important area. The list box at the top right-hand side of the window allows selection of individual Subroutines and the code produced by the Macro Recorder is displayed in the window. By default, individual parts of the macro are colour coded, and should look something like the script above. First comes the start of the Subroutine. Two comment lines in green beginning with a single quote mark follow this. These give the name of the macro and any explanatory information you may wish to add. Next, come the actions, then the final line Ending the Subroutine. Note that some lines are inset automatically for ease of reading.
Project Explorer
If the Project Explorer (Project VBAProject pane) is not visible:
Click on the Project Explorer button on the VBA Standard toolbar, alternatively, press Ctrl R to display the pane together with the tree structure for the VBA Project associated with the workbook. You can expand the Microsoft Excel Objects Folder ( + ) displays the individual worksheets in the workbook. Expanding the Modules folder displays the icon for the code Module1. Double clicking on the module will display the Code Window for the module.
17
Note that the workbook appears as a VBA Project. This is a new term intended to bring the worlds of Visual Basic and Excel together! The Project (i.e. workbook) also has any attached VBA modules inside it and is associated with any loaded add-ins, such as the XY Chart Labeler. Any workbooks in the XLSTART folder and your personal StartUp folder (if you have one) will also appear in the Project Explorer list (even if the workbooks are hidden). In particular this means that you will see the special Personal.xlsb workbook which Excel creates as a general-purpose storage area for macros, and which is stored in the XLSTART folder.
Properties Window
Immediately below the Project Explorer is the Properties Window that displays properties of any selected item in the Project Explorer.
This window displays the properties of any object selected in the Project Explorer window. Editing in the Name box allows you to change the name of the project.
18
Note In Excel and PowerPoint the default name for all projects is VBAProject. In Word, the default is Project Normal (when attached to templates) or Project (when attached to a document).
Under the Editor tab it is best to enable the Auto Syntax Check option which will display a dialogue if any syntax errors occur while entering code. Auto List Members displays a list that contains information that logically completes the statement you are typing. The Editor Format tab allows settings for the display of code including font and text colour.
19
Object Browser
This tool allows you to look through all the available VBA Objects.
20
Type the following macro code to make Excel pick up the text in a cell and make it the filename.
Sub SaveFile() Dim ThisFileName As String ThisFileName = Range(A1).Value ActiveWorkbook.SaveAs Filename:=ThisFileName End Sub The finished code should look like this when displayed in VBE
21
Click on the Close button to close the VBE screen, and then run the macro. Excel will pick up the text that is stored in cell A1 and make it the filename for the workbook.
Or Click on the View tab, in the Macros group, click on Macros and
then click on View Macros to display the Macros dialogue box, select the Macro you want to edit and click on the Edit Button.
22
Click on the arrowhead and select Macros a list of macros is displayed, select the macro you want to add to the Quick Access Toolbar and click on the Add button. The macro default symbol is you can change this symbol if you wish by selecting the macro.
Click on the Modify button, (the Modify Button window appears) with lots of different symbols.
24
Insert
The Assign Macro dialogue box opens automatically. Select the appropriate macro name and click OK.
The button remains selected allowing you to change the label from the default Button1 to something appropriate.
Click off the button to deselect it and then test the macro, by clicking on it. To rename the button right-click on the button and select Edit Text.
25
Danger! Please see page 9, Assigning a macro to a shortcut key. Be aware as Excel does not warn you if you are overwriting an existing keyboard shortcut of any kind; e.g. in Excel, in Windows, in another application, such as Hypersnap.
The final thing we need to do is some error trapping, to get around the problem of what would happen if the macro was run and no chart was selected.
26
To trap errors:
Below the last line of comments add the line:
Where should I store the macro? We have the choice of storing the macro in this workbook, a new workbook or in a personal macro workbook. If we store the macro in a personal macro workbook the macro will be available whenever we have an Excel file open. If we store the macro in this workbook or a new workbook then it will only be available when that particular workbook is open.
27
Any open workbooks, (both hidden and visible) appear in the Project Explorer where their properties and code can be edited.
28
Select the macro you want to delete and click on the Delete button, the following dialogue box appears, click on the Yes button to delete the macro.
Items in square brackets [] are optional. Words in Bold are required. Name Arglist Type Statements Expression The name given to the function. List of arguments passed to the function (arguments are separated by commas). Data type of the value returned by the function. A valid Visual Basic statement. Expression to set the value returned by the function.
We will create some simple user-defined functions: one to calculate the area of a triangle, given the length of two adjacent sides and the included angle and two others to convert degrees Celsius to Fahrenheit and vice versa.
MS Word and MS Excel: Macro Recorder and User-defined Functions (MWX2101) 29
area of a triangle:
Area = ab sin()
D4 contains the formula = 0.5*A4*B4*SIN(RADIANS(C4)) to test the user defined function. Press Alt F11 to open the Visual Basic Editor and click on the Insert menu and select Module. Type in the code below. As you type the keywords the Auto List Members option will supply a list of appropriate options to complete the statement. Type in the comment line starting with an apostrophe.
'Calculates the area of a triangle given two sides and the included angle. Function TRIAREA(sideA, sideB, Angle) Alpha = Application.WorksheetFunction.Radians(Angle) 'Deg to Radian TRIAREA = 0.5 * sideA * sideB * Sin(Alpha) 'Calculate area End Function
30
The comment line, shown in green, is preceded by an apostrophe. The code starts with keyword Function (shown in blue) followed by the name of the user defined function and its three arguments. These will be shown in the Insert Function dialogue box as typed. The calling formula passes the values of its arguments to the function by position rather than by name.
The following line is an assignment statement where the variable Alpha is given a value. As the angles are entered in degrees in the worksheet they must be converted to radians before the value is used in a trigonometric function. Here the worksheet function Radians has been used, hence the keywords Application.WorksheetFunction. In the final assignment statement, the function is given a value that is returned to the worksheet. The trigonometric function sine is available in Visual Basic and does not require the Application.WorksheetFunction qualifier. The final line contains the obligatory End Function (shown in blue). Save the codes and return to the Excel worksheet and enter the formula using the newly created function in E4.
31
You should find TRIAREA in the Insert Function dialogue box under User-Defined functions. Scroll down the function list and select the function e.g. TRIAREA. Click on the OK button to display the Function Arguments dialogue box
Enter the values from the worksheet in each text box and click on the OK button
32
To add a description:
Activate the worksheet in the workbook containing the User-defined function. Press Alt F8 to display the Macro dialogue box.
In the Macro Name: text box, type the function name e.g. TRIAREA. Click on the Options button and type a description in the Macro Options dialogue box.
33
Click on the OK button to close the Macro Options dialogue box. Click on the Cancel to close the Macros dialogue box. Check the Insert Function dialogue box and notice the description has changed.
Now below Cels(Fahren) enter the code for the second function:
34
You can use the Office Assistant to find the worksheet functions available to Visual Basic by clicking the Help button and searching for "worksheet functions". Not all worksheet functions are available as many are provided as VBA built in functions. These run more efficiently than worksheet functions. Perversely the VBA functions are more difficult to find. Activate the Object Browser (see page 19) and search, for example, on format. A list of VBA formatting functions appears. Currently the user-defined function is available in any sheet of the current workbook.
Note If you wish to access the function from another workbook the name of the workbook containing the function must be included. e.g. = MyFuncs.xls!TRIAREA(A4,B4,C4) This is not necessary if the function is installed as an add-in.
35
A User-Defined Workbook
The most convenient storage method is to create an auto-loading workbook that is also hidden. Hidden workbooks can be edited from the Visual Basic Editor.
The virus payload can be a simple message, a replication of itself (as in the most successful Excel virus, Laroux), cause corruption of your files, or re-format your computers hard drive. The Word virus Switcher, for example, attempts to delete *.xls (Excel) and *.mdb (Access) files (among others) and the Excel Melissa clone Papa virus posts itself to the first 50 contacts in your Outlook addresses book.
36
To adjust the security level for files that might contain macro viruses
Click on the Developer tab, in the Code group click on Macro Security. Select the required option.
References
As an excellent starter try the unfortunately named: Excel VBA Programming for Dummies, by John Walkenbach, published by Hungry Minds Inc. More advanced references are: Microsoft Excel 2007 Visual Basic for Applications Step by Step by Reed Jacobson, published by Microsoft Press International. Microsoft Excel Developers Handbook by Eric Wells, published by Microsoft Press International. Excel 2007 Power Programming with VBA (Mr. Spreadsheets Bookself), by John kWalkenbach.
37