Tuesday, July 19, 2011

How to Write an Excel VBA Program


1. Find the Excel file that you want to augment by including a VBA program. Double-click on the file to open the spreadsheet.
2. Hold down Alt and press F11 to open the VBA editor. The editor will open up in a new window.
3. Right-click on any of your worksheets, which will be listed in the thin column on the left side of the VBA editor. Move your mouse over 'Insert' and select 'Module.' This will add a new module, which is just something to hold your VBA program, to the list. Double-click on the module that appears, and the right half of the VBA editor will turn white.
4. Click on the right side of the VBA editor. A blinking cursor appears. Enter the following code into the editor:Sub Name()Change 'Name' to whatever you want to name your subroutine. Press Enter to complete the line and the VBA editor will automatically place the 'End Sub' command on a line beneath the cursor. This is how you will start all macros that you create in VBA.
5. Create your program's variables on the next few lines. Start each line with the word 'Dim,' which signifies that you are creating a variable. Type the name of the variable followed by the word 'as,' then the type of variable. For example, both 'Dim x as Integer' and 'Dim y as Variant' are acceptable. If you have multiple variables of the same type, place them on the same line separated by a comma, such as 'Dim x, y as Integer.'
6. Enter the actual code for your program beneath the variables. Enter your code in lowercase, as VBA will automatically capitalize commands that it recognizes, which can help you write your code. VBA will help you complete certain commands. For example, when you enter 'Range(' to begin a line of code that will select a range of cells on the worksheet, VBA will display a small box next to your cursor telling the correct format to complete the argument. When you get to a point in your code where it is obvious that you will need to call certain functions, VBA will automatically display a list of all the functions, letting you select from the list instead of typing it in.

Blogger news