Introducing VBA macros
Creating VBA macros
Recording VBA macros
More about recording VBA macros
Writing VBA code
Learning more about VBA
This chapter is an introduction to the Visual Basic for Applications (VBA) macro language — a key component for users who want to customize and automate Excel. This chapter teaches you how to record macros and create simple macro procedures. Subsequent chapters expand upon the topics in this chapter.
In its broadest sense, a macro is a sequence of instructions that automates some aspect of Excel so that you can work more efficiently and with fewer errors. You may create a macro, for example, to format and print your month-end sales report. After the macro is developed, you can then execute the macro to perform many time-consuming procedures automatically.
You don't have to be a power user to create and use simple VBA macros. Casual users can simply turn on Excel's macro recorder: Excel records your actions and converts them into a VBA macro. When you execute this macro, Excel performs the actions again. More advanced users, though, can write code that tells Excel to perform tasks that can't be recorded. For example, you can write procedures that display custom dialog boxes, add new commands to Excel's menus, or process data in a series of workbooks.
If you plan to work with VBA macros, you'll want to make sure that the Developer tab is present on the Excel Ribbon. The Developer tab, which does not appear by default, contains useful commands for VBA users. To display this tab
Choose File Options.
In the Excel Options dialog box, select Customize Ribbon.
In the list box on the right, place a check mark next to Developer.
Click OK to return to Excel.
Figure 39.1 shows the Ribbon commands of the Developer tab.
Macros have the potential to cause serious damage to your computer, such as erasing files or installing malware. Consequently, Microsoft has added macro-security features to help prevent macro-related problems.
Figure 39.2 shows the Macro Settings section of the Trust Center dialog box. To display this dialog box, choose Developer Code Macro Security.
By default, Excel uses the Disable All Macros with Notification option. With this setting in effect, if you open a workbook that contains macros (and the file is not digitally "signed"), the macros will be disabled, and Excel displays a Security Warning above the Formula bar (see Figure 39.3). If you're certain that the workbook comes from a trusted source, click the Enable Content button in the security warning area, and the macros will be enabled. Excel remembers your decision; if you enable the macros, you will not see the Security Warning the next time you open that file.
NOTE
If the Visual Basic (VB) Editor window is open when you open a workbook that contains macros, Excel does not display the Security Warning above the Formula bar. Rather, it displays a dialog box with two buttons: Enable Macros and Disable Macros.
Rather than deal with individual workbooks, you may prefer to designate one or more folders as "trusted locations." All the workbooks in a trusted location are opened without a macro warning. You designate trusted folders in the Trusted Locations section of the Trust Center dialog box.
If you store one or more VBA macros in a workbook, you must save the file with an XLSM extension.
The first time you save a workbook that contains macros, the file format defaults to XLSX — and this format can't contain macros. Unless you change the file format to XLSM, Excel displays the warning shown in Figure 39.4. You need to click No, and then choose Excel Macro-Enabled Workbook (*.xlsm) from the Save As Type drop-down list in the Save As dialog box.
NOTE
Alternatively, you can save the workbook in the old Excel 97-2003 format (which uses an XLS extension). This file format can contain macros.
Before getting into the details of creating macros, you need to understand a key distinction. A VBA macro (also known as a procedure) can be one of two types: a Sub or a Function. The next two sections discuss the difference.
You can think of a Sub procedure as a new command that either the user or another macro can execute. You can have any number of Sub procedures in an Excel workbook. Figure 39.5 shows a simple VBA Sub procedure. When this code is executed, VBA inserts the current date into the active cell, applies a number format, makes the cell bold, and then adjusts the column width.
NOTE
A workbook that contains this macro is available on the companion CD-ROM. It also includes a button that makes it easy to execute the macro. The file is named current date.xlsm.
Sub procedures always start with the keyword Sub, the macro's name (every macro must have a unique name), and then a pair of parentheses. (The parentheses are required; they're empty unless the procedure uses one or more arguments.) The End Sub statement signals the end of the procedure. The lines in between comprise the procedure's code.
What's New in the Visual Basic Editor?In a word, nothing. Beginning with Excel 2007, Microsoft made many changes to Excel. However, the VB Editor has remained untouched. The VBA language has been updated to accommodate the new Excel features, but the VB Editor has no new features, and the toolbars and menus work exactly like they always have. |
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:
Choose Developer Code Macros to display the Macro dialog box. Select the procedure name from the list and then click Run. You can also access the Macro dialog box by pressing Alt+F8.
Press the procedure's shortcut key combination (if it has one).
If the VB Editor is active, move the cursor anywhere within the code and press F5.
Execute the procedure by calling it from another VBA procedure.
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 procedure looks much like a Sub procedure. Notice, however, that function procedures begin with the keyword Function and end with an End Function statement.
NOTE
A workbook that contains this function is available on the companion CD-ROM. The file is named cube root.xlsm.
NOTE
Creating VBA functions that you use in worksheet formulas can simplify your formulas and enable you to perform calculations that otherwise may be impossible. Chapter 40 discusses VBA functions in greater detail.
Some DefinitionsIf you're new to VBA, you may be overwhelmed by the terminology. I've put together some key definitions to help you keep the terms straight. These terms cover VBA and UserForms (custom dialog boxes) — two important elements that are used to customize Excel:
|
Excel provides two ways to create macros:
Turn on the macro recorder and record your actions.
Enter the code directly into a VBA module.
The following sections describe these methods.
In this section, I describe the basic steps that you take to record a VBA macro. In most cases, you can record your actions as a macro and then simply replay the macro; you needn't look at the code that's automatically generated. If simply recording and playing back macros is as far as you go with VBA, you don't need to be concerned with the language itself (although a basic understanding of how things work doesn't do any harm).
The Excel macro recorder translates your actions into VBA code. To start the macro recorder, choose Developer Code Record Macro (or, click the Record Macro icon on the left side of the status bar). Excel displays the Record Macro dialog box, shown in Figure 39.7.
The Record Macro dialog box presents several options:
Macro Name: The name of the macro. Excel proposes generic names, such as Macro1, Macro2, and so on.
Shortcut Key: You can specify a key combination that executes the macro. The key combination always uses the Ctrl key. You can also press Shift when you enter a letter. For example, pressing Shift while you enter the letter H makes the shortcut key combination Ctrl+Shift+H.
|
Store Macro In: The location for the macro. Your choices are the current workbook, your Personal Macro Workbook (See "Storing macros in your Personal Macro Workbook," later in this chapter), or a new workbook.
Description: A description of the macro (optional).
To begin recording your actions, click OK; your actions within Excel are converted to VBA code. When you finish recording the macro, choose Developer Code Stop Recording. Or, you can click the Stop Recording button on the status bar. This button replaces the Start Recording button while your macro is being recorded.
NOTE
Recording your actions always results in a new Sub procedure. You can't create a Function procedure by using the macro recorder. Function procedures must be created manually.
This example demonstrates how to record a very simple macro that inserts your name in the active cell.
To create the macro, start with a new workbook and follow these steps:
Activate an empty cell.
NOTE
Select the cell to be formatted before you start recording your macro. This step is important. If you select a cell while the macro recorder is turned on, the actual cell that you select will be recorded into the macro. In such a case, the macro would always format that particular cell, and it would not be a general-purpose macro.
Choose Developer Code Record Macro. Excel displays the Record Macro dialog box. (Refer to Figure 39.7.)
Enter a new single-word name for the macro, to replace the default Macro1 name. A good name is MyName.
Assign this macro to the shortcut key Ctrl+Shift+N by entering an uppercase N in the Shortcut Key field.
Click OK to close the Record Macro dialog box and begin recording your actions.
Type your name into the selected cell and then press Enter.
Choose Developer Code Stop Recording (or click the Stop Recording button on the status bar).
The macro was recorded in a new module named Module1. To view the code in this module, you must activate the VB Editor. You can activate the VB Editor in either of two ways:
Press Alt+F11.
Choose Developer Code Visual Basic.
In the VB Editor, the Project window displays a list of all open workbooks and add-ins. This list is displayed as a tree diagram, which you can expand or collapse. The code that you recorded previously is stored in Module1 in the current workbook. When you double-click Module1, the code in the module appears in the Code window.
Figure 39.8 shows the recorded macro, as displayed in the Code window.
The macro should look something like this (with your name substituted for mine, of course):
Sub MyName() ' ' MyName Macro ' ' Keyboard Shortcut: Ctrl+Shift+N ' ActiveCell.FormulaR1C1 = "John Walkenbach" End Sub
The macro recorded is a Sub procedure that is named MyName. The statements tell Excel what to do when the macro is executed.
Notice that Excel inserted some comments at the top of the procedure. These comments are some of the information that appeared in the Record Macro dialog box. These comment lines (which begin with an apostrophe) aren't really necessary, and deleting them has no effect on how the macro runs. If you ignore the comments, you'll see that this procedure has only one VBA statement:
ActiveCell.FormulaR1C1 = "John Walkenbach"
This single statement causes the name you typed while recording the macro to be inserted into the active cell. The FormulaR1C1 part is a property of the Range object — but I'm getting ahead of myself.
Before you recorded this macro, you set an option that assigned the macro to the Ctrl+Shift+N shortcut key combination. To test the macro, return to Excel by using either of the following methods:
Press Alt+F11.
Click the View Microsoft Excel button on the VB Editor toolbar.
When Excel is active, activate a worksheet. (It can be in the workbook that contains the VBA module or in any other workbook.) Select a cell and press Ctrl+Shift+N. The macro immediately enters your name into the cell.
After you record a macro, you can make changes to it (although you must know what you're doing). For example, assume that you want your name to be bold. You could re-record the macro, but this modification is simple, so editing the code is more efficient. Press Alt+F11 to activate the VB Editor window. Then activate Module1 and insert the following statement before the End Sub statement:
ActiveCell.Font.Bold = True
The edited macro appears as follows:
Sub MyName() ' ' MyName Macro ' ' Keyboard Shortcut: Ctrl+Shift+N ' ActiveCell.FormulaR1C1 = "John Walkenbach" ActiveCell.Font.Bold = True End Sub
Test this new macro, and you see that it performs as it should.
This example demonstrates how to record a time-stamp macro that inserts the current date and time into the active cell.
To create the macro, follow these steps:
Activate an empty cell.
Choose Developer Code Record Macro. Excel displays the Record Macro dialog box.
Enter a new single-word name for the macro, to replace the default Macro1 name. A good name is TimeStamp.
Assign this macro to the shortcut key Ctrl+Shift+T by entering an uppercase T in the Shortcut Key field.
Click OK to close the Record Macro dialog box.
Enter this formula into the selected cell:
=NOW()
With the date cell selected, click the Copy button (or press Ctrl+C) to copy the cell to the Clipboard.
Choose Home Clipboard Paste Values (V). This step replaces the formula with static text so that the data and time do not update when the worksheet is calculated.
Press Esc(ape) to cancel Copy mode.
Choose Developer Code Stop Recording (or click the Stop Recording button on the status bar).
Activate an empty cell and press Ctrl+Shift+T to execute the macro. There's a pretty good chance that the macro won't work!
The VBA code that is recorded in this macro depends upon a setting on the Advanced tab of the Excel Options dialog box: namely, after Pressing Enter, Move Selection. If this setting is enabled, the recorded macro won't work as intended because the active cell was changed when you pressed Enter. Even if you reactivated the date cell while recording (in Step 7), the macro still fails.
Activate the VB Editor and take a look at the recorded code. Figure 39.9 shows the recorded macro, as displayed in the Code window.
The procedure has five statements. The first inserts the NOW() formula into the active cell. The second statement selects cell C4 — an action I performed because the cell pointer moved to the next cell after I entered the formula.
The third statement copies the cell. The fourth statement, which is displayed on two lines (the underscore character means that the statement continues on the next line), pastes the Clipboard contents (as a value) to the current selection. The fourth statement cancels the moving border around the selected range.
The problem is that the macro is hard-coded to select cell C4. If you execute the macro when a different cell is active, the code always selects cell C4. This is not what you intended, and it causes the macro to fail.
NOTE
You'll also notice that the macro recorded some actions that you didn't make. For example, it specified several options for the PasteSpecial operation. Recording actions that you don't specifically make is just a by-product of the method that Excel uses to translate actions into code.
You can fix the macro in several ways. If you understand VBA, you can edit the code so it works properly. Or, you can re-record the macro using relative references.
Delete the existing TimeStamp procedure, and re-record it. Before you start recording, click the Use Relative References command in the Code group of the Developer tab. This control is a toggle, and it's turned off by default.
Figure 39.10 shows the new macro, recorded with relative references in effect.
When Excel is active, activate a worksheet. (It can be in the workbook that contains the VBA module or in any other workbook.) Select a cell and press Ctrl+Shift+T. The macro immediately enters the current date and time into the cell. You may need to widen the column to see the date and time. To widen the column automatically, just add this statement to the end of the macro (before the End Sub statement):
ActiveCell.EntireColumn.AutoFit
If you followed along with the preceding examples, you should have a better feel for how to record macros — and also a good feel for problems that might occur with even simple macros. If you find the VBA code confusing, don't worry. You don't really have to be concerned with it as long as the macro that you record works correctly. If the macro doesn't work, rerecording the macro rather than editing the code often is easier.
A good way to learn about what gets recorded is to set up your screen so that you can see the code that is being generated in the VB Editor windows. To do so, make sure that the Excel window isn't maximized; then arrange the Excel window and the VB Editor window so both are visible. While you're recording your actions, make sure that the VB Editor window is displaying the module in which the code is being recorded. (You may have to double-click the module name in the Project window.)
|
If you're going to work with recorded macros, you need to understand the concept of relative versus absolute recording modes. In a previous example in this chapter, I showed how even a simple macro could fail because of an incorrect recording mode.
Normally, when you record a macro, Excel stores exact references to the cells that you select. (That is, it performs absolute recording.) If you select the range B1:B10 while you're recording a macro, for example, Excel records this selection as
Range("B1:B10").Select
This VBA statement means exactly what it says: "Select the cells in the range B1:B10." When you invoke the macro that contains this statement, the same cells are always selected, regardless of where the active cell is located.
Look in the Developer Code group of the Ribbon for Use Relative References. When you click this control, Excel changes its recording mode from absolute (the default) to relative. When recording in relative mode, selecting a range of cells is translated differently, depending on where the active cell is located. For example, if you're recording in relative mode and cell A1 is active, selecting the range B1:B10 generates the following statement:
ActiveCell.Offset(0, 1).Range("A1:A10").Select
This statement can be translated as "From the active cell, move 0 rows down and 1 column right, and then treat this new cell as if it were cell A1. Now select what would be A1:A10." In other words, a macro that is recorded in relative mode starts out by using the active cell as its base and then stores relative references to this cell. As a result, you get different results, depending on the location of the active cell. When you replay this macro, the cells that are selected depend on the active cell. This macro selects a range that is 10 rows by 1 column, offset from the active cell by 0 rows and 1 column.
When Excel is recording in relative mode, the Use Relative Reference control appears depressed. To return to absolute recording, click the Use Relative Reference control again (and it displays its normal, undepressed state).
Most user-created macros are designed for use in a specific workbook, but you may want to use some macros in all your work. You can store these general-purpose macros in the Personal Macro Workbook so that they're always available to you. The Personal Macro Workbook is loaded whenever you start Excel. This file, named personal.xlsb, doesn't exist until you record a macro, using Personal Macro Workbook as the destination.
NOTE
The Personal Macro Workbook normally is in a hidden window (to keep it out of the way).
To record the macro in your Personal Macro Workbook, select the Personal Macro Workbook option in the Record Macro dialog box before you start recording. This option is in the Store Macro In drop-down box.
If you store macros in the Personal Macro Workbook, you don't have to remember to open the Personal Macro Workbook when you load a workbook that uses macros. When you want to exit, Excel asks whether you want to save changes to the Personal Macro Workbook.
When you begin recording a macro, the Record Macro dialog box gives you an opportunity to provide a shortcut key for the macro. Here's what to do if you'd like to change the shortcut key or provide a shortcut key for a macro that doesn't have one:
Choose Developer Code Macros (or press Alt+F8) to display the Macro dialog box.
In the Macro dialog box, select the macro name from the list.
Click the Options button, and Excel displays its Macro Options dialog box. See Figure 39.11.
Specify the shortcut key. Use a single letter (for a Ctrl+letter shortcut), or press Shift and enter an uppercase letter (for a Ctrl+Shift+letter shortcut).
Click OK to return to the Macro dialog box.
Click Cancel to close the Macro dialog box.
After you record a macro and test it, you may want to assign the macro to a button placed in a worksheet. You can follow these steps to do so:
If the macro is a general-purpose macro that you plan to use in more than one workbook, make sure that the macro is stored in your Personal Macro Workbook.
Choose Developer Controls Insert and then click the Button control from the Form Controls section (see Figure 39.12). Move your mouse pointer over the icons, and you see a ToolTip that describes the control.
In the Assign Macro dialog box, select the macro from the list.
Click OK to close the Assign Macro dialog box.
(Optional) Change the text that appears on the button to make it descriptive; right-click the button, choose Edit Text from the shortcut menu, and make your changes.
After performing these steps, clicking the button executes the assigned macro.
|
As demonstrated in the preceding sections, the easiest way to create a simple macro is to record your actions. To develop more complex macros, however, you have to enter the VBA code manually — in other words, write a program. To save time, you can often combine recording with manual code entry.
Before you can begin writing VBA code, you must have a good understanding of such topics as objects, properties, and methods. And it doesn't hurt to be familiar with common programming constructs, such as looping and If-Then statements.
This section is an introduction to VBA programming, which is essential if you want to write (rather than record) VBA macros. It isn't intended to be a complete instructional guide. My book Excel 2010 Power Programming with VBA (Wiley) covers all aspects of VBA and advanced spreadsheet application development.
Before you can enter code, you must insert a VBA module into the workbook. If the workbook already has a VBA module, you can use the existing module sheet for your new code.
Use the following steps to insert a new VBA module:
Press Alt+F11 to activate the VB Editor window. The Project window displays a list of all open workbooks and add-ins.
In the Project window, locate and select the workbook you're working in.
Choose Insert Module. VBA inserts a new (empty) module into the workbook and displays it in the Code window.
A VBA module, which is displayed in a separate window, works like a text editor. You can move through the sheet, select text, insert, copy, cut, paste, and so on.
VBA is by far the most complex feature in Excel, and you can easily get overwhelmed. To set the stage for the details of VBA, here is a concise summary of how VBA works:
You perform actions in VBA by writing (or recording) code in a VBA module sheet and then executing the macro in any one of various ways. VBA modules are stored in an Excel workbook, and a workbook can hold any number of VBA modules. To view or edit a VBA module, you must activate the VB Editor window. (Press Alt+F11 to toggle between Excel and the VB Editor window.)
A VBA module consists of procedures. A procedure is basically computer code that performs some action. The following is an example of a simple Sub procedure called ShowSum, which adds 1 + 1 and displays the result:
Sub ShowSum() Sum = 1 + 1 MsgBox "The answer is " & Sum End Sub
A VBA module also can store function procedures. A function procedure performs calculations and returns a single value. A function can be called from another VBA procedure or can even be used in a worksheet formula. Here's an example of a function named AddTwo. (It adds two values, which are supplied as arguments.)
Function AddTwo(arg1, arg2) AddTwo = arg1 + arg2 End Function
VBA manipulates objects. Excel provides more than 100 classes of objects that you can manipulate. Examples of objects include a workbook, a worksheet, a range on a worksheet, a chart, and a rectangle shape.
Objects are arranged in a hierarchy and can act as containers for other objects. For example, Excel itself is an object called Application, and it contains other objects, such as Workbook objects. The Workbook object can contain other objects, such as Worksheet objects and Chart objects. A Worksheet object can contain objects such as Range objects, PivotTable objects, and so on. The arrangement of all these objects is referred to as an object model.
Objects that are alike form a collection. For example, the Worksheets collection consists of all worksheets in a particular workbook. The ChartObjects collection consists of all ChartObjects on a worksheet. Collections are objects in themselves.
You refer to an object in your VBA code by specifying its position in the object hierarchy, using a period as a separator.
For example, you can refer to a workbook named Book1.xlsx as
Application.Workbooks("Book1.xlsx")
This expression refers to the Book1.xlsx workbook in the Workbooks collection. The Workbooks collection is contained in the Application object (that is, Excel). Extending this to another level, you can refer to Sheet1 in Book1 as follows:
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1")
You can take it to still another level and refer to a specific cell as follows:
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1")
If you omit specific references, Excel uses the active objects. If Book1.xlsx is the active workbook, the preceding reference can be simplified as follows:
Worksheets("Sheet1").Range("A1")
If you know that Sheet1 is the active sheet, you can simplify the reference even more:
Range("A1")
Objects have properties. A property can be thought of as a setting for an object. For example, a Range object has properties, such as Value and Address. A Chart object has properties such as HasTitle and Type. You can use VBA both to determine object properties and to change them.
You refer to properties by combining the object with the property, separated by a period. For example, you can refer to the value in cell A1 on Sheet1 as follows:
Worksheets("Sheet1").Range("A1").Value
You can assign values to variables. To assign the value in cell A1 on Sheet1 to a variable called Interest, use the following VBA statement:
Interest = Worksheets("Sheet1").Range("A1").Value
Objects have methods. A method is an action that is performed with the object. For example, one of the methods for a Range object is ClearContents. This method clears the contents of the range.
You specify methods by combining the object with the method, separated by a period. For example, to clear the contents of range A1:C12, use the following statement:
Worksheets("Sheet1").Range("A1:C12").ClearContents
VBA also includes all the constructs of modern programming languages, including variables, arrays, looping, and so on.
The preceding describes VBA in a nutshell. Now you just have to learn the details, some of which are covered in the rest of this chapter.
VBA is an object-oriented language, which means that it manipulates objects, such as Ranges, Charts, Shapes, and so on. These objects are arranged in a hierarchy. The Application object (which is Excel) contains other objects. For example, the Application object contains a number of objects, including the following:
AddIns (a collection of AddIn objects)
Windows (a collection of Window objects)
Workbooks (a collection of Workbook objects)
Most of these objects can contain other objects. For example, a Workbook object can contain the following objects:
Charts (a collection of Chart sheet objects)
Names (a collection of Name objects)
Styles (a collection of Style objects)
Windows (a collection of Window objects in the workbook)
Worksheets (a collection of Worksheet objects)
Each of these objects, in turn, can contain other objects. A Worksheet object, for example, can contain the following objects:
ChartObjects (a collection of all ChartObject objects)
PageSetup (an object that stores printing information)
PivotTables (a collection of all PivotTable objects)
A collection consists of all like objects. For example, the collection of all Workbook objects is known as the Workbooks collection. You can refer to an individual object in a collection by using an index number or a name. For example, if a workbook has three worksheets (named Sheet1, Sheet2, and Sheet3), you can refer to the first object in the Worksheets collection in either of these ways:
Worksheets(1) Worksheets("Sheet1")
The objects that you work with have properties, which you can think of as attributes of the objects. For example, a Range object has properties, such as Column, Row, Width, and Value. A Chart object has properties, such as Legend, ChartTitle, and so on. ChartTitle is also an object, with properties such as Font, Orientation, and Text. Excel has many objects, and each has its own set of properties. You can write VBA code to do the following:
Examine an object's current property setting and take some action based on it.
Change an object's property setting.
You refer to a property in your VBA code by placing a period (a dot) and the property name after the object's name. For example, the following VBA statement sets the Value property of a range named frequency to 15. (That is, the statement causes the number 15 to appear in the range's cells.)
Range("frequency").Value = 15
Some properties are read-only, which means that you can examine the property, but you can't change the property. For a single-cell Range object, the Row and Column properties are read-only properties: You can determine where a cell is located (in which row and column), but you can't change the cell's location by changing these properties.
A Range object also has a Formula property, which is not read-only; that is, you can insert a formula into a cell by changing its Formula property. The following statement inserts a formula into cell A12 by changing the cell's Formula property:
Range("A12").Formula = "=SUM(A1:A10)"
NOTE
Contrary to what you may think, Excel doesn't have a Cell object. When you want to manipulate a single cell, you use the Range object (with only one cell in it).
At the top of the object hierarchy is the Application object, which is actually Excel, the program. The Application object has several useful properties:
Application.ActiveWorkbook: Returns the active workbook (a Workbook object) in Excel.
Application.ActiveSheet: Returns the active sheet (a Sheet object) of the active workbook.
Application.ActiveCell: Returns the active cell (a Range object) object of the active window.
Application.Selection: Returns the object that is currently selected in the active window of the Application object. This can be a Range, a Chart, a Shape, or some other selectable object.
You also should understand that properties can return objects. In fact, that's exactly what the preceding examples do. The result of Application.ActiveCell, for example, is a Range object. Therefore, you can access properties by using a statement such as the following:
Application.ActiveCell.Font.Size = 15
In this case, the ActiveCell property returns a Range object. The Font property returns a Font object, which is contained in the Range object. Size is a property of the Font object. The preceding statement sets the Size property to 15 — that is, it causes the font in the currently selected cell to have a size of 15 points (pt).
|
ActiveCell.Row
In many cases, you can refer to the same object in a number of different ways. Assume that you have a workbook named Sales.xlsx and it's the only workbook open. Furthermore, assume that this workbook has one worksheet, named Summary. Your VBA code can refer to the Summary sheet in any of the following ways:
Workbooks("Sales.xlsx").Worksheets("Summary") Workbooks(1).Worksheets(1) Workbooks(1).Sheets(1) Application.ActiveWorkbook.ActiveSheet ActiveWorkbook.ActiveSheet ActiveSheet
The method that you use is determined by how much you know about the workspace. For example, if more than one workbook is open, the second or third method is not reliable. If you want to work with the active sheet (whatever it may be), any of the last three methods would work. To be absolutely sure that you're referring to a specific sheet on a specific workbook, the first method is your best choice.
Objects also have methods. You can think of a method as an action taken with an object. For example, Range objects have a Clear method. The following VBA statement clears a Range, an action that is equivalent to selecting the Range and then choosing Home Editing Clear Clear All:
Range("A1:C12").Clear
In VBA code, methods look like properties because they are connected to the object with a "dot." However, methods and properties are different concepts.
Like all programming languages, VBA enables you to work with variables. In VBA (unlike in some languages), you don't need to declare variables explicitly before you use them in your code (although doing so is definitely a good practice).
NOTE
If your VBA module contains an Option Explicit statement at the top of the module, then you must declare all variables in the module. Undeclared variables will result in a compile error, and your procedures will not run.
In the following example, the value in cell A1 on Sheet1 is assigned to a variable named Rate:
Rate = Worksheets("Sheet1").Range("A1").Value
You then can work with the variable Rate in other parts of your VBA code. Note that the variable Rate is not a named range, which means that you can't use it as such in a worksheet formula.
VBA uses many constructs that are found in most other programming languages. These constructs are used to control the flow of execution. This section introduces a few of the more common programming constructs.
One of the most important control structures in VBA is the If-Then construct, which gives your applications decision-making capability. The basic syntax of the If-Then structure is as follows:
If condition Then statements [Else elsestatements]
In plain English, if a condition is true, then a group of statement will be executed. If you include the Else clause, then another group of statements will be executed if the condition is not true.
The following is an example (which doesn't use the optional Else clause). This procedure checks the active cell. If it contains a negative value, the cell's color is changed to red. Otherwise, nothing happens.
Sub CheckCell() If ActiveCell.Value < 0 Then ActiveCell.Font.ColorIndex = 3 End Sub
You can use a For-Next loop to execute one or more statements a number of times. Here's an example of a For-Next loop:
Sub SumSquared() Total = 0 For Num = 1 To 10 Total = Total + (Num ^ 2) Next Num MsgBox Total End Sub
This example has one statement between the For statement and the Next statement. This single statement is executed 10 times. The variable Num takes on successive values of 1, 2, 3, and so on, up to 10. The variable Total stores the sum of Num squared, added to the previous value of Total. The result is a value that represents the sum of the first 10 integers squared. This result is displayed in a message box.
Another construct that you encounter if you record macros is the With-End With construct. This is a shortcut way of dealing with several properties or methods of the same object. The following is an example:
Sub AlignCells() With Selection .HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter .WrapText = False .Orientation = xlHorizontal End With End Sub
The following macro performs exactly the same operations but doesn't use the With-End With construct:
Sub AlignCells() Selection.HorizontalAlignment = xlCenter Selection.VerticalAlignment = xlCenter Selection.WrapText = False Selection.Orientation = xlHorizontal End Sub
The Select Case construct is useful for choosing among two or more options. The following example demonstrates the use of a Select Case construct. In this example, the active cell is checked. If its value is less than 0, it's colored red. If it's equal to 0, it's colored blue. If the value is greater than 0, it's colored black.
Sub CheckCell() Select Case ActiveCell.Value Case Is < 0 ActiveCell.Font.Color = vbRed Case 0 ActiveCell.Font.Color = vbBlue Case Is > 0 ActiveCell.Font.Color = vbBlack End Select End Sub
Any number of statements can go below each Case statement, and they all get executed if the case is true.
The following is a VBA macro that can't be recorded because it uses programming concepts that must be entered manually. This macro creates a list of all formulas on the active sheet. The list is stored on a new worksheet.
Sub ListFormulas() ' Create a range object Set InputRange = ActiveSheet.UsedRange ' Add a new sheet Set OutputSheet = Worksheets.Add ' Variable for the output row OutputRow = 1 ' Loop through the range
For Each cell In InputRange If cell.HasFormula Then OutputSheet.Cells(OutputRow, 1) = "'" & cell.Address OutputSheet.Cells(OutputRow, 2) = "'" & cell.Formula OutputRow = OutputRow + 1 End If Next cell End Sub
NOTE
A workbook that contains this example is available on the companion CD-ROM. The file is named list formulas.xlsm.
Although this macro may look complicated, it's fairly simple when you break it down. Here's how it works:
The macro creates an object variable named InputRange. This variable corresponds to the used range on the active sheet (avoiding the need to check every cell).
It then adds a new worksheet and assigns the worksheet to an object variable named OutputSheet. The OutputRow variable is set to 1. This variable is incremented later on.
Figure 39.13 shows the result of running this macro — a handy list of all formulas in the worksheet.
As macros go, this example is okay, but it's certainly not perfect. It's not very flexible, and it doesn't include any error handling. For example, if the workbook structure is protected, trying to add a new sheet will cause an error.
This chapter barely scratches the surface of what you can do with VBA. If this is your first exposure to VBA, you're probably a bit overwhelmed by objects, properties, and methods. I don't blame you. If you try to access a property that an object doesn't have, you get a run-time error, and your VBA code grinds to a screeching halt until you correct the problem. Fortunately, several good ways are available to learn about objects, properties, and methods.
Read the rest of the book. Subsequent chapters in this section contain additional information and many more examples.
Record your actions. The best way to become familiar with VBA is to turn on the macro recorder and record actions that you make in Excel. You can then examine the code to gain some insights regarding the objects, properties, and methods.
Use the Help system. The main source of detailed information about Excel's objects, methods, and procedures is the VBA Help system. Help is very thorough and easy to access. When you're in a VBA module, just move the cursor to a property or method and press F1. You get help that describes the word that is under the cursor.
Get another book. Several books are devoted exclusively to using VBA with Excel. My book, Excel 2010 Power Programming with VBA (Wiley), is one.