BEHIND THE SCENES: THE VBA ENVIRONMENT

Now that you’ve recorded your macro, let’s find out what Excel did. When you clicked OK in the Record Macro dialog box, Excel created something called a module in the active workbook.

As you entered the company name and address in the worksheet, Excel recorded your actions and inserted the corresponding VBA code in the module.

The new module doesn’t appear with the other sheets in the workbook; to view the module, choose Tools, Macro, Macros. Next, select the MyPolyAddress macro, and click the Edit button. The Visual Basic Editor (VBE) starts up, and the module that contains the MyPolyAddress macro appears.

A module looks like a window that you might see in a word processing program. The menu bar above the module includes menus for editing, debugging, and running VBA code.

In the module you can review, enter, copy, move, insert, and delete VBA statements and comments using techniques that are similar to those you use in a word processing program.

Of course, because the VBE is a separate application, you can switch back and forth between your Excel workbook and the VBE by clicking the appropriate button in the Windows taskbar.

Let’s focus only on the code we’ve recorded. On the right side of the VBE is a window displaying the module containing the code:

Sub MyPolyAddress()
'
' MyPolyAddress Macro
' Macro recorded 10/26/2006 by  Ming Leung
' Display my Poly address.
'
' Keyboard Shortcut: Ctrl+Shift+A
'
    Columns("A:A").ColumnWidth = 17.14
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "Prof. Ming Leung"
    Range("A3").Select
    ActiveCell.FormulaR1C1 = "Polytechncic University"
    Range("A4").Select
    ActiveCell.FormulaR1C1 = "Six Metrotech Center"
    Range("A5").Select
    ActiveCell.FormulaR1C1 = "Brooklyn, NY 11201"
    Range("A6").Select
End Sub
The first and last lines of the code act as the beginning and endpoints for the macro you’ve recorded; a Sub statement starts the macro and names it, and an End Sub statement ends the macro.

You’ll notice that special VBA terms, called keywords, are displayed in dark blue. (You can view and change the colors assigned to various elements of a macro by choosing Tools, Options in the VBE and clicking the Editor Format tab.)