Вы находитесь на странице: 1из 8

Page Title

Beyond Excel

BASICS
PIVOTCHART DRILLDOWN

2012 Craig Hatmaker

Page Title

2012 Craig Hatmaker

Beyond Excel

PivotChart Drilldown

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.

2012 Craig Hatmaker

PivotChart Drilldown

Beyond Excel

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
Excels 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 isnt 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 PivotTables
drilldown capability to any PivotChart.
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:

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

2012 Craig Hatmaker

Page 4

PivotChart Drilldown

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 Windows left dropdown we should


select Chart. Using the Code Windows
right dropdown we should select the
particular chart event to attach our code.
In the Code Windows 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 routines
first and last lines.

NOTE!
Code is attached to Chart
Sheets code module

Figure 2 - Events for Charts

2012 Craig Hatmaker

Page 5

PivotChart Drilldown

Beyond Excel

Coding the Double Click Event


At right is the routine to determine
what was clicked and invoke the
associated
PivotTables
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 charts
BeforeDoubleClick event.
The first and last lines of this routine
were generated by the VBE when I
selected Chart from the code windows
left dropdown, and BeforeDoubleClick
from the code windows right drop down
(see Figure 2).
Documentation Block:
Below the first line is a
documentation block that explains this
routines 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
PivotCharts associated PivotTables
ShowDetail method which displays
the records that support the clicked
seriers.
2012 Craig Hatmaker

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
Arg1
Arg2
Cancel

'
'

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:

Double clicked chart element type


When ElementID=3, this is the chart series
And this is the chart point
Set to True to stop double click default

'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

Page 6

PivotChart Drilldown

Beyond Excel

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 charts MouseUp
event.
The first and last lines of this routine
were generated by the VBE when I
selected Chart from the code windows
left dropdown, and MouseUp from the
code windows right drop down (see
Figure 2).
Documentation Block:
Below the first line is a
documentation block that explains this
routines purpose, inputs, how-to-use,
and modification history.

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
Shift
x
y

'

Example:

'
'
'

Date
Init Modification
10/04/10 CWH Initial Programming w/some help from
http://www.computorcompanion.com/LPMArticle.asp?ID=221

'

Declarations
Dim ElementID
Dim Arg1
Dim Arg2

Mouse
State
Mouse
Mouse

botton that was released


of SHIFT, CTRL, and ALT keys
pointer X coordinate within Chart
pointer Y coordinate within Chart

*none - This is an event handler

As Long
As Long
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:

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

'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

Error Handling:
Every routine should have error
handling.

End Sub

Procedure:
This routine:
Calls GetChartElement passing to it
the mouse pointers x and y
coordinates.
GetChartElement
returns what was clicked.
Checks if a series was clicked. If it

2012 Craig Hatmaker

was, GetChartElement passed 3 in


the ElementID parameter.
If the above are true, then the yellow
highlighted
line
invokes
the
PivotCharts associated PivotTables
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.

Page 7

PivotChart Drilldown

Beyond Excel

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:
Well 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.

'

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

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:
Chart Event Discussion:
Drilldown Video Part 1:
Drilldown Video Part 2:

2012 Craig Hatmaker

msdn.microsoft.com/en-us/library/aa195740(v=office.11).aspx
www.computorcompanion.com/LPMArticle.asp?ID=221
www.youtube.com/watch?v=-Uu2WqDxLdk
http://youtu.be/J5kPny4LaqE

Page 8