Chapter 16

Learning VBA for Data Analysis

Record a Macro

A macro is a sequence of instructions that perform one or more actions or return a result. You can save time and make the process of creating a macro easier by recording some or all of the actions you want your macro to perform. To build a macro that manipulates Excel in some way, you use the macro recorder. After you activate the recorder, you use Excel to perform the action or actions that you want in the macro, which Excel then translates into the equivalent VBA statements and stores as a macro for later use. You can store your recorded macros in any workbook, but Excel provides a special workbook for this purpose: the Personal Macro Workbook.

Record a Macro

9781118517147-fg1601.eps

001 Click the View tab.

002 Click the Macros down arrow.

003 Click Record Macro.

A You can also click the Macro Recording icon in the status bar.

9781118517147-fg1602.eps

The Record Macro dialog box appears.

004 Type a name for the macro.

005 Click the Store Macro In down arrow and then select the workbook you want to use to store the macro from the drop-down list.

Note: For most macros, it is best to store the code in the Personal Macro Workbook.

006 (Optional) Type a description of the macro.

007 Click OK.

Excel starts the macro recorder.

9781118517147-fg1603.eps

B The Recording icon appears in the status bar.

008 Perform the Excel actions you want to record.

9781118517147-fg1604.eps

009 Click the Recording icon.

Excel stops the macro recorder and saves the macro in the workbook that you selected in step 5.

Open the VBA Editor

If you want to add a macro to a workbook, or to create a macro from scratch, you can do this in the VBA Editor, a program that enables you to view, create, edit, and run VBA macros. After you finish recording your actions, Excel translates them into VBA statements and saves the macro in a module, a special window in which you can view, edit, and run macros; you access the module using the VBA Editor. If you make mistakes during the recording, or if you want to augment the recorded macro with other VBA statements, then you need to do this in the module. Similarly, you also require access to the module if you want to paste code from other sources or create new macros from scratch.

Open the VBA Editor

9781118517147-fg1605.eps

001 Click the Developer tab.

Note: See the section, Record a Macro, to learn how to display the Developer tab.

002 Click Visual Basic.

You can also press Alt+F11.

9781118517147-fg1606.eps

The Microsoft Visual Basic for Applications window appears.

003 Double-click the workbook that contains the recorded macro.

A PERSONAL.xlsb is the Personal Macro Workbook.

If you do not see the Project pane, you can click View and then click Project Explorer, or press Ctrl+R.

9781118517147-fg1607.eps

B Excel displays the workbook’s modules.

004 Double-click the module you want to open.

9781118517147-fg1608.eps

The module window opens.

C The VBA Editor opens the module in a new window.

D If you recorded a macro and are working with the workbook that you used to store that macro, the recorded code appears in the module window.

Explore the Excel Object Model

To program Excel with VBA, you need to understand the Excel object model. In the programming lexicon, an object model is a complete summary of the objects associated with a particular program or feature, the hierarchy used by those objects, and the properties and methods supported by each object. Here an object is a distinct, manipulable item such as a worksheet or range. A property is a programmable characteristic of an object, such as a worksheet’s name, or whether a range is formatted with bold text. A method is an action you can perform on an object, such as creating a new worksheet or clearing the formatting from a range. This section shows you a few properties and methods for the three main Excel objects: the workbook, worksheet, and range.

Workbook Object

You can use VBA to create new workbooks, open, save, and close workbooks, and more. You can reference a specific workbook either by using the ActiveWorkbook object, which represents the workbook that currently has the focus, or by using the Workbooks collection, which represents all the workbooks currently open in Excel. Here are some examples:

Workbooks(1)

Workbooks(“Budget.xlsx”)

Workbook Properties

Property

Description

Workbooks.Count

Returns the number of open workbooks.

Name

Returns the filename of the workbook.

Path

Returns the location of the workbook.

FileFormat

Returns the Excel file format of the workbook.

FullName

Returns the location and filename of the workbook.

PivotTables

Returns the collection of PivotTables in the workbook.

Saved

Returns False if the workbook has unsaved changes.

VBASigned

Returns True if the workbook has been digitally signed.

Workbook Methods

Method

Description

Activate

Switches to a workbook.

Workbooks.Add

Creates a new workbook.

Workbooks.Open

Opens an existing workbook.

Protect

Protects a workbook.

Save

Saves a workbook.

SaveAs

Saves a workbook to a different file.

PrintOut

Prints a workbook.

Close

Closes a workbook.

Unprotect

Unprotects a workbook.

Worksheet Object

You can use VBA to create new worksheets, copy, move, and delete worksheets, and more. You can reference a specific worksheet either by using the ActiveSheet object, which represents the worksheet that currently has the focus, or by using the Worksheets collection, which represents all the worksheets currently open in Excel. Here are some examples:

Worksheets(1)

Worksheets(“Sheet1”)

Worksheet Properties

Property

Description

Worksheets.Count

Returns the number of worksheets in the workbook.

Name

Returns the name of the worksheet.

StandardHeight

Returns or sets the standard row height.

StandardWidth

Returns or sets the standard column width.

Visible

Hides or displays a worksheet.

Worksheet Methods

Method

Description

Worksheets.Add

Creates a new worksheet.

Activate

Switches to a worksheet.

Calculate

Calculates a workbook.

Copy

Copies a worksheet.

Move

Moves a worksheet.

Delete

Deletes a worksheet.

Range Object

You can use VBA to select a range, add data to a range, format a range, and more. You can reference a specific cell by using the ActiveCell object, which represents the worksheet cell that currently has the focus. You can also use the WorkSheet object’s Range method to specify a range using a reference or a defined name. Here are some examples:

Worksheets(1).Range(“A1:B10”)

ActiveSheet.Range(“Expenses”)

Range Properties

Property

Description

Address

Returns the address of the range.

Count

Returns the number of cells in the range.

NumberFormat

Returns the numeric format of the range.

Value

Returns or sets the data or formula for the range.

Range Methods

Method

Description

Cut

Cuts a range to the Clipboard.

Copy

Copies a range to the Clipboard.

Clear

Clears all data and formatting from a range.

Select

Select a range.

Add a Macro to a Module

If you have a macro that you want to create or copy, you need to add the VBA code for the macro to a module in the VBA Editor. As you become familiar with manipulating Excel using VBA, you will likely come up with many ways to simplify complex tasks and automate routine and repetitive chores using macros. To implement these macros, you need to type your code into a module in the VBA Editor.

Similarly, you may run across a macro that you want to use for your own work, either as it is or by modifying the code to suit your needs. You can either transcribe this macro into a module on your system, or better yet, copy the macro and then paste it into a module.

Add a Macro to a Module

9781118517147-fg1609.eps

001 Start the VBA Editor.

002 Double-click the module into which you want to add the macro.

If you prefer to add your code to a new module, you can click Insert and then click Module, instead.

9781118517147-fg1610.eps

Excel opens the module window.

003 Position the cursor where you want to start the new macro.

Note: You must add the new macro either before or after an existing macro.

9781118517147-fg1611.eps

004 Type Sub, a space, the name of the new macro, and then press Enter.

Note: Make sure the name you use is not the same as any existing macro name in the module.

9781118517147-fg1612.eps

A The VBA Editor adds the line End Sub to denote the end of the macro.

If you copied the macro code from another source, click Edit and then click Paste, instead.

005 Type the macro statements between the Sub and End Sub lines.

B As you type a VBA function, object, property, or method, the VBA Editor displays the syntax in a pop-up box.

Run a Macro

You can run a macro from any open workbook. You have the option of running the macro from the VBA Editor or from Excel. Excel maintains a list of the macros that are stored in each open workbook. When you want to run a macro, you can either open the module that contains the macro or display the list of available Excel macros. Either way, to run a macro, you must first open the workbook in which the macro is stored.

It is best to use the VBA Editor if you are testing the macro, because although VBA switches to Excel to execute the code, it returns to the VBA Editor when it is done. Therefore, you can run the code, see whether it works properly, and then adjust the code as necessary.

Run a Macro

Run a Macro from the VBA Editor

9781118517147-fg1613.eps

001 Open the module that contains the macro.

002 Click any statement within the macro you want to run.

A The macro name appears in the list of macros.

003 Click Run.

004 Click Run Sub/UserForm.

You can also click the toolbar’s Run icon (9781118517147-ma022.tif) or press F5.

The VBA Editor runs the macro.

Run a Macro from Excel

9781118517147-fg1614.eps

001 Open the workbook that contains the macro.

You can skip step 1 if the macro is stored in the Personal Macro Workbook.

002 Click the View tab.

003 Click Macros.

If you have the Developer tab displayed, you can also click the Developer tab and then click Macros.

You can also press Alt+F8.

9781118517147-fg1615.eps

The Macro dialog box appears.

004 Click the Macros In down arrow and then select the workbook that contains the macro you want to run from the drop-down list.

If you are not sure which workbook contains the macro, select All Open Workbooks, instead.

B Excel displays a list of macros in the workbook.

005 Click the macro you want to run.

006 Click Run.

Excel runs the macro.

Include a Function Macro in a Formula

9781118517147-fg1616.eps

001 Type = and whatever formula operators and operands you need before the function.

002 Click Insert Function.

The Insert Function dialog box appears.

003 Select the User Defined category.

004 Click the function.

005 Click OK.

006 Specify the function’s argument, if any, and click OK (not shown).

Excel inserts the function macro into the formula.

Assign a Shortcut Key to a Macro

If you have a macro that you use often, you can quickly access the code by assigning a shortcut key to the macro. Macros are meant to be timesavers, so it is not unusual to have a macro that you run several times each day, or even several times in a row. In such situations, those mouse clicks can add up and you may wonder whether the macro is really saving you time. To work around this problem, you can assign a shortcut key to the macro. As long as the macro’s workbook is open, you can press the shortcut key within Excel to run the macro.

Assign a Shortcut Key to a Macro

9781118517147-fg1617.eps

001 Open the workbook that contains the macro.

You can skip step 1 if the macro is stored in the Personal Macro Workbook.

002 Click the View tab.

003 Click Macros.

If you have the Developer tab displayed, you can also click the Developer tab and then click Macros.

You can also press Alt+F8.

9781118517147-fg1618.eps

The Macro dialog box appears.

004 Click the Macros In down arrow and then select the workbook that contains the macro you want to work with from the drop-down list.

If you are not sure which workbook contains the macro, select All Open Workbooks, instead.

A Excel displays a list of macros in the workbook.

005 Click the macro.

006 Click Options.

9781118517147-fg1619.eps

The Macro Options dialog box appears.

007 Type the character you want to use as part of the shortcut key.

008 Click OK.

Excel assigns the shortcut key to the macro.

9781118517147-fg1620.eps

009 Click Cancel.

You can now run the macro by pressing the shortcut key.

Assign a Macro to the Quick Access Toolbar

If you have a VBA macro that you use frequently, you can create one-click access to the code by assigning that macro to a button on the Excel Quick Access Toolbar. The Quick Access Toolbar is the row of buttons that appears, by default, on the left side of the title bar.

As long as you leave open the workbook in which the macro is stored, you have one-click access to the macro. Because you must have the macro’s workbook open, it is a good idea to only create toolbar buttons for macros in your Personal Macro Workbook, which is always open.

Assign a Macro to the Quick Access Toolbar

9781118517147-fg1621.eps

001 Click the Customize Quick Access Toolbar button.

002 Click More Commands.

9781118517147-fg1622.eps

The Excel Options dialog box appears.

A Excel automatically displays the Quick Access Toolbar tab.

003 Click the Choose Commands From down arrow.

004 Click Macros.

9781118517147-fg1623.eps

005 Click the macro you want to add.

006 Click Add.

B Excel adds the command.

007 Click OK.

9781118517147-fg1624.eps

C Excel adds a button for the macro to the Quick Access Toolbar.

Assign a Macro to the Ribbon

You can improve your Excel productivity by customizing the Ribbon with buttons that run the macros you use frequently. It is often useful to organize your macros in some way. For example, you might have a set of macros related to formatting, another set related to file management, and so on. To organize these and other related macros, you can add them to the Excel Ribbon. To add a new command to the Ribbon, you must first create a new tab or a new group within an existing tab, and then add the command to the new tab or group.

Assign a Macro to the Ribbon

Display the Customize Ribbon Tab

9781118517147-fg1625.eps

001 Right-click any part of the Ribbon.

002 Click Customize the Ribbon.

Add a New Tab or Group

9781118517147-fg1626.eps

The Excel Options dialog box appears.

A Excel automatically displays the Customize Ribbon tab.

001 Click the tab you want to customize.

B You can also click New Tab to create a custom tab.

002 Click New Group.

C Excel adds the group.

003 Click Rename.

004 In the Rename dialog box, type a name for the group.

005 Click OK.

Assign a Macro

9781118517147-fg1627.eps

001 Click the Choose Commands From down arrow and then click Macros.

002 Click the macro you want to add to the Ribbon.

003 Click Add.

D Excel adds the macro to the tab.

004 Click OK.

9781118517147-fg1628.eps

E Excel adds the new group and command to the Ribbon.

Set the Macro Security Level

VBA is a powerful language that is all too often used for nefarious ends. Fortunately, you can adjust the macro security setting to one of four options to protect your system. The Disable All Macros without Notification option enables you to disable all macros, without a way to enable them. The Disable All Macros with Notification option notifies you that a document contains macros and disables the macros, but gives you the option of enabling them. The Disable All Macros Except Digitally Signed Macros option enables macros only if they come from a source that has digitally signed the VBA project. The Enable All Macros option runs all macros without prompting.

Set the Macro Security Level

9781118517147-fg1629.eps

001 Click File.

9781118517147-fg1630.eps

002 Click Options.

9781118517147-fg1631.eps

The Excel Options dialog box appears.

003 Click Trust Center.

004 Click Trust Center Settings.

9781118517147-fg1632.eps

The Trust Center dialog box appears.

005 Click Macro Settings.

006 Click to select the security level you want to use (9781118517147-ma001.tif changes to 9781118517147-ma002.tif).

007 Click OK.

008 Click OK.

Excel puts the new macro security level into effect.

Digitally Sign Your Excel Macros

If you set macro security to Disable All Macros Without Notification, Excel does not allow you to run your own macros that reside outside the Personal Macro Workbook. Does this mean you must store all your macros in the Personal Macro Workbook? That would make it difficult to distribute your macros to other people. Fortunately, it is possible to “prove” that you are the author of your own macros. You can do that by self-certifying, which creates a trust certificate that applies only to your own work and to using that work on your own computer.

Digitally Sign Your Excel Macros

9781118517147-fg1633.eps

Note: Before proceeding, create your personal digital certificate by running the SelfCert.exe program, as described in the Apply It section.

001 Press Alt+F11.

Excel opens the Visual Basic for Applications Editor.

002 Click the project to which you want to assign the certificate.

003 Click Tools.

004 Click Digital Signature.

9781118517147-fg1634.eps

The Digital Signature dialog box appears.

005 Click Choose.

9781118517147-fg1635.eps

The Windows Security dialog box appears.

A Windows displays your digital certificate.

Note: Remember that you only see this digital certificate after you have run the SelfCert.exe program, as described in the Apply It section of this task.

006 Click OK.

9781118517147-fg1636.eps

B The certificate appears in the Digital Signature dialog box.

007 Click OK.

Excel applies the digital certificate to the project.