12. Enhancing Pivot Table Reports with Macros

Why Use Macros with Pivot Table Reports

Imagine that you could be in multiple locations at one time, with multiple clients at one time, helping them with their pivot table reports. Suppose you could help multiple clients refresh their data, extract top 20 records, group by months, or sort by revenue—all at the same time. The fact is you can do just that by using Excel macros.

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. Macros can be created by recording and saving a series of keystrokes. Once saved, a macro can be played back on demand. In other words, you can record your actions in a macro, save the macro, and then allow your clients to play back your actions with the click of a button or press of a keyboard shortcut. It would be as though you were right there with them! This functionality is especially useful when you’re distributing pivot table reports.

For example, suppose that you want to give your clients the option of grouping their pivot table report by month, by quarter, or by year. Although the process of grouping can be performed by anyone, some of your clients might not have a clue how to do it. In this case, you could record a macro to group by month, a macro to group by quarter, and a macro to group by year. Then you could create three buttons, one for each macro. In the end, your clients, having little experience with pivot tables, need only to click a button to group their pivot table report.

A major benefit of using macros with your pivot table reports is the power you can give your clients to easily perform pivot table actions that they would not normally be able to perform on their own, empowering them to more effectively analyze the data you provide.

Recording a Macro

Look at the pivot table in Figure 12.1. You know that you can refresh this pivot table by right-clicking inside the pivot table and selecting Refresh Data. Now, if you were to record your actions with a macro while you refreshed this pivot table, you or anyone else could replicate your actions and refresh this pivot table by running the macro.

Image

Figure 12.1 You can easily refresh this basic pivot table by right-clicking and selecting Refresh, but if you recorded your actions with a macro, you could also refresh this pivot table simply by running the macro.

The first step in recording a macro is to initiate the Record Macro dialog. Select the Developer tab on the ribbon and then select Record Macro.


Tip

Can’t find the Developer tab on the ribbon? Click the File tab on the ribbon and then choose Options. The Excel Options dialog opens; click Customize Ribbon. In the list box to the far right, place a check next to Developer. Placing a check next to this option enables the Developer tab.


When the Record Macro dialog activates, you can fill in a few key pieces of information about the macro:

Image Macro Name—Enter a name for your macro. You should generally enter a name that describes the action being performed.

Image Shortcut Key—You can enter any letter into this input box. That letter becomes part of a set of keys on your keyboard that can be pressed to play back the macro. This is optional.

Image Store Macro In—Specify where you want the macro to be stored. If you are distributing your pivot table report, you should select This Workbook so that the macro is available to your clients.

Image Description—In this input box, you can enter a few words that give more detail about the macro.

Because this macro refreshes your pivot table when it is played, name your macro RefreshData, as shown in Figure 12.2. Also assign the shortcut key R. Notice that, based on this, the dialog gives you the key combination Ctrl+Shift+R. Keep in mind that you use the key combination to play your macro after it is created. Be sure to store the macro in This Workbook. Click OK to continue.

Image

Figure 12.2 Fill in the Record Macro dialog as shown here and then click OK to continue.

When you click OK in the Record Macro dialog, you initiate the recording process. At this point, any action you perform is recorded by Excel. In this case, you want to record the process of refreshing your pivot table.

Right-click anywhere inside the pivot table and select Refresh Data. After you have refreshed your pivot table, you can stop the recording process by going up to the Developer tab and selecting the Stop Recording button.

Congratulations! You have just recorded a macro. You can now play your macro by pressing Ctrl, Shift, and R on your keyboard at the same time.


Note

In Excel 2013, Microsoft enhanced the security model to remember files that you’ve deemed trustworthy. That is to say, when you open an Excel workbook and click the Enable button, Excel remembers that you trusted that file. Each time you open the workbook after that, Excel automatically trusts it.

For information on macro security in Excel 2016, pick up Que Publishing’s Excel 2016 in Depth by Bill Jelen.


Creating a User Interface with Form Controls

Allowing your clients to run your macro with shortcut keys such as Ctrl+Shift+R can be a satisfactory solution if you have only one macro in your pivot table report. However, suppose you want to allow your clients to perform several macro actions. In this case, you should give your clients a clear and easy way to run each macro without having to remember a gaggle of shortcut keys.

A basic user interface provides the perfect solution. A user interface is a set of controls such as buttons, scrollbars, and other devices that allow users to run macros with a simple click of the mouse. In fact, Excel offers a set of controls designed specifically for creating user interfaces directly on a spreadsheet. These controls are called form controls. The general idea behind form controls is that you can place one on a spreadsheet and then assign a macro to it—meaning a macro you have already recorded. After a macro is assigned to the control, that macro is executed, or played, when the control is clicked.

You can find form controls in the Controls group on the Developer tab. To get to the form controls, simply select the Insert icon in the Controls group, as shown in Figure 12.3.

Image

Figure 12.3 To see the available form controls, click Insert in the Controls group on the Developer tab.


Note

Notice that there are form controls and ActiveX controls. Although they look similar, they are quite different. Form controls, with their limited overhead and easy configuration settings, are designed specifically for use on a spreadsheet. Meanwhile, ActiveX controls are typically used on Excel user forms. As a general rule, you should use form controls when working on a spreadsheet.


Here, you can select the control that best suits your needs. In this example, you want your clients to be able to refresh their pivot table with the click of a button. Click the Button control to select it and then drop the control onto your spreadsheet by clicking the location you would like to place the button.

After you drop the button control onto your spreadsheet, the Assign Macro dialog, shown in Figure 12.4, opens and asks you to assign a macro to this button. Select the macro you want to assign to the button, in this case RefreshData, and then click OK.

Image

Figure 12.4 Select the macro you want to assign to the button, and then click OK. In this case, you want to select RefreshData.


Note

Keep in mind that all the controls in the Forms toolbar work in the same way as the command button, in that you assign a macro to run when the control is selected.


As you can see in Figure 12.5, you can assign each macro in your workbook to a different form control and then name the controls to distinguish between them.

Image

Figure 12.5 You can create a different button for each one of your macros.

As you can see in Figure 12.6, when you have all the controls you need for your pivot table report, you can format the controls and surrounding spreadsheet to create a basic interface.

Image

Figure 12.6 You can easily create the feeling of an interface by adding a handful of macros, a few form controls, and a little formatting.

Altering a Recorded Macro to Add Functionality

When you record a macro, Excel creates a module that stores the recorded steps of your actions. These recorded steps are actually lines of VBA code that make up your macro. You can add some interesting functionality to pivot table reports by tweaking a macro’s VBA code to achieve various effects.

To get a better understanding of how this process works, start by creating a new macro that extracts the top five records by customer. Go to the Developer tab and select Record Macro. Set up the Record Macro dialog as shown in Figure 12.7. Name your new macro TopNthCusts, and specify This Workbook as the place where you want to store the macro. Click OK to start recording.

Image

Figure 12.7 Name your new macro and specify where you want to store it.

After you have started recording, right-click the Customer field and select Filter. Then select Top 10. Selecting this option opens the Filter dialog, where you specify that you want to see the top five customers by sales amount. Enter the settings shown in Figure 12.8 and then click OK.

Image

Figure 12.8 Enter the settings you see here to get the top five customers by revenue.

After you record the steps to extract the top five customers by revenue, select Stop Recording from the Developer tab.

You now have a macro that, when played, filters your pivot table to the top five customers by revenue. The plan is to tweak this macro to respond to a scrollbar. That is, you force the macro to base the number used to filter the pivot table on the number represented by a scrollbar in your user interface. In other words, a user can get the top 5, top 8, or top 32 simply by moving a scrollbar up or down.

Inserting a Scrollbar Form Control

To get a scrollbar onto your spreadsheet, select the Insert icon on the Developer tab; then select the scrollbar control from the form controls. Place the scrollbar control onto your spreadsheet. You can change the dimensions of the scrollbar to an appropriate length and width by clicking and dragging the corners.

Right-click the scrollbar and select Format Control. This activates the Format Object dialog, in which you make the following setting changes: Set Minimum Level to 1 so the scrollbar cannot go below 1, set Maximum Level to 200 so the scrollbar cannot go above 200, and set Cell Link to $M$2 so that the number represented by the scrollbar will output to cell M2. After you have completed these steps, your dialog should look like the one shown in Figure 12.9.

Image

Figure 12.9 After you have placed a scrollbar on your spreadsheet, configure the scrollbar as shown here.

Next, you need to assign the TopNthCusts macro you just recorded to your scrollbar. To do this, right-click the scrollbar and select Assign Macro. Select the TopNthCusts macro from the list shown in Figure 12.10 and then click OK. Assigning this macro ensures that it plays each time the scrollbar is clicked.

Image

Figure 12.10 Select the macro from the list.

At this point, test your scrollbar by clicking it. When you click your scrollbar, two things should happen: The TopNthCusts macro should play, and the number in cell M2 should change to reflect your scrollbar’s position. The number in cell M2 is important because that is the number you are going to reference in your TopNthCusts macro.

The only thing left to do is tweak your macro to respond to the number in cell M2, effectively tying it to your scrollbar. To do this, you have to get to the VBA code that makes up the macro. You have several ways to get there, but for the purposes of this example, go to the Developer tab and select Macros. Selecting this option opens the Macro dialog, exposing several options. From here, you can run, delete, step into, or edit a selected macro. To get to the VBA code that makes up your macro, select the macro and then click Edit, as demonstrated in Figure 12.11.

Image

Figure 12.11 To get to the VBA code that makes up the TopNthCusts macro, select the macro and then select Edit.

The Visual Basic Editor opens, with a detailed view of all the VBA code that makes up this macro (see Figure 12.12). Notice that the number 5 is hard-coded as part of your macro. The reason is that you originally recorded your macro to filter the top five customers by revenue. Your goal here is to replace the hard-coded number 5 with the value in cell M2, which is tied to your scrollbar. Therefore, you need to delete the number 5 and replace it with the following:

ActiveSheet.Range("M2").Value

Image

Figure 12.12 Your goal is to replace the hard-coded number 5, as specified when you originally recorded your macro, with the value in cell M2.

Your macro’s code should now look like the code shown in Figure 12.13.

Image

Figure 12.13 Simply delete the hard-coded number 5 and replace it with a reference to cell M2.

Close the Visual Basic Editor to get back to your pivot table report. Test your scrollbar by setting it to 11. Your macro should play and filter out the top 11 customers by revenue, as shown in Figure 12.14.

Image

Figure 12.14 After a little formatting, you have a clear and easy way for your clients to get the top customers by revenue.


Tip

When you select a new item from the combo box you created here, the pivot tables automatically adjust the columns to fit the data. This behavior can be annoying when you have a formatted template. You can suppress this behavior by right-clicking each pivot table and selecting PivotTable Options. Selecting this option activates the PivotTable Options dialog, where you can remove the check next to the AutoFit Column Widths on Update selection.


Next Steps

In the next chapter, you’ll go beyond recording macros. Chapter 13, “Using VBA to Create Pivot Tables,” shows how to utilize Visual Basic for Applications to create powerful, behind-the-scenes processes and calculations using pivot tables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset