Excel 2010 Bible

(National Geographic (Little) Kids) #1

Part VI: Programming Excel with VBA


800


The CurrentDate macro also includes a comment. Comments are simply notes to yourself, and
they’re ignored by VBA. A comment line begins with an apostrophe. You can also put a comment
in the same line as a statement. In other words, when VBA encounters an apostrophe, it ignores the
rest of the text in the line.

You execute a VBA Sub procedure in any of the following ways:

l Choose Developer ➪ Code ➪ Macros to display the Macro dialog box. Select the proce-
dure name from the list and then click Run. You can also access the Macro dialog box by
pressing Alt+F8.

l (^) Press the procedure’s shortcut key combination (if it has one).
l If the VB Editor is active, move the cursor anywhere within the code and press F5.
l (^) Execute the procedure by calling it from another VBA procedure.


VBA functions

The second type of VBA procedure is a function. A function always returns a single value (just as a
worksheet function always returns a single value). A VBA function can be executed by other VBA
procedures or used in worksheet formulas, just as you would use Excel’s built-in worksheet
functions.

Figure 39.6 shows a custom worksheet function. This function is named CubeRoot, and it
requires a single argument. CubeRoot calculates the cube root of its argument. A Function pro-
cedure looks much like a Sub procedure. Notice, however, that function procedures begin with
the keyword Function and end with an End Function statement.

On the CD
A workbook that contains this function is available on the companion CD-ROM. The file is named cube root
.xlsm.


FIGURE 39.6

This VBA function returns the cube root of its argument.

Free download pdf