VBA Pivot Drill down

8
Page Title © 2012 Craig Hatmaker Beyond Excel BASICS PIVOTCHART DRILLDOWN

description

A help guide for drill downs in pivot table with VBA

Transcript of VBA Pivot Drill down

Page Title

© 2012 Craig Hatmaker

Beyond Excel

BASICS

PIVOTCHART DRILLDOWN

Page Title

© 2012 Craig Hatmaker

Beyond Excel

PivotChart Drilldown

© 2012 Craig Hatmaker

Beyond Excel

Table of Contents Why Read This? .......................................................................................................................................................................................... 4

Overview .................................................................................................................................................................................................... 4

Coding Chart Events ................................................................................................................................................................................... 5

Coding the Double Click Event ................................................................................................................................................................... 6

Coding the MouseUp Event ....................................................................................................................................................................... 7

Housekeeping ............................................................................................................................................................................................ 8

References and Links ................................................................................................................................................................................. 8

New to VBA?

Click Intro to VBA for instructions on how to get started coding with Visual Basic for Applications.

PivotChart Drilldown

© 2012 Craig Hatmaker Page 4

Beyond Excel

Note! This is for charts on their own chart sheet. This is not for charts embedded in normal worksheets. For help with that see References:

Why Read This?

Learn how to add “drilldown” functionality to PivotCharts In a Chart sheet.

Charts are a fantastic way to display data. They can quickly and readily reveal implications hidden in mounds of data. For example, suppose we have a database of customer orders. With Excel’s charts, we can readily show which products are our top sellers; which customers are our best customers; how

many orders we process each day; how those process volumes are trending, and more. Such graphs are easy in Excel.

Good graphs reveal the truth. But what if the truth isn’t what we expected? How can we be sure the graph truly is correct, and perhaps begin to understand the reason for our surprise?

Drilldown reveals the numbers behind the charts. Unfortunately, Excel provides no “out of the box” method to

click a chart element and expose the supporting information. PivotTables have drilldown. PivotCharts do not. But with VBA, we can extend the PivotTable’s drilldown capability to any PivotChart.

Overview

Thanks to YouTube we can see how this works. Click the picture at right or this link for a short video:

www.youtube.com/watch?v=-Uu2WqDxLdk

Figure 1 PivotChart Drilldown Demo

PivotChart Drilldown

© 2012 Craig Hatmaker Page 5

Beyond Excel

Coding Chart Events

We want to add code so that when we click on a chart it reveals its supporting data. This requires VBA code. We must add the code directly to the chart object. To do this we start the VBE, make sure the Project Explorer is visible (Ctrl-R), then double click the Chart sheet to display its Code Window. Using the

Code Window’s left dropdown we should select Chart. Using the Code Window’s right dropdown we should select the particular chart event to attach our code.

In the Code Window’s right dropdown we can see all the events that the chart sheet will respond to. Intuitively we would select the

BeforeDoubleClick event so when we double click on the chart, it does what we tell it to do.

Select that event and the VBE will create a “stub” for us with the routine’s first and last lines.

Figure 2 - Events for Charts

NOTE! Code is attached to Chart Sheet’s code module

PivotChart Drilldown

© 2012 Craig Hatmaker Page 6

Beyond Excel

Private Sub Chart_BeforeDoubleClick(ByVal ElementID As Long, _ ByVal Arg1 As Long, ByVal Arg2 As Long, Cancel As Boolean) ' Description:Mimic double click on PivotTable for drilldown ' Use only with PivotCharts ' Inputs: ElementID Double clicked chart element type ' Arg1 When ElementID=3, this is the chart series ' Arg2 And this is the chart point ' Cancel Set to True to stop double click default ' Notes: This event is best documented here: ' http://msdn.microsoft.com/en-us/library/ff197223.aspx ' Example: (None - this is an event handler) ' Date Init Modification ' 02/02/11 CWH Initial Programming ' Declarations ' Error Handling and Function Return Code Initialization On Error GoTo ErrHandler ' Only handle clicks on chart series (ElementID=3) If ElementID = 3 Then ' Sometimes Excel interprets a double click on a point as applying ' to the entire series, in which case Arg2=-1. If Arg2 = -1 Then ' If there's just one point, use it. Otherwise ask what to do. If Me.SeriesCollection(Arg1).Points.Count > 1 Then If MsgBox("Excel selected the entire series." & vbCr & _ "To see entire series, click OK." & vbCr & _ "To see a single point, click Cancel and try again.", _ vbOKCancel, "Selection problem") = vbCancel Then _ Err.Raise 998, , "Cancel Pressed" End If Arg2 = Me.SeriesCollection(Arg1).Points.Count + 1 End If ' Show detail Me.PivotLayout.PivotTable.DataBodyRange. _ Cells(Arg2, Arg1).ShowDetail = True ErrHandler: 'Error Handling and Routine termination Select Case Err.Number Case Is = 0: 'No error - do nothing ' Case is = #: 'Add anticipated error handling here Case Else: 'Unanticipated errors MsgBox "Error#" & Err.Number & vbCrLf & Err.Description, _ vbCritical + vbMsgBoxHelpButton, _ Me.Name & "!Chart_BeforeDoubleClick", _ Err.HelpFile, Err.HelpContext End Select End Sub

Coding the Double Click Event

At right is the routine to determine what was clicked and invoke the associated PivotTable’s drilldown function. First Line:

This is a private subroutine because it is an event handler. All event handlers are private subroutines by default. This particular event handler is for the chart’s BeforeDoubleClick event.

The first and last lines of this routine were generated by the VBE when I selected Chart from the code window’s left dropdown, and BeforeDoubleClick from the code window’s right drop down (see Figure 2). Documentation Block:

Below the first line is a documentation block that explains this routine’s purpose, inputs, how-to-use, and modification history.

Declaration Block:

Before writing executable code I declare all variables. This routine has none.

Error Handling:

Every routine should have error handling. Procedure: This routine:

Checks if a series was clicked. If it was, windows passed 3 in the ElementID parameter.

Checks if the entire series was clicked. Sometimes windows interprets a double click on a series point as a double click on the entire series.

If the above are true, then the yellow highlighted line invokes the PivotChart’s associated PivotTable’s ShowDetail method which displays the records that support the clicked seriers.

PivotChart Drilldown

© 2012 Craig Hatmaker Page 7

Beyond Excel

Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, _ ByVal X As Long, ByVal Y As Long) ' Description:Drill Down into Pivot Chart's data ' Parameters: Button Mouse botton that was released ' Shift State of SHIFT, CTRL, and ALT keys ' x Mouse pointer X coordinate within Chart ' y Mouse pointer Y coordinate within Chart ' Example: *none - This is an event handler ' Date Init Modification ' 10/04/10 CWH Initial Programming w/some help from ' http://www.computorcompanion.com/LPMArticle.asp?ID=221 ' Declarations Dim ElementID As Long Dim Arg1 As Long Dim Arg2 As Long ' Error Handling and Routine Initialization On Error GoTo ErrHandler ' Pass: x, y. Receive: ElementID, Arg1, Arg2 Me.GetChartElement X, Y, ElementID, Arg1, Arg2 ' If Series clicked, show detail If ElementID = 3 And Arg2 > 0 Then _ Me.PivotLayout.PivotTable.DataBodyRange. _ Cells(Arg2, Arg1).ShowDetail = True ErrHandler: 'Error Handling and Routine termination Select Case Err.Number Case Is = 0: 'No error - do nothing ' Case is = #: 'Add anticipated error handling here Case Else: 'Unanticipated errors MsgBox "Error#" & Err.Number & vbCrLf & Err.Description, _ vbCritical + vbMsgBoxHelpButton, _ Me.Name & "!Chart_MouseUp", _ Err.HelpFile, Err.HelpContext End Select End Sub

Coding the MouseUp Event

Windows Sometimes interprets a double click on a series point as a double click on the entire series. We can avoid this problem by not double clicking on the chart and using the MouseUp event instead. The MouseUp event fires when the left mouse button Is released. So a single click will trigger it. First Line:

This is a private subroutine because it is an event handler. This particular event handler is for the chart’s MouseUp event.

The first and last lines of this routine were generated by the VBE when I selected Chart from the code window’s left dropdown, and MouseUp from the code window’s right drop down (see Figure 2). Documentation Block:

Below the first line is a documentation block that explains this routine’s purpose, inputs, how-to-use, and modification history.

Declaration Block:

Before writing executable code I declare all variables. This routine has none.

Error Handling:

Every routine should have error handling. Procedure: This routine:

Calls GetChartElement passing to it the mouse pointer’s x and y coordinates. GetChartElement returns what was clicked.

Checks if a series was clicked. If it

was, GetChartElement passed 3 in the ElementID parameter.

If the above are true, then the yellow highlighted line invokes the PivotChart’s associated PivotTable’s ShowDetail method which displays

the records that support the clicked seriers.

As you can see, this is only slightly more complicated than the BeforeDoubleClick event but handles clicking on charts better.

PivotChart Drilldown

© 2012 Craig Hatmaker Page 8

Beyond Excel

' Declarations Dim oWks As Worksheet Dim bExists As Boolean ' Error Handling and Routine Initialization On Error GoTo ErrHandler ' If Series clicked, show detail If ElementID = 3 And Arg2 > 0 Then Chart.PivotLayout.PivotTable.DataBodyRange. _ Cells(Arg2, Arg1).ShowDetail = True bExists = False ' Move results to worksheet "Drilldown" For Each oWks In ThisWorkbook.Worksheets If oWks.Name = "Drilldown" Then bExists = True Exit For End If Next If Not bExists Then ActiveSheet.Name = "Drilldown" Else With Worksheets("Drilldown") Set oWks = ActiveSheet .Cells.Delete Shift:=xlUp oWks.Cells.Copy .Cells(1, 1).PasteSpecial .Activate Application.DisplayAlerts = False oWks.Delete Application.DisplayAlerts = True End With End If End If

Housekeeping

Both of these methods create a new worksheet for each drilldown request. That can really clutter our workbooks. To maintain good housekeeping we can use a designated worksheet for drilldown requests using the code at right.

The highlighted sections should be added to the chart BeforeDoubleClick or MouseUp event (depending on which you use).

Declarations:

We’ll need a worksheet variable and a flag to tell us if the “Drilldown” worksheet exists.

Procedure:

The added lines:

Cycle through all worksheets to see if any of them are named “Drilldown” (I normally use a routine from my library called WorksheetExists to do this. You may want to create your own).

If worksheet “Drilldown” does not exists then rename the newly created worksheet “Drilldown”.

If it does exists: Clear it; Copy the newly created worksheet to it; Activate it; and delete the newly created worksheet.

References and Links

Chart Sheet Downloads: Double Click Code https://dl.dropbox.com/u/13737137/Projects/Drilldown/DrillDown_DoubleClick.xls Mouse Up Code https://dl.dropbox.com/u/13737137/Projects/Drilldown/DrillDown_MouseUp.xls Embedded Charts Downloads: Individual Charts https://dl.dropbox.com/u/13737137/Projects/Drilldown/Embedded_PivotChart_Drilldown.xls Class Method: https://dl.dropbox.com/u/13737137/Projects/Drilldown/Embedded_PivotChart_Drilldown_Class.xls References: Select Event Parameters: msdn.microsoft.com/en-us/library/aa195740(v=office.11).aspx Chart Event Discussion: www.computorcompanion.com/LPMArticle.asp?ID=221 Drilldown Video Part 1: www.youtube.com/watch?v=-Uu2WqDxLdk Drilldown Video Part 2: http://youtu.be/J5kPny4LaqE