Excel Macros – Quick Guide to VBA Coding Contents Adding a Button to an Excel Spreadsheet ........................................................................................ 1 Variable Types in VBA ............................................................................................................................ 2 IF Statements in VBA .............................................................................................................................. 2 Strings of Text in VBA ............................................................................................................................ 4 Programing Loops in VBA ..................................................................................................................... 4 Cell Properties .......................................................................................................................................... 6 Record Macro ............................................................................................................................................ 6 Adding a Button to an Excel Spreadsheet Locate the Controls panel on the Developer toolbar, and then click the Insert item. From the Insert menu, click the first item, which is a button: Now move your mouse to your spreadsheet. Hold down your mouse and draw out a rectangular button. As soon as you let go of the left mouse button you'll see the Assign Macro dialogue box appear: Select your Macro from the list and click OK. You can edit the text on a button. Right click the button to see a menu appear. From the menu, select Edit Text: 1 When you select Edit Text, a cursor will appear at the start of the text, and you can name the button. Variable Types in VBA In order to set a variable, you must declare the type of variable you are setting. This can be done using ‘Dim’ Example: Dim MyVariable as Integer Example 2: Dim MyVariable as Integer = 5 Variable types and values can be declared in the same or different lines in VBA. Variable names cannot start with a number, have spaces, or include special characters. The various types of variables you can declare are: As Integer As Long (alternative to As Integer, used when storing many numbers in one variable) As Single (used to store precision data, and store many decimal places) As Double (similar to As Single, but more precise) As String (used when storing words or characters) IF Statements in VBA Programming in any language is heavily reliant on Conditional Logic like the IF Statement. It allows you to go down different paths, depending on an initial condition. The structure of a VBA IF Statement looks like this: If <Condition_To_Test> Then 2 <'CODE HERE> End If You start with the word If (uppercase "I" lowercase "f"). After a space, you have a condition that you want to test. This conditional is something that can either be TRUE or FALSE. After your condition, you type a space followed by the word Then (uppercase "T"). An If Statement ends with the words End If. Create a new Sub in your coding window, and call it If_Test_1. Add the following code for your Sub: Dim MyNummber As Integer MyNumber = 10 If MyNumber = 10 Then MsgBox "Number = 10" End If 3 Strings of Text in VBA Setting up a variable to hold text is quite straightforward. You simply Dim a variable As String: Dim MyString As String To store text inside of your variable you need to surround it with double quotes: MyString = "Some text" Even if you place numbers between double quotes they still gets treated as text and not Integers: MyString = "25" The above line means store 25 as text, and NOT store the number 25. You can place text into a cell on your spreadsheet: Dim MyString As String MyString = "Some text" ActiveCell.Value = MyString And you can get text out of cell on your spreadsheet: Dim MyString As String MyString = ActiveCell.Value Programing Loops in VBA The most common type of loop is called a For Loop. Bear in mind that a For Loop goes round and round until it meets an end condition. Once the end condition is met then the programming flow will continue downward, in its natural direction. 4 The following will run you through an example of a sample code involving a For Loop. answer = 1 We've added a new Integer variable called answer. The message box has been moved to the end. Between the For line and the Next line we have some new code. This: answer = answer + StartNumber To understand this line, start after the equal sign: answer + StartNumber This says, "Add together whatever is stored in the variable called answer and whatever is stored in the variable called StartNumber. However, we haven't stored anything in the answer variable yet. So what value does it hold? If you don't store a value in an Integer variable then it gets set to 0. TheStartNumber variable is 1 the first time round the loop. So the sum on the right of the equal sign is really this: 0+1 When VBA has finished calculating this it needs to store the result somewhere. That "somewhere" is whatever you have to the left of the equal sign. We have the variable called answer to the left of the equal sign. So this is where VBA stores the result of 0 + 1. In other words, the answer variable will be overwritten with the new value. The next time round the loop the two variables to the right of the equal sign will hold the following values: 1+2 The third time round the loop the two variables to the right of the equal sign will be this: 3+3 But by going round the loop 5 times, we've added up the numbers from 1 to 5. This gives a value of 15. Run your programme and test it out. The message box should display an answer of 15. 5 Now run the code. The message box displays 5 times, once for each time round the loop. This time, the values will be the same as from our table above, from the left-hand column under answer = Cell Properties As well as referring to cells on a spreadsheet with Range you can use Cells. The Cells property has an Item property that you use to reference the cells on your spreadsheet: Worksheets(“Sheet1”).Activate [selects the sheet] Range(“A1”).Select or Range(“A1:B1”).Select [this selects the cell] Or alternatively: Cells.Item(Row, Column) The Row is always a number. But the column can be a number or letter: Cells.Item(1, 1) Cells.Item(1, "A")x`` You can shorten this even further and get rid of the Item property altogether: Cells(1, 1) Cells(1, "A") After selecting a cell, you can do a range of functions on that cell like Range(“A1”).copy, Range(“A1”).paste, Range(“A1”).Value = “NewValue”, Range(“A1”).Offset(1,1) are a couple examples. Record Macro 1. On the Tools menu, point to Macro, and then click Record New Macro. In the Macro name box, enter a name for the macro. Notes 6 The first character of the macro name must be a letter. Other characters can be letters, numbers, or underscore characters. Spaces are not allowed in a macro name; an underscore character works well as a word separator. Do not use a macro name that is also a cell reference or you can get an error message that the macro name is not valid. 2. If you want to run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box. You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters), where letter is any letter key on the keyboard. The shortcut key letter you use cannot be a number or special character such as @ or #. NOTE The shortcut key will override any equivalent default Microsoft Excel shortcut keys while the workbook that contains the macro is open. 3. In the Store macro in box, click the location where you want to store the macro. If you want a macro to be available whenever you use Excel, select Personal Macro Workbook 4. If you want to include a description of the macro, type it in the Description box. 5. Click OK. If you want the macro to run relative to the position of the active cell, record it using relative cell references. On the Stop Recording toolbar, click Relative Reference so that it is selected. Excel will continue to record macros with relative references until you quit Excel or until you click Relative Reference again, so that it is not selected. 6. Carry out the actions you want to record. 7. On the Stop Recording toolbar, click Stop Recording . 7