Chart Events
When you use a computer, you continuously interact with objects and programs, through events. An event is anything that happens, such as moving the mouse, clicking on objects, changing data, or activating windows. Programs can raise events of their own as well. A program can respond to events using event procedures. For example, if you click a scroll button, Excel responds by scrolling the window down.
As a programmer, you can write event procedures that will respond to (or trap) events by users. These event procedures can trap events in the worksheet, in the workbook, at the application level, or in a chart. In this article, I introduce you to chart event procedures in Microsoft Excel, which you can use for charts on a chart sheet and embedded charts.
Why Use Chart Events?
Chart events can make it much easier for people to use your programs, and add interactivity to your charts. Perhaps you need users to select a point in a series. If you create an event procedure that detects a click on the chart, users won’t have to type in a series name and a point number.
After the click the program can perform one or more useful tasks:
Display a customized chart tip;
Extract information from the chart and place it in a worksheet;
Activate another chart or worksheet;
Identify points to be included in a subsequent analysis.
Although Excel can accept data in a variety of formats and arrangements, you can do certain things with the data to ensure your charts are easy to build and maintain. “Good data” has these characteristics:
Data for each series is arranged in Columns (preferable to Rows)
First column is used for Categories (X axis labels)
First row is used for Series Names
Top left cell is blank
Data below series names is numeric (right-adjusted with no alignment specified)
There are no blank rows or blank columns within the data range
There is a buffer row or column between the table and any other non-blank cells.
In this case, I use sample data similar to the above above to demonstrate chart event procedures.
Chart Sheet Events
The first set of examples is for charts that reside on their own sheets, not embedded in worksheets. These examples are contained in the downloadable workbook ChartSheetEvents.xlsm.
Create A Chart Sheet
Select the entire range you want included in your chart, or select a single cell within this range. If you followed guidelines 6 and 7 about Good Data, Excel selects the range of continuous data that includes the selected cell.
Select the data range, or a single cell within the data range. Press the F11 function key, to quickly create a chart sheet from the data range range, using the default chart type.
The Chart Code Module
Right-click the chart sheet tab, and select View Code from the pop-up menu. This opens the Visual Basic Editor (VBE).
Within the VBE, a code module appears with the caption ChartSheetEvents.xlsm – Chart1 (code):
This is a special kind of code module, which is associated with the chart. Code contained in this module runs when events occur on the chart.
The code module should contain only the line
This line means any variable used in the module must be explicitly declared prior to use. This approach is slightly more work, but it assures that no errant variable will be accidentally defined by a typographical error.
If the module does not include the Option Explicit line, type it in, then go to the VBE’s Tools menu, select Options…, and on the Editor tab, check the Require Variable Declarations box. Every module you create after setting this option will automatically contain the Option Explicit line.
While you’re in the dialog, you may as well uncheck Auto Syntax Check, which pops up a dialog whenever you enter code with a syntax error. Since the code with an error is also colored red, there’s no need for an annoying dialog which you have to cancel to continue.
Chart Event Procedure
At the top of the code module, you see two dropdowns. One contains the items (General) and Chart, the other contains (Declarations). While you can type your entire event procedure from scratch, it’s easier to use these dropdowns when creating procedures.
Select Chart from the left hand dropdown. The following stub of an event procedure appears in the code module:
This procedure runs whenever the chart is activated. Between these lines, type whatever code you want to be executed when the chart is activated. For example:
Now when you activate the chart, the following message box appears:
This example is demonstrated using the chart named Welcome in the companion workbook. This is just an example. Remove the message box code before it makes you insane.
More Chart Events
Chart_Activate is good for illustration of chart events, but other events can be much more useful. The chart events available to you are listed below. These can be accessed from the right hand dropdown in the chart code module when Chart is selected in the left hand dropdown.
Activate
BeforeDoubleClick
BeforeRightClick
Calculate
Deactivate
DragOver
DragPlot
MouseDown
MouseMove
MouseUp
Resize
Select
SeriesChange
Next you can use an event to tell which chart element has been selected. Choose Chart from the left hand dropdown of the code module, then choose Select from the right hand dropdown, to produce the following procedure stub:
Note that I’ve inserted the line continuation character (an underscore) in the first line to wrap the line at a convenient place.
The Chart_Select event fires whenever a chart element has been selected. Three arguments are passed to the procedure: ElementID, which identifies the selected chart element, and Arg1 and Arg2, which provide additional information. For example, if ElementID identifies that a series has been selected, Arg1 identifies which series has been selected, and Arg2 identifies the point within the series which has been selected, or Arg1 = -1 to indicate that the entire series is selected. If Arg1 or Arg2 are not relevant to the selected ElementID, they are assigned the value zero.
When you select Chart from the left hand dropdown, the Chart_Activate procedure shell is created in the code module (Activate is the default event for a chart). You can ignore it, delete it, or use it for another purpose.
This table lists the ElementID values, and the meanings of their associated Arg1 and Arg2 parameters.
No need to memorize the details, since the VBE Object Browser (VBE View menu > Object Browser) knows everything.
Now you can add a line to the procedure to identify which chart element has been selected, and show the values of its associated arguments:
To test your event procedure, select the chart’s title. Click OK in the message box, and then test your event procedure with other elements, such as a series, and a point in a series.
The following three message boxes appear when selecting the Chart Title (ElementID = 4), Series 1 (ElementID = 3, Arg1 = 1, and Arg2 = -1), and Series 1 Point 4 (ElementID = 3, Arg1 = 1, Arg2 = 4). To select an individual point, you must single click twice: once to select the entire series, then again to select the point.
This example is demonstrated using the chart named Select in the companion workbook.
These message boxes aren’t very informative – text descriptions would be more useful. Replace the Chart_Select event code with the following more extensive procedure. It converts the values to text, and creates a more informative message:
Test your new code, by selecting elements in the chart. Here are the revised message boxes, made more informative by analyzing the ElementID and other arguments:
This example is demonstrated using the chart named Nicely Select in the companion workbook.
This is a more useful procedure, because it tells us in human words what has been selected. On the other hand, it is less useful than it could be, because it pops up a message box every time a new chart element is selected, forcing the user to clear the message box before proceeding.
Identify the Point Clicked By the User
Another useful event procedure tells you which point was clicked on, and display its values. Chart_Select is not the best event to trap to detect clicking on a point, because two Chart_Select events must occur when a point is selected: the series is selected by the first click, and the point by the second. The MouseUp event is a better event to trap.
To create a new event procedure, choose Chart in the left dropdown and MouseUp in the right, to create this shell:
Four arguments are passed to this procedure.
Button tells which mouse button was released: xlNoButton, xlPrimaryButton (usually the left button), xlSecondaryButton (right button), or xlMiddleButton.
Shift tells which keys are depressed when the mouse button was released. The value of Shift can be one or a sum of several of the following values:
For example, if Shift = 2, the CTRL key was depressed when the mouse button was clicked; if Shift = 5, both the SHIFT and ALT keys were depressed.
The coordinates of the cursor, x and y, are in chart object client coordinate units. It’s not necessary to be concerned about these, since you just pass them along to other functions to get more useful information.
Test the following event procedure, which uses Chart_MouseUp to determine where the mouse click occurred. The procedure:
traps the release of the button,
determines where on the chart the click occurred (x, y),
passes these coordinates to the GetChartElement function to determine what chart element is located at these coordinates,
determines whether a data point (or data label) is located at the mouse click,
extracts the X and Y values for the data point, if the click occurred at a data point or data label,
displays this information in a message box.
Here is an informative dialog that results from clicking on the 4th point of the first series. Compare to the third dialog from the last example above.
This example is demonstrated using the chart named Identify Point in the companion workbook.
You could do many things with the data from this procedure.
A message box requires a user response to continue; you could replace the dialog by drawing a textbox with the same information, as a smarter chart tip. Use the MouseMove event instead, to mimic Excel’s normal chart tip behavior.
You could place this data into a worksheet range. After clicking on several points, you would have a small table of values from the selected points. These could be used for subsequent analysis.
You could identify the clicked point, then jump to another appropriate chart. This approach has the effect of drilling down deeper into the data. See the short example below.
Drill Down to a Related Chart
Suppose the values for the categories A through E in the chart reflected sums of other values. You could have several other chart sheets, Chart A through Chart E, that show detail for the selected categories. An event procedure such as the following produces this kind of drill down effect (to test the procedure, create chart sheets named Chart A, Chart B, etc.):
To return to the starting chart on another mouse click, you can add the following Chart_MouseUp event procedure to the code modules of the detail charts. For example, add the following procedure to the code module for the Chart A sheet. When you select an element in Chart A, you’ll return to the main chart:
This example is demonstrated using the charts named DrillDown and Chart A through Chart E in the companion workbook.
The VBE Project Explorer
You may have noticed the Project Explorer window of the Visual Basic Editor. By default it is docked in the upper left of the VB window. If the Project Explorer window is not open, from within the VBE, choose VBE View menu > Project Explorer or press Ctrl+R. Here is the Project Explorer window in its floating (undocked) state.
Every VBA Project that you have open in Excel is listed in the Project Explorer, including open workbooks and installed add-ins. If the project is unprotected, its constituent objects are listed in a tree view structure underneath it. If the folder icon in the toolbar is selected, the objects are grouped. If the folder icon is not selected, the objects are listed in alphabetical order without grouping.
You can see three of the four groups of objects in the screenshot above. All chart sheets and worksheets are listed under the Microsoft Excel Objects group, with the ThisWorkbook object that represents the workbook itself. Regular code modules are listed under the Modules group, where we see the module named MChartEvents in the workbook ChartClassEvents.xlsm. The Class Modules group contains class modules, such as CAppEvent and CChartEvent, which will be constructed later in this article. If a project has any user forms, these will be listed under the Forms group.
Under Microsoft Excel Objects, the sheets and workbook are listed in alphabetical order by their “Code Name”. The Code Name is the name of the object in the VB Editor; we see code names Chart1 through Chart5, Chart5a through Chart5e, Sheet1, and ThisWorkbook are shown above. The Excel name of an object is shown in parentheses after its Code Name. You can change the Code Name by changing the (Name) property in the VBE’s Properties window; if you change the Name property, the name displayed on the sheet tab in Excel will be changed.
To access a sheet’s code module, double click it in the Project Explorer window, or right-click a sheet tab in Excel and choose View Code. To access the workbook’s code module, double-click on the ThisWorkbook object in the Project Explorer window.
New Forms, Modules, and Class Modules are added to a project using the VBE’s Insert menu. A new chart sheet or worksheet object is added whenever a sheet is created within Excel. A new project is added to the Project Explorer’s list when a workbook is created or opened, or an add-in is installed, within Excel.
Embedded Chart Events
The approach I have described so far is effective, but only for a single chart sheet. To apply to multiple chart sheets, the event code has to be copied to each chart sheet’s code module. It does not work at all for embedded charts.
A more flexible and powerful technique is to use a class module to trap chart events. A class module can be used for any chart, whether it’s an embedded chart or chart sheet. And it eliminates the need to place the code in a chart sheet’s code module. Any events in the code module of a chart are available in a chart event class module. A chart event class module is demonstrated in the downloadable workbook ChartClassEvents.xlsm.
To create a new class module, click Alt+F11 to switch to the VB Editor. Make sure the ChartClassEvents.xlsm workbook is selected in the Project Explorer window.
Within the VBE, choose Insert menu > Class Module. A new code module opens, with the caption ChartClassEvents.xlsm – Class1 (Code). If the Properties window is not open, choose View menu > Properties, or press the F4 function key. In the Properties window, change the class name to CChartEvent, following the convention that the name of a class module begins with capital C.
The class module should begin with this line:
If not, follow the instructions in The Chart Code Module subsection in the Chart Sheet Events section of this article, above.
Next, add this line in the Declarations section of the class module, to declare a Chart type object with event trapping enabled.
After adding this line, the class module contains the EventChart item in the left hand dropdown, in addition to (General) and Class. When the EventChart item is selected, all of the chart events described in the first half of this article appear in the right hand dropdown.
To create the equivalent chart event procedure as you created in the “More Chart Events” subsection above, select EventChart from the left dropdown and Select from the right dropdown, to produce this procedure shell:
The shell of the EventChart_Activate procedure is produced when the EventChart item is selected in the left dropdown. This can be deleted or ignored. Add the Msgbox command within this procedure to identify the element and arguments for the selected chart element. The entire class module code should look like this:
The code is almost ready to trap chart events, but first you need to enable events for the chart.
Enabling Events for the Chart
Make sure the ChartClassEvents.xls workbook is selected in the Project Explorer window. From the VBE Insert menu, select Module. A new code module opens, with the caption ChartClassEvents.xls – Module1 (Code). In the Properties window, change the module name to MChartEvents, following the convention that the name of a regular module begins with capital M.
The module should begin with this line:
If not, follow the instructions in “The Chart Code Module” section. Now you must declare an instance of the chart events class, by adding this line in the Declarations section of the class module, immediately below the Option Explicit line.
Next, you create two procedures, Set_This_Chart and Reset_Chart, To activate a chart for events, you assign the active chart to the EventChart property of the instance of the class:
To deactivate the chart for events, you assign the EventChart property of the instance of the class to Nothing:
These two lines are wrapped in the Set_This_Chart and Reset_Chart procedures, with a check within the Set_This_Chart procedure to prevent errors if no chart is selected. The entire module looks like this:
To test the procedures, select any chart, embedded or chart sheet, and run Set_This_Chart. Now select any chart element, and a message box pops up to tell you the ElementID, Arg1, and Arg2.
Enabling Events for Chart(s)
This approach is fine for a single embedded chart, but it can be broadened to include all charts embedded in the active sheet. Instead of a variable clsChartEvent, you declare an array clsChartEvents() to contain all of the enabled charts, and wrap them within loops so all embedded charts on the active sheet are included.
Adjust the MChartEvents module to look like this:
Activate a sheet with embedded charts and run Set_All_Charts. All embedded charts will now respond to chart events as the single embedded chart did in the previous section. This approach works for any embedded charts on a worksheet or a chart sheet (yes, you can embed chart objects on a chart sheet).
The previous code won’t activate the parent chart sheet, however. You reinstate the clsChartEvent declaration, to be used with the chart sheet, and adjust the Set_All_Charts procedure to activate a chart sheet and then activate the embedded charts.
Modify the module to look like this:
Using Event Procedures to Enable Chart Events
Event procedures in Microsoft Excel have different levels of influence. In the earlier example, the event procedures in the code module behind a chart sheet only detect events within the chart sheet. Similarly, event procedures on a worksheet’s code module only detect events in that worksheet. Event procedures on a workbook’s code module trap events that occur in all sheets within the workbook. Finally, application-level event procedures watch over all sheets and workbooks in Excel. There is no application code module, however, so you need to create a special class module to handle application events.
Using these events is a more convenient way to activate chart events than running the Set_All_Charts and Reset_All_Charts procedures used above. The following code examples demonstrate how you can use events to set different levels of activation for chart events:
all charts in one worksheet
all charts in one chart sheet
all charts on all sheets in one workbook
all charts on all sheets in all workbooks
You can decide which level of activation you need, based on the purpose of your chart event code. If you are only concerned with a single chart in one worksheet, you can stop with the first example. If you have built an extensive add-in that processes events for any charts, you need a full-blown application events class module. The companion workbook ChartClassEvents.xlsm follows level 4.
1. Worksheet Events to Enable All Charts In One Worksheet
You must trap the Activate and Deactivate events for the desired worksheet, and use these events to run the Set_All_Charts and Reset_All_Charts procedures. Right-click the sheet tab, and choose View Code from the pop up menu to open the VBE. You see a new code module with the caption ChartClassEvents.xls – Sheet1 (Code), assuming this is Sheet1. Choose Worksheet on the left hand dropdown and Activate from the right hand dropdown. Now type the line Set_All_Charts inside the Worksheet_Activate procedure stub. Then choose Deactivate from the right hand dropdown, and type the line Reset_All_Charts inside the Worksheet_Deactivate procedure stub. You see the following in the code module:
This code turns on chart events for all charts embedded in the worksheet when it is activated, then turns off chart events when the worksheet is deactivated. If your program executes additional code in the Worksheet_Activate and _Deactivate events, include the lines above with the other code, in the order that works best for your application.
2. Chart Sheet Events to Enable All Charts In One Chart Sheet
You need to trap the Activate and Deactivate events for the desired chart sheet, and use these events to run the Set_All_Charts and Reset_All_Charts procedures. To open the VBE, right-click the sheet tab, and choose View Code from the pop up menu. It opens the code module with the caption ChartClassEvents.xls – Chart1 (Code), assuming this is Chart1. Choose Chart on the left dropdown and Activate from the right dropdown, and type the line Set_All_Charts inside the Chart_Activate procedure shell. Then choose Deactivate from the right dropdown, and type the line Reset_All_Charts inside the Chart_Deactivate procedure shell. You see the following in the code module:
This code turns on chart events for the chart sheet itself and for all charts embedded in the chart sheet when the sheet is activated, then turns off chart events when the sheet is deactivated. If your program executes additional code in the Chart_Activate and _Deactivate events, include the lines above with the other code, in the order that works best for your application.
3. Workbook Events to Enable All Charts On All Sheets In One Workbook
Remove the Worksheet_Activate, Worksheet_Deactivate, Chart_Activate, and Chart_Deactivate code that enables chart events for specific worksheets or chart sheets. These procedures are rendered redundant by the following Workbook_SheetActivate and _SheetDeactivate event procedures.
You must trap the Activate and Deactivate events for all sheets (worksheets and chart sheets) in the desired workbook, and use these events to run the Set_All_Charts and Reset_All_Charts procedures. Right-click the small Excel icon to the left of the File menu, and choose View Code from the pop up menu to open the VBE. It opens the code module with the caption ChartEvents.xls – ThisWorkbook (Code). Choose Workbook on the left dropdown, SheetActivate from the right dropdown, and type the line Set_All_Charts inside the Workbook_SheetActivate procedure stub. Then choose SheetDeactivate from the right dropdown, and type the line Reset_All_Charts inside the Workbook_SheetDeactivate procedure stub. You now see the following in the code module:
This code turns on chart events for all charts embedded in the newly activated sheet, and for the sheet itself if it’s a chart sheet, then turns off chart events when the sheet is deactivated. If your program executes additional code in the Workbook_SheetActivate and _SheetDeactivate events, include the lines above with the other code, in the order that works best for your application.
4. Application Events to Enable All Charts on All Sheets In All Workbooks
You must trap the Activate and Deactivate events for all sheets (worksheets and chart sheets) in any workbook, and the Activate and Deactivate events for all workbooks, and use these events to run the Set_All_Charts and Reset_All_Charts procedures. This process is a little more involved than using sheet or workbook events because you must create a class module to detect application events.
To create the Application Event Class Module, switch to the VB Editor to create a new class module. Make sure the ChartClassEvents.xls workbook is selected in the Project Explorer window. In the VBE, choose Insert menu > Class Module. A new code module opens with the caption ChartClassEvents.xls – Class1 (Code). If the Properties window is not open, choose View menu > Properties or press the F4 function key. In the Properties window, change the class name to CAppEvent (following the convention that the name of a class module begins with a capital C). Now declare an Application type object with event trapping enabled, by adding this line in the Declarations section of the class module.
After adding this line, the class module contains the EventApp item in the left dropdown, in addition to (General) and Class. Select EventApp from the left dropdown, and select in turn SheetActivate, SheetDeactivate, WorkbookActivate, and WorkbookDeactivate from the right dropdown. Insert the line Set_All_Charts in the Activate event procedures, and Reset_All_Charts in the Deactivate event procedures. The CAppEvent class module should now contain this code:
You must create an instance of the application class before it will respond to events. To activate the application event class, in the MChartEvents module, add a declaration line:
Insert the following procedures into the MChartEvents module. The first tells the class that it is responding to events in the current application, and enables events in the active sheet’s charts. The second tells the class that it is responding to events in Nothing (no events!), and disables events in the active sheet’s charts.
The last step in activating application-level events is to run the InitializeAppEvents procedure. You could use a command bar button or menu command for this, but those approaches both require the user to remember to go click something. Since you now are an expert on events, you can use workbook events to activate the application events.
The application events and chart events class modules likely reside within an add-in or workbook you’ve built to trap events from the entire application. Open the ThisWorkbook code module for your workbook. If your program is a regular workbook, use the dropdowns at the top of the code module to insert Workbook_Open and Workbook_BeforeClose procedures, and enter InitializeAppEvents and TerminateAppEvents where appropriate, as shown below:
If your program is an add-in, use the dropdowns at the top of the code module to insert Workbook_AddinInstall and Workbook_AddinUninstall procedures, and enter InitializeAppEvents and TerminateAppEvents where appropriate, as shown below:
When the workbook is opened or the add-in installed, the application event class is instantiated, so it can begin watching for chart events. When the workbook is closed or the add-in uninstalled, the application event class in terminated, and chart events are no longer trapped.
In a perfect world, this would be sufficient to keep the application event procedures working. In our programming environment, however, many things can break the application event hooks. If your program encounters a run time error, for example, you may find yourself without application events, and therefore, without chart events. You should insert the InitializeAppEvents line into other procedures where appropriate. For example, you could place it at the top or bottom of every procedure run from your program’s command bar and menu buttons.
The Final Event
In this article, you found out how useful chart events can be. They can extend the user interface of the programs you write, making it easy for users to identify points for your program to work on. With a little ingenuity, you can create powerful applications. For example, recently, I made a utility that draws a trend line for only part of a plotted series using the first and last points indicated by two mouse clicks. I made another utility that lets the user zoom in and out on the basis of mouse actions. Once you’ve experimented with chart events, you’ll think of many ways to enhance your projects.
Chart Event Articles on the Peltier Tech Blog
There are several examples that make use of chart events on this blog, including:
Chart Event to Highlight a Series
Chart Event Class Module to Highlight a Series
Highlight a Series with a Click or a Mouse Over
Accordion Chart for Jorge
The post Chart Events in Microsoft Excel appeared first on Peltier Tech Blog.