18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Part VI<br />

Programming Excel with VBA<br />

NOTE<br />

Recording your actions always results in a new Sub procedure. You can’t create a Function<br />

procedure by using the macro recorder. Function procedures must be created manually.<br />

Recording a macro: A simple example<br />

This example demonstrates how to record a very simple macro that inserts your name in the active cell.<br />

To create the macro, follow these steps:<br />

1. Activate an empty cell.<br />

2. Choose Developer ➪ Code ➪ Record Macro. Excel displays the Record Macro dialog box.<br />

3. Enter a new single-word name for the macro, to replace the default Macro1 name. A good<br />

name is MyName.<br />

4. Assign this macro to the shortcut key Ctrl+Shift+N by entering uppercase N in the edit box<br />

labeled Shortcut Key.<br />

5. Click OK to close the Record Macro dialog box.<br />

6. Type your name into the selected cell.<br />

7. The macro is finished, so choose Developer ➪ Code ➪ Stop Recording (or click the Stop<br />

Recording button in the status bar).<br />

Examining the macro<br />

The macro was recorded in a new module named Module1. To view the code in this module, you must activate<br />

the Visual Basic Editor. You can activate the VB Editor in either of two ways:<br />

n Press Alt+F11.<br />

n Choose Developer ➪ Code ➪ Visual Basic.<br />

In the VB Editor, the Project window displays a list of all open workbooks and add-ins. This list is displayed<br />

as a tree diagram, which you can expand or collapse. The code that you recorded previously is stored in<br />

Module1 in the current workbook. When you double-click Module1, the code in the module appears in the<br />

Code window.<br />

Figure 39.8 shows the recorded macro, as displayed in the Code window.<br />

FIGURE 39.8<br />

The MyName procedure was generated by Excel’s macro recorder.<br />

688

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!