Excel VBA - City University Continuing Education Visual Basic for Applications in Microsoft Excel Please note the interface Excel 2007 is radically different to that of previous versions. However I do not expect much, if any, difference within the programming code. File types 1 Introduction ............................................................................................................ 1 2 The Developer tab .................................................................................................. 2 3 Running and recording a macro .......................................................................... 2 3.1 Recording a macro ............................................................................................. 2 3.2 Running a macro ................................................................................................ 4 3.3 A more direct way to record and run macros ................................................ 5 Defining a shortcut once the macro has recorded ...................................................... 5 4 Recording a macro with relative references ....................................................... 6 4.1 What absolute references look like .................................................................. 6 4.2 Relative references ............................................................................................. 6 4.3 Turning relative references on ......................................................................... 6 4.4 The code looks like … ....................................................................................... 6 5 Using the Visual Basic Editor ............................................................................... 7 5.1 Editing a macro .................................................................................................. 7 5.2 Writing a macro from scratch .......................................................................... 7 5.3 Running a macro from VB editor .................................................................... 8 5.4 Stepping through a macro ................................................................................ 8 6 VBA macro language ............................................................................................. 8 6.1 Analysis of a macro ........................................................................................... 8 7 Two inbuilt functions: MsgBox and InputBox ................................................... 8 7.1 MsgBox - the basic function ............................................................................. 8 7.2 InputBox.............................................................................................................. 9 1 Introduction This course is designed for people with a sound knowledge of Excel, who wish to use its Visual Basic for Applications language to create macros. It is aimed particularly at non-programmers, who are prepared to learn and apply programming concepts. A macro is a sequence of mouse- or key-strokes saved under one command. They allow users to automate time-consuming or difficult tasks, so that the user can work more efficiently and with fewer errors. A macro could be used, for example, to format and print a spreadsheet, or to copy and paste blocks of text. One created or recorded, they can be run with one command. Visual Basic for Applications, or VBA, is similar to Visual Basic, which was itself derived from the BASIC programming language. In the early nineties, Microsoft introduced Visual Basic for Windows, which provided tools for creating and controlling elements of the Windows environment. At this time, applications like Word, Excel and Access has their own macro languages, which meant that people had to learn a different language every time they used one of these programs. VBA was introduced first for Excel 5, and then for the other applications in Office 95. Nowadays Word, Access, PowerPoint and Excel all use VBA, making it easier to program in all applications at once. VBA is very similar to Visual Basic in its grammar, except that VBA files are stored in the file format of the application where they were created: for example Excel VBA files are stored in Excel workbooks. The advantage of Excel VBA is that you can directly manipulate the Excel environment, unlike a program that is external. Page 1 of 10 Excel VBA - City University Continuing Education 2 The Developer tab You can add custom controls to a worksheet – the main advantage is that you can make your sheet easier to use by giving it the feel of a finished package In order to get started you must have the Developer tab on your Ribbon, by following these steps: 1. click the icon to display the Office toolbar 2. choose Excel options at the bottom of the display 3. in the window that appears ensure that Popular is highlighted 3 Running and recording a macro There are two steps to using a macro: recording (defining) it and running it (playing it back) 3.1 Recording a macro When you record the macro, you enact the keystrokes or mousestrokes while the recorder stores them in a Visual Basic Module sheet. Macros vary greatly in size and complexity but the recording process follows the same structure: Start recording; Perform the actions to be recorded; Stop the macro. Absolute and relative references in macros – the importance of selecting a block of text before recording the macro If you start recording, then select cells while the recorder is on, the act of selection is also recorded. This means that the macro always runs using this original selection, regardless of what is actually selected at run time. This is because the macro recorder uses absolute referencing by default. However, using relative references can also give unexpected results, so leave this option for now. More on this topic in coming weeks. For the moment, always select a cell before starting the macro recorder! The following example changing the number format of a range of cells: 4. put a tick in the checkbox that says Put the Developer Tag in the Ribbon The Developer tab displays the options to run or record a macro, and to switch to the VB Editor. 1. Open week1.xls 2. Highlight range C6:E9 3. Click the View ribbon Page 2 of 10 Excel VBA - City University Continuing Education 4. On the right there is an icon labelled Macros; click this icon and a menu appears. Click Record Macro. 6. Optionally, you can choose a character for a shortcut key – hold Shift and type I The keyboard shortcut is therefore Shift + i 7. You can optionally type a short description of what the macro does, for later reference 8. Choose OK to close the dialog and return to the spreadsheet. The macro is now recording. 9. You will now perform the actions to format the currency of the selection. 10. From the Home ribbon, click the little icon labelled Number. Hopefully you will recognise the Format Cells window. 5. The Record Macro window appears. The default macro name is Macro1 type the name you want to call the macro, in this case call it CurFormat. (spaces are not allowed in the macro name). 11. Choose Currency in the list box and Kr. Icelandic from the dropdown labelled Symbol Page 3 of 10 Excel VBA - City University Continuing Education 3.2 Running a macro Select a range of cells that you want to apply the new currency format to, e.g., C15:D17 Choose the Macros option (View ribbon, Macros then View Macros) or Developer ribbon, Macros Highlight the macro name and choose Run. 12. Choose OK to return to the spreadsheet. You will see that the numbers have been formatted 13. To stop recording click the View ribbon, click Macro and click Stop Recording from the menu. It’s easy for beginners to forget to stop recording – if so the macro will include lots of unintended actions and you will probably crash Excel and lose your work. Page 4 of 10 Excel VBA - City University Continuing Education The formatting will be applied to the new selection. Select another range of numeric cells, and test your macro by using the shortcut key you defined. Defining a shortcut once the macro has recorded You can do this from the Macros dialog box. It is not possible from the Visual Basic Editor. 1. Choose the Macros option (View ribbon, Macros then View Macros) or Developer ribbon, Macros 2. Choose Options 3. Add/edit the Shortcut key description and choose OK 4. Close the Macro dialog box 3.3 A more direct way to record and run macros At the bottom left of the Excel window there is a scarcely noticeable icon near the word ‘Ready’. This button is record macro. To stop recording you will find the Stop recording button in the same place. Page 5 of 10 Excel VBA - City University Continuing Education 4 Recording a macro with relative references 4.1 What absolute references look like If you have been following the course as taught in class, you will have been recording macros using absolute references such as 4.2 Relative references However, the Macro Recorder can also store a cell select statement relatively in terms of how many cells above/below and to the left/right of the previously selected cell. This involves using something called the Offset property, which looks like this: Range(“H9”).select Rangeobject.Offset(rowoffset,columnoffset) Not to be confused with absolute references in Excel formulas, which involve the $ sign, Range(“H9”) is absolute in the sense that it is not clear which cell has been selected previously: it could have been A1, H8, J9 etc. H9 is H9 is H9. Activecell.Offset(2,3) would be two rows down and three columns to The code might look like this: the right of cell H9 Sub with_absolute_refs() Range(“G10”).Offset(0,-5) would be the same row as G10 and five the right of the active cell Range(“H9”).Offset(-4,3) would be four rows up and three columns to columns to its left ' ' with absolute references - i.e., with ' relative addressing turned off ' ' Keyboard Shortcut: Ctrl+q Range("H9").Select 4.3 Turning relative references on Underneath Record macro on the Developer ribbon is Use Relative References. By ensuring that this option is turned on before recording a macro, you change the way the Macro Recorder writes code when selecting or activating cells. The code this time looks different, with lots of statements such as Activecell.offset(x,y) where x is the row offset and y the column offset. ActiveCell.FormulaR1C1 = "Hello" Range("K11").Select ActiveCell.FormulaR1C1 = "some text" Range("H13").Select ActiveCell.FormulaR1C1 = "Goodbye" Range("E15").Select 4.4 The code looks like … Sub with_relative_refs() ' ' with_relative_refs Macro ' with relative referencing turned on ' End Sub ' Keyboard Shortcut: Ctrl+r Page 6 of 10 Excel VBA - City University Continuing Education ' ActiveCell.Offset(8, 7).Range("A1").Select ActiveCell.FormulaR1C1 = "Hello" ActiveCell.Offset(2, 3).Range("A1").Select ActiveCell.FormulaR1C1 = "some text" ActiveCell.Offset(2, -3).Range("A1").Select ActiveCell.FormulaR1C1 = "Goodbye" ActiveCell.Offset(2, -3).Range("A1").Select End Sub 5 Using the Visual Basic Editor 5.1 Editing a macro You can look at the VBA source code for a macro. 5. Choose the View ribbon, click the Macros icon and choose View Macros 1. Select the macro and choose Edit 2. This opens the Visual Basic Editor as a separate window and brings you to the macro source code, which you can edit. Fortunately the VB Editor hasn’t changed appearance from the previous version 3. You can return to Excel in various ways: click the View Microsoft Excel button, use the taskbar at the bottom, but best of all is keyboard shortcut Alt + F11 The recorded macro is in a text window called a module. The macro is enclosed in between the line beginning Sub and the line End Sub. The green lines that start with a single quote are comments, they are not code, and they don’t have to be there. Therefore the macro code contains only one line. 5.2 Writing a macro from scratch Many times you will want to type a macro from scratch. Insert a new module from the Insert menu, or click in an existing model. Type the key word Sub, followed by a space, then the name of the macro (remember no spaces in the macro name) then an opening and closing bracket. Press return and the line End Sub appears automatically Type your code! But what do you type? You will have to study hard over the next 10 weeks to find out! Page 7 of 10 Excel VBA - City University Continuing Education 5.3 Running a macro from VB editor It can be time saving to run a macro directly from VBE 1. You can run a macro even from the Editor 2. While the cursor is within a macro subroutine, press F5 This runs macro and is very convenient for testing 5.4 Stepping through a macro You can step through a macro to trace the consequence of each line of code 1. Position the Excel and Visual Basic window so each takes up half of the screen. 2. Put you cursor on a line of macro code then press F8 3. A yellow highlight appears, the yellow line is the next line to be executed 4. Keep pressing F8 to step through the code and observe the Excel window to see the effect 6 Sub means start a subroutine. Next comes the name of the macro followed by brackets, which contain arguments. Arguments are data passed to the program; at the moment, your programs have no arguments, but the brackets must still be inserted The macro finishes with End Sub, which simply means the current subroutine is at an end. Both Sub and End are keywords - they have a special meaning for Visual Basic and cannot be used by the programmer in other contexts. You can’t name a macro as “sub” or “end”. 7 Two inbuilt functions: MsgBox and InputBox MsgBox is a function that communicates information to the user while the macro runs. The function takes at least one argument, namely the message (formally, known as the Prompt). You can embellish the box with other information such as a Title or different types of buttons. 7.1 MsgBox - the basic function sub HelloWorld() MsgBox "Hello World" End Sub VBA macro language 6.1 Analysis of a macro All macro code is part of a subroutine. In the VB editor, you will see at the very least these lines in every macro Sub MacroName () End Sub Text after an ' (apostrophe) on the same line is a comment, useful for the writer of the programmer to explain aspects of the code to future readers. The apostrophe stops the text being interpreted as instructions to the program. 7.1.1 MsgBox - with more options The Message Box above is a little stark. You can embellish the box with other information such as a Title or different types of buttons. If so, you can supply more arguments to the MsgBox function. Arguments are separated by a comma Page 8 of 10 Excel VBA - City University Continuing Education sub HelloWorld2() MsgBox "Hello World", vbOKCancel, "Greeting Box" End Sub The second argument determines what button appears in the box. By default it is the OK button., but after you type the first argument to MsgBox and have typed the comma s, a list of possible values for the Button argument appears. 7.2 InputBox An Input box prompts the user to enter some information, which can then be manipulated by your Visual Basic program. A very simple example, would be a box that asks the user to type in their name, so that the program could greet the user. The Syntax for InputBox is as follows: InputBox Prompt, [Title, Default, XPos, YPos,HelpFile, Context] Use Ctrl-Spacebar to bring up this box if it doesn't appear automatically Only the Prompt is obligatory: InputBox "Please enter your name” The third argument is "title", which is the text to appear in the Title bar. It makes the box look more finished, but isn't absolutely necessary. No list of possible values appear when you type this because the text is completely arbitrary as far as VBA is concerned - you choose what the title should be. However, there is little point in providing OK and Cancel buttons unless you know how to program the alternatives, so an OK button is all we need for now. The OKbutton is the default for the second argument, so if you leave it blank, and put two commas between the first and third arguments, the OK button will appear automatically. MsgBox "Hello World",, "Greeting Box" You can also specify: A title – to appear in the title bar of the Input box. A default entry (e.g., for the City where you live, you might put London), which the user can leave or replace X and Y co-ordinates – in pixels - to position the box on screen. 0,0 is the top left of the computer screen. Input box “Please enter your name”, “Name”,”Smith”,5000,4000 You can leave options blank by simply writing a comma to go to the next argument: Input box “Please enter your name”, ,5000, 4000 Page 9 of 10 Excel VBA - City University Continuing Education 7.2.1 For later … Getting the user to type in information is not particularly useful in itself unless you use the information later. This brings us onto variables, which are needed to store data supplied to the macro such as names, addresses and other information. Page 10 of 10