Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

VBA Guide Sheet

Download as pdf
Download as pdf
You are on page 1of 7
Excel Macros — Quick Guide to VBA Coding Contents Adding a Button to an Excel Spreadshect.... Variable Types in VBA IF Statements IN VBA... Strings of Text in VBA Programing Loops in VBA... Cell Properti Record Macro. Addi 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 Ce mouse and draw out a 5 rectangular button. As soon as On ZS © you let go of the left mouse O45 wl button you'll see the Assign ActiveX Controls Macro dialogue box appear: ofMaal BosBen. 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: 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 Sub Vartapie Practice) Dim Myitunber As Inceger Variable types and values can be declared in the same or different lines in VBA. Variable names cannot start wymamber = 10 with @ number, have spaces, or include special End Sub characters The various types of variables you can declare are: As Integer AsLong (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 Then <'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 ). 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 Sub If_Test_10) MyNumber = 10 lf MyNumber = 10 Then MsgBox “Number = 10" MyNumber = 10 If MyNumber Dim MyNunmber As Integer MsgBox "Number 10 Then End If End if End Sub Operator Meaning = Has a value of < Less than > Greater than <= Less than or equal to >= Greater than or equal to <> Not equal to Sub If Test_30) Dam Myunmber As Integer MyNumber = MS Miogbox Miunber ¢" ie Less than 20" End If End Sub 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. The following will run you through an Seb TeopExanpie () example of a sample code involving a For Dim scaxcimaber as Tavege= Loop. Dim EndNunber As Integer Dim answer As Integer answer = 1 Endlumber = 5 We've added a new Integer variable For StartNumber = 1 To End¥unber called answer. The message box has been moved to the end. Between the For line answer = answer + StartNunber and the Next line we have some new code. This: Next StartNunber MsgBox answer answer = answer + StartNumber End Sub 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: o+4 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: 142 The third time round the loop the two variables to the right of the equal sign will be this: 343 But by going round the loop 5 times, we've added up the numbers from 4 to 5. This gives a value of 15. Run your programme and test it out. The message box should display an answer of 15. 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.ltem(Row, Column) The Row is always a number. But the column can be a number or letter: Cells.ltem(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 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. 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 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. . If you want to include a description of the macro, type it in the Description box. 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 itis selected. Excel will continue to record macros with relative references until you quit Excel or until you click Relative Reference again, so that itis not selected. Carry out the actions you want to record. . On the Stop Recording toolbar, click Stop Recording . [31]

You might also like