18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Part VI<br />

Programming Excel with VBA<br />

Saving Workbooks That Contain Macros<br />

If you store one or more macros in a workbook, the file must be saved with macros enabled, which is a file<br />

with an XLSM extension.<br />

The first time you save a workbook that contains macros, the file format defaults to XLSX — a format that<br />

can’t contain macros. Unless you change the file format to XLSM, Excel displays the warning shown in<br />

Figure 39.4. You need to click No here and then choose Excel Macro-Enabled Workbook (*.xlsm) from the<br />

Save As Type drop-down.<br />

FIGURE 39.4<br />

Excel warns you if your workbook contains macros and you attempt to save it in a nonmacro file format.<br />

Two Types of VBA Macros<br />

Before getting into the details of creating macros, you need to understand a key distinction. A VBA macro<br />

(also known as a procedure) can be one of two types: a Sub or a Function. The next two sections discuss the<br />

difference.<br />

VBA Sub procedures<br />

You can think of a Sub procedure as a new command that either the user or another macro can execute. You<br />

can have any number of Sub procedures in an Excel workbook. Figure 39.5 shows a simple VBA Sub procedure.<br />

When this code is executed, VBA inserts the current date into the active cell, formats it, makes the cell<br />

bold, and then adjusts the column width.<br />

FIGURE 39.5<br />

A simple VBA procedure.<br />

684

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

Saved successfully!

Ooh no, something went wrong!