## Floating Bars in Excel Charts

Floating bars can be used to plot many types of data sets. (“Bars” in this usage means “bars”, as Excel calls horizontally oriented bars, as well as “columns”, as Excel calls vertically oriented bars.) In a waterfall chart, floating bars (usually vertical) show how contributing factors affect a cumulative total. In a Gantt chart, horizontal floating bars along a horizontal date scale help program managers plan task start and end dates and durations, and track progress towards completion of these tasks. Floating bars can be useful to show running highs and lows in a data set, such as daily high and low temperatures, stock prices, diastolic and systolic blood pressure readings, etc.

There are numerous ways to create floating bars in an Excel chart. There are so many ways that I should write more than one post, but I’m going to cram them all into this one. I’ve divided the techniques into the following:

• Stacked Column and Bar Charts
• Line Chart Tricks
• Error Bars
• XY Chart Line Segments

## Stacked Column and Bar Charts

Stacked column and bar charts are probably the most obvious way to create floating bar charts. This approach is pretty flexible, and allows individual floating bars to be formatted differently, but will require some calculations to get the bars to appear as desired.

### Stacked Column Charts (Vertical Bars)

This tutorial will show simple floating columns, stacked floating columns, floating columns that span the horizontal axis, and overlapping floating columns, all using stacked column charts.

#### Floating Columns

In the data set below, there are several high and low values for the categories in a column chart. The clustered column chart shows the values we want to highlight: we want a floating column to connect each low value to its corresponding high value.

We achieve this by inserting a column in the worksheet which has a simple formula to calculate the difference between high and low (“Delta” in the table below). Adjusting the data range and changing from clustered to stacked columns shows all we need. The floating column is resting on top of the Low value column.

A little formatting gives us all we need. The Low series is formatted to be invisible: no border and no fill. The vertical axis has been rescaled to zoom in on the data and remove some of the white space below the floating bars.

You can change the relative width of the columns and gaps between by selecting them and changing the Gap Width property; a Gap Width of 100 means that the gap will be 100% as wide as a bar. I like to use gap widths of 50% to 100%, and I used 75% in most of the charts here.

With this technique, each column can be selected (it may take two single clicks) and formatted independently of the rest, for purposes of highlighting one or more specific values.

The gold and purple colors above may show extreme highlighting, and were selected to clearly show the different colors. In general, subtle highlighting, like the slightly darker shade of point C or the outlined column of point F are usually sufficient.

#### Stacked Floating Columns

The stacked column chart allows multiple items to be stacked, since each floating column rests on the lower columns. This table and chart show low, medium, and high values.

Insert two columns for the two sets of calculations of floating column heights, and plot these with the minimum value.

As before, format the lowest column to be invisible, and adjust the axis scale, if desired.

As before, individual columns can be formatted independently of the others.

#### Floating Columns Crossing the Horizontal Axis

If you want to show floating columns that span negative and positive values, you will encounter problems, as shown by this sample data. It all looks fine when we examine the unstacked columns that show the minimum and maximum values.

However, when we plot the minimum values and stack the differences on top, we see that the stacking doesn’t work the way we would have liked. Excel plots columns with negative values below the X axis and columns with positive values above the X axis. Even though the Delta begins below the X axis, the Delta column has a positive value, and is plotted starting at zero or at the top of the minimum, if that value is positive.

Our simple formulas are not adequate, and we need a different approach. We’ll add three columns to the data sheet: one for the blank columns on which the floating columns will rest, one for whatever part of the floating column is positive (above the X axis), and one for whatever part of the floating column is negative. Using pseudo-references, the formulas we need are:

``````Blank:  =IF(High<0,High,IF(Low>0,Low,0))
Pos:  =IF(High>0,High-MAX(Low,0),0)
Neg:  =IF(Low<0,Low-MIN(High,0),0)``````

When we plot these values, we get the floating columns spanning the ranges we expect. Note that the floating columns may consist of two pieces, one (orange) below and one (blue) above the X axis, if necessary separated from the axis by the blank series (shown gray in the chart below).

As always, format the blank series to be blank (no border and no fill), and format the floaters as desired.

As before, individual floating columns can be formatted independently; the positive and negative portions can be formatted the same or differently.

#### Overlapping Floating Columns

You may want to show two sets of floating columns. For example, you may want to compare high and low temperatures for a set of dates with the average historical high and low temperatures for those dates. The way to handle this is to have one set of data on the primary axis, and the other set on the secondary axis.

The table and chart below show two sets of high and low values. The blue will eventually be shown on the primary axis and the orange on the secondary.

Insert two columns in the sheet, to capture the differences between high and low in the two sets of data. Here are the low and delta of each set in a stacked column chart.

Here is the same stacked column chart, with the orange series moved to the secondary axis. Each axis has its own Gap Width setting. Here I’ve used 50 for the primary axis (blue columns in back), and 150% for the secondary axis (orange columns in front).

More formatting: Hide the low columns (no border or fill) and adjust the Y axis. Also, delete the secondary vertical axis and if present the secondary horizontal axis. The chart will keep the series for each axis separate (so they have separate gap widths and so they don’t go stacking on each other), but will plot them on the primary axis scales.

Individual columns can always be formatted separately.

### Stacked Bar Charts (Horizontal Bars)

The techniques described above for Vertical Column Charts work the same for Horizontal Bar Charts. This tutorial will show simple floating bars, stacked floating bars, floating barsthat span the vertical axis, and overlapping floating bars, all using stacked bar charts.

#### Floating Bars

In the data set below, there are several high and low values for the categories in a bar chart. The clustered bar chart shows the values we want to highlight: we want a floating bar to connect each low value to its corresponding high value.

To get the vertical axis labels in your chart to be in the same top-to-bottom order as in the worksheet, follow the approach described in Why Are My Excel Bar Chart Categories Backwards? and in Excel Plotted My Bar Chart Upside-Down.

Note also that in an Excel Bar Chart the vertical axis is the X axis (for the independent variable), and the horizontal axis is the Y axis (for the dependent variable). This confuses a lot of people, so I usually stick to “horizontal” and “vertical” instead of “X” and “Y”.

We achieve this by inserting a column in the worksheet which has a simple formula to calculate the difference between high and low (“Delta” in the table below). Adjusting the data range and changing from clustered to stacked bars shows all we need. The floating bar is resting to the right of the Low value bar.

A little formatting gives us all we need. The Low series is formatted to be invisible: no border and no fill. The horizontal axis has been rescaled to zoom in on the data and remove some of the white space to the left of the floating bars.

You can change the relative width of the bars and gaps between by selecting them and changing the Gap Width property; a Gap Width of 100 means that the gap will be 100% as wide as a bar. I like to use gap widths of 50% to 100%, and I used 75% in most of the charts here.

With this technique, each bar can be selected (it may take two single clicks) and formatted independently of the rest, for purposes of highlighting one or more specific values.

#### Stacked Floating Bars

The stacked bar chart allows multiple items to be stacked, since each floating bar rests on the lower bars. This table and chart show low, medium, and high values.

Insert two columns for the two sets of calculations of floating bar lengths, and plot these with the minimum value.

As before, format the lowest bar to be invisible, and adjust the axis scale, if desired.

As before, individual bars can be formatted independently of the others.

#### Floating Bars Crossing the Vertical Axis

If you want to show floating bars that span negative and positive values, you will encounter problems, as shown by this sample data. It all looks fine when we examine the unstacked bars that show the minimum and maximum values.

However, when we plot the minimum values and stack the differences on top, we see that the stacking doesn’t work the way we would have liked. Excel plots bars with negative values to the left of the X axis and bars with positive values to the right of the X axis. Even though the Delta begins to the left of the X axis, the Delta bar has a positive value, and is plotted starting at zero or at the right end of the minimum, if that value is positive.

Our simple formulas are not adequate, and we need a different approach. We’ll add three columns to the data sheet: one for the blank bars on which the floating bars will rest, one for whatever part of the floating bar is positive (above the X axis), and one for whatever part of the floating bar is negative. Using pseudo-references, the formulas we need are:

``````Blank:  =IF(High<0,High,IF(Low>0,Low,0))
Pos:  =IF(High>0,High-MAX(Low,0),0)
Neg:  =IF(Low<0,Low-MIN(High,0),0)``````

When we plot these values, we get the floating bars spanning the ranges we expect. Note that the floating bars may consist of two pieces, one (orange) to the left of and one (blue) to the right of the X axis, if necessary separated from the axis by the blank series (shown gray in the chart below).

As always, format the blank series to be blank (no border and no fill), and format the floaters as desired.

As before, individual floating bars can be formatted independently; the positive and negative portions can be formatted the same or differently.

#### Overlapping Floating Bars

You may want to show two sets of floating bars. For example, you may want to compare high and low temperatures for a set of dates with the average historical high and low temperatures for those dates. The way to handle this is to have one set of data on the primary axis, and the other set on the secondary axis.

The table and chart below show two sets of high and low values. The blue will eventually be shown on the primary axis and the orange on the secondary.

Insert two columns in the sheet, to capture the differences between high and low in the two sets of data. Here are the low and delta of each set in a stacked bar chart.

Here is the same stacked bar chart, with the orange series moved to the secondary axis. Each axis has its own Gap Width setting. Here I’ve used 50 for the primary axis (blue bars in back), and 150% for the secondary axis (orange bars in front).

If you used the Upside-Down-Bar-Chart trick to plot the primary vertical axis labels in the same order that they appear in the worksheet, you’ll have to display the secondary vertical axis and apply the same trick to it.

More formatting: Hide the low bars (no border or fill) and adjust the Y axis. Also, delete the secondary horizontal axis and if present the secondary vertical axis. The chart will keep the series for each axis separate (so they have separate gap widths and so they don’t go stacking on each other), but will plot their values using the primary axis scales.

Individual bars can always be formatted separately.

## Line Chart Tricks

Excel’s line charts have a few built-in features that can be used to generate floating columns. These include Up-Down Bars and High-Low Lines, which can be combined to create Open-High-Low-Close (OHLC) Stock Charts, and also Drop Lines. Being tied into line charts, these features can only be used to generate vertical floating bars.

### Up-Down Bars

Up-Down Bars connect the values of a chart’s first line chart series and last line chart series with floating bars. There are actually two sets of bars: Up Bars, which connect a lower first value to a higher last value (the value goes Up), and Down Bars, which connect a higher first value to a lower last value (the value goes Down).

#### Floating Columns

For simple floating bars, you need to plot two data series in a line chart.

In Excel 2013, click the Plus icon next to the chart, and check the Up-Down Bars box; alternatively, on the Chart Tools > Design ribbon tab, click the Add Chart Element dropdown, and select Up-Down Bars. In Excel 2007 or 2010, on the Chart Tools > Layout ribbon tab, use the Up/Down Bars dropdown.

The chart below specifically has Down Bars, since all of the values in the last series are lower than all those of the first series.

Unlike the Stacked Column Chart technique, we need to carry out no calculations to determine how tall the floating bars have to be, and we don’t need a hidden set of bars on which to balance the floating bars.

Now apply a little formatting. Format the lines to have no markers and no lines, and give the up-down bars a suitable fill color.

You can change the relative width of the up-down bars and gaps between by selecting them and changing the Gap Width property of one of the line chart series; a Gap Width of 100 means that the gap will be 100% as wide as a bar. I like to use gap widths of 50% to 100%, and I used 75% in most of the charts here.

#### Mixed Formats: Up vs. Down

You can’t format individual up-down bars with their own colors, but since there are Up Bars and Down Bars, you can at least format some with one color and the rest with another color.

In the data below I’ve switched the First and Last values for points C and D. The line series cross, so the Last series is greater than the First for these points.

When Up-Down Bars are added, the black Down Bars for most of the points are replaced by Up Bars for points C and D.

In this way we can assign different formats to highlight selected points.

#### Up-Down Bars: First to Last

As mentioned before, Up-Down Bars connect the first line chart series to the last, ignoring values in between. In this data set, the earlier First and Last series have had intermediate series Second and Third inserted between them.

When Up-Down Bars are inserted, they connect First and Last, ignoring any values of Second and Third that may extend beyond First and Last.

#### Floating Columns Crossing the Horizontal Axis

When dealing with the Stacked Column Chart technique, if you recall, we couldn’t simply use a floating column to span values below and above the horizontal axis. Let’s try this with Up-Down Bars.

The lines show where we want the bars to appear, and when we add the Up-Down Bars…

… they go where we want. Again, no calculations required.

#### Overlapping Floating Columns

We can use Up-Down Bars to generate overlapping sets of floating bars, using primary and secondary axis groups. Here are two pairs of values plotted in a line chart. The Blue series are plotted on the primary axis, and the Orange series on the secondary. The secondary vertical axis has been deleted so that all values are plotted along the primary axis.

One of the primary series is selected, and Up-Down Bars are added.

One of the secondary series is selected, and again Up-Down Bars are selected.

The Up-Down Bars are formatted with different colors, and the line chart series are formatted to use different gap widths as well as no lines and no markers.

As before, individual bars can be formatted as Up Bars among a field of Down Bars. In the table below, first and last values have been switched for points C and D for both primary and secondary series. The line chart series cross…

… and the bars have been formatted differently to highlight points C and D.

### High-Low Lines

High Low Lines connect the highest and lowest values of a chart’s line chart series using vertical lines. The order of series makes no difference to these lines.

#### Floating Columns

For simple floating bars, you need to plot two data series in a line chart.

In Excel 2013, on the Chart Tools > Design ribbon tab, click the Add Chart Element dropdown, click Lines, and select High-Low Lines. In Excel 2007 or 2010, on the Chart Tools > Layout ribbon tab, use the Lines dropdown, and select High-Low Lines.

Format the plotted line series with no lines and no markers to hide them, and you’re left with boring black vertical lines.

In classic versions of Excel (2003 and earlier) you had limited ability to format such lines, but Excel 2007 introduced the ability to make the lines pretty much as wide as desired. The high-low lines in the chart below are 13.5 points thick, and look a lot like the floating columns produced by the other techniques above.

These lines can be assigned colors and thicknesses, but are not actually rectangular shapes, so they don’t have both border and fill colors.

#### High-Low Lines: Highest to Lowest

High-Low Lines work by connecting the lowest and highest values at each category. It doesn’t matter where in the sequence the high or low value occurs. In the data below, the highest (blue) and lowest (red) values are highlighted: they are distributed among the columns of data.

When High-Low Lines are added, they connect high and low, regardless of which series includes the extremes.

Note that no values are located above or below the formatted High-Low Lines.

#### Floating Columns Crossing the Horizontal Axis

The Stacked Column Chart technique required tricky formulas to allow a floating column to span values below and above the horizontal axis, while the Up-Down Bar approach did not. Let’s try this with High-Low Lines.

The lines show where we want the bars to appear, and when we add the High-Low Lines…

… and format them…

… they go where we want. As with Up-Down Bars, it works easily, no calculations required.

#### Overlapping Floating Columns

We can use High-Low Lines to generate overlapping sets of floating bars, using primary and secondary axis groups. Here are two pairs of values plotted in a line chart. The Blue series are plotted on the primary axis, and the Orange series on the secondary. The secondary vertical axis has been deleted so that all values are plotted along the primary axis.

A primary axis series is selected, and High-Low Lines are added.

A secondary axis series is selected, and again High-Low Lines are selected.

The High-Low Lines are formatted with different colors and line widths (13.5 and 8 pts), and the line chart series are formatted to use no lines and no markers.

### Stock Charts

Up-Down Bars and High-Low Lines were probably introduced into Excel to enable Open-High-Low-Close type Candlestick stock charts. Open and Close are the First and Last series from the Up-Down Bars examples above, and High and Low are, well, High and Low from the High-Low Lines examples. When applied together with the data columns in the appropriate order, simple line charts can be formatted into OHLC charts.

#### Line Chart Plus

Here is a table with two weeks of stock data and the corresponding line chart.

… and do a little formatting to create a candlestick chart. Use no markers or lines for the plotted series, and use your favorite colors and gap width for the Up-Down Bars. I always forget whether black or white bars signify up or down, and green and red make a bad combination for color vision deficient viewers, so I usually use blue for up and red or orange for down.

In “Classic” versions of Excel (97 through 2003), the line chart with High-Low Lines and Up-Down Bars was smart enough to recognize itself as a stock chart type, but since Excel 2007, such a chart only considers itself a line chart.

In Excel 2007 and later you cannot combine a stock chart with any other chart type, so you can’t add another series to show how, say, some market index varies in comparison. But you can make your stock chart using a line chart like I did here, then add whatever index lines you want.

#### Built-In OHLC

Using the same data set, you can directly insert an OHLC stock chart.

A little formatting, and it’s identical the the line chart stock chart above.

The only difference is that the “official” stock chart can’t be combined with any other data.

### Drop Lines

Drop Lines are lines that drop from data points to the horizontal (category) axis in line charts and area charts. Each line or area series in a chart can have Drop Lines, and every point in a series with Drop Lines has a Drop Line. Drop Lines cannot produce floating bars, since they by definition start at the axis, but they are related to these other techniques, and it’s useful to know about them, even if you use them only infrequently.

#### Column Chart

Here is the simple data and line chart we’ll use for our Drop Lines example.

In Excel 2013, on the Chart Tools > Design ribbon tab, click the Add Chart Element dropdown, click Lines, and select Drop Lines. In Excel 2007 or 2010, on the Chart Tools > Layout ribbon tab, use the Lines dropdown, and select Drop Lines. The lines are thin vertical black lines.

Like any lines in Excel 2007 and later, we have great flexibility in how we want to format Drop Lines. Here I’ve hidden the line series (no markers and no lines) and I’ve given the Drop Lines a width of 13.5 points and a blue/cyan line color, to produce what appears to be a standard column chart.

## Error Bars

### Line Charts with Error Bars

Line charts can have vertical Error Bars, oriented upwards or downwards of the data points, or both. This technique will work with column and area charts as well, but it’s easier to illustrate with line charts.

#### Floating Bars

We can use Error Bars with custom lengths as floating bars. Here we have high and low values, shown together in a line chart. There is another worksheet column with formulas that compute the differences (Delta).

We only need one of the line chart series for our Error Bars. We can plot the High values, and use Minus Error Bars for our floating bars (left), or we can plot the Low values, and use Plus Error Bars for our floating bars (right).

To assign custom values for error bars, first add Error Bars (in Excel 2013, use the Plus icon floating beside the chart; in Excel 2007 or 2010, use the Error Bars control on the Chart Tools > Layout tab). Then under Error Bar Values in the formatting dialog or task pane, select Custom and click Select Values. In the dialog, click in the Plus or Minus box, and select the range of cells with the Error Bar values. If you are only using one of the boxes, you have to explicitly type a zero in the other box, or Excel will not recognize your selection. Stupid Excel.

Hide the line chart series (format with no lines or markers), and format the Error Bar lines to use No End Caps, and appropriate width (here I’ve used 13.5 points) and line color.

#### Stacked Floating Bars

Here are High, Mid, and Low values along with the computed differences between adjacent points (Upper and Lower). We want stacked floating bars showing the distance between Low and Mid and between Mid and High.

“Aha!” you say, “I’m way ahead of you this time.” Plot the Mid series with Plus and Minus Error Bars (below left), then format the Error Bars as above (below right). But wait, the Plus and Minus Error Bars cannot be independently formatted?

Too bad, but it’s not a big deal. We just need two series, one for each independently formatted set of Error Bars. Here, I’ll plot the High and Low series.

I’ll add Minus Error Bars to the High series, then Plus error bars to the Low series.

Then I’ll hide both series and format the Error Bars.

#### Floating Columns Crossing the Horizontal Axis

When using Stacked Column Charts to generate floating bars, if you recall, we couldn’t simply use a floating column to span values below and above the horizontal axis. But Up-Down Bars and High-Low Lines didn’t care if they crossed the axis. Let’s try this with Error Bars, using the same High and Low values as before.

So we try the High series with Minus Error Bars, and the Low series with Plus Error Bars. Both allow the Error Bars to cross the category axis.

Format away.

#### Error Bars as Drop Lines

Error Bars can also be used to create Drop Lines. Here’s a simple line chart using the Drop Lines data from above.

Instead of adding Drop Lines, we can add Error Bars, choose the Minus direction, and a Percentage Value of 100.

No lines and markers for the data series, no end caps but thick lines and a nice line color for the Error Bars.

### XY Scatter Charts with Error Bars

As with the line charts in the preceding section, XY scatter charts can support vertical Error Bars. They can also support horizontal Error Bars. Every trick that works with line chart vertical Error Bars will also work with XY scatter chart vertical and horizontal Error Bars.

#### Vertical Floating Bars

Okay, we already know it’s going to work, but let’s run through the exercise for completeness. Here is the same High and Low data as before, with numeric rather than alphabetic X values.

Plot the High series with Minus Error Bars or the Low series with Plus Error Bars…

… a little formatting, and it’s the same as with the line chart Error Bars.

#### Horizontal Floating Bars

Plot the same data, but exchange X and Y in the chart.

Plot the High series with Minus horizontal Error Bars or the Low series with Plus horizontal Error Bars.

The same as before, but horizontal.

#### Vertical Drop Lines

We can use vertical error bars on an XY scatter chart to create drop lines. Same data as before, but in a scatter plot.

Add Minus Error Bars, using the Percentage Value option, and 100%.

Hide the plotted series and format the Error Bars.

This is the answer to two common Excel-related forum questions:

• How do I get Drop Lines on my scatter plot?
• How can I get a column chart on a value X axis?

#### Horizontal Drop Lines

Taking the previous data, but switching X and Y…

Add horizontal Minus Error Bars, using the Percentage Value option, and 100%, then hide the plotted series and format the Error Bars.

## XY Chart Line Segments

A very powerful technique for creating floating bars is using XY chart series line segments. You can make vertical and horizontal floating bars, but you are not constrained to these simple orientations. You can position endpoints of your bars pretty much anywhere in you chart, so the possibilities are limitless. In addition, line segments can be independently formatted, even within the same series of points.

I will use simple examples to illustrate the technique, then set you free.

### Floating Columns and Bars

Here are plots showing the same High and Low values for vertical and horizontal floating bars.

XY chart segments connect points in the same series, not in different series as in several of the techniques covered so far. So we need to arrange the data to plot points in one series, not two.

We could use that data, but then we’d have to format the in-between (slanted) segments to use no line color. Pretty tedious after the second or third line segment. But if we insert a blank row between each pair of values, Excel will not plot a line segment across the gap, so formatting will be easy.

As with the previous techniques using thick formatted lines, we’ll start with out XY scatter chart, and thicken up the lines. The vertical lines are 13.5 points, the horizontal lines, 10.5 points. But we’ve hidden the markers; why are there circles at the endpoints?

It turns out that Excel’s richly formattable lines have three different “Cap Type” styles. I’ve illustrated them here with small red markers to illustrate their appearance. The Round Cap style has a circular end shape extending beyond the endpoint of the line segment, where the marker is at the center of the circle. The Square Cap style has a square end end shape extending beyond the endpoint of the line segment, with the markers at the center of the square. And the Flat Cap stops exactly at the end of the segment, with the line squared off right at the marker.

We didn’t have to worry about this with the Error Bars, Drop Lines, and High-Low Lines, because their default “Cap Type” is Flat Cap.

The default “Cap Type” for chart series line segments is Round Cap, which makes for nice-looking polygonal plotted lines. But for floating bars, we most likely will want to use the Flat Cap style.

Here are floating bars using vertical and horizontal XY segments and the Flat Cap style.

We can select individual line segments (click once to select the entire series, and again to select the particular line segment), and format them independently of the others.

### Stacked Floating Columns and Bars

Here is our stacked floating bar data, plotted as separate series for vertical and horizontal floating bars.

Here is the same data rearranged to facilitate XY series line segments for vertical and horizontal floating bars, including the blank rows between pairs of points.

Hide the markers and fatten up the lines, and we’ve got stacked floating bars.

As before, individual bars (line segments) can be formatted independently of the rest.

## Summary

Here is a summary of the Floating Bar techniques discussed in this article.

Most techniques provide vertical bars, a couple horizontal bars, and XY Scatter Line Segments alone produce bars at any orientation.

A few techniques provide actual rectangular bars, which have a border and fill, while many approximate the appearance of a rectangle with thick line segments.

Some techniques allow individual bars in a set to be formatted independently, and some allow easy creation of stacked bars through the use of multiple series.

Stacke column and bar charts do not permit floating bars to cross the category axis, at least not without using tricky formulas to split bars into positive and negative components. The other techniques allow floating bars above, below, or across the axis.

## Secondary Axis as Percentage of Target

I haven’t posted in quite a while. I have a few long tutorials that I’m working on, but there hasn’t been enough uninterrupted time to get them done.

I’ve also been working on a new edition of my Chart Utility which will run in PowerPoint. This will allow those users who spend most of their time in PowerPoint to run the utility from there, switching to Excel for long enough to select their data, then build their chart as a native PowerPoint chart. I mean, it’s still really an Excel chart, but it will behave as if it were created in PowerPoint (which it was), and the data will sit in its data sheet in PowerPoint. Tentative plans call for the new utility to be released a month and a half ago. I’ll probably release it in stages, starting in a couple weeks.

In the meantime, a customer asked me to help with a certain topic, and I thought it made a great tutorial, so here it is.

## Secondary Axis as Percentage of Target

A customer had a stacked chart showing contributions to a fundraising effort by source (below) and wanted to show percentage toward the target. He had sketched something with labels and tickmarks and arrows everywhere, but I thought that was a bit too intrusive and cluttered. Instead I decided to use a secondary axis scale showing the percentage.

I’ve written before about how Secondary Axes in Charts can be more confusing than enlightening, adding to the cognitive load required to understand a chart. But I’ve also written about Secondary Axes that Work – Proportional Scales, and I’ve showed how to Add Percentages on the Secondary Axis. This is really another illustration of that last tutorial.

The only way to get a secondary axis is to have a series that is plotted on the secondary axis. I modified his data range by adding a series named “Blank” with a value of zero. The chart below is selected, and you can see from the highlighted ranges in the worksheet that it includes all series including the new Blank one. To the right I’ve done some calculations that we’ll be using momentarily. Essentially, given a target of 300 and a primary Y axis maximum of 160, I know that the corresponding secondary Y axis maximum should be 53.333%.

The charts below show the steps in constructing the improved chart. Left, I moved the Blank series to the secondary axis. Excel added a secondary vertical axis with a scale ranging from zero to one. Center, I deleted the gridlines, and made all three visible axis lines the same medium-light gray color, and gave the vertical axes major tick marks outside of the axis. Right, I rescaled the axes. I hard-coded the min and max of the primary axis to 0 and 160, just so they didn’t change without me knowing it. I set the min and max of the secondary axis to 0 and 53.333%, and changed the number format to Percentage with No Digits.

Finally I made the chart a little bit taller to allow for a descriptive title. Probably some indication of currency in the primary axis tick labels would also be useful. I also hid the row with the blank data and the columns with my secondary axis calculations, in case the entire sheet would be made public.

## Plotting Part of a Data Range

Excel is pretty handy for collecting, analyzing, and charting lots of data. If you want to plot a subset of your data, you can manually adjust the data range used by the chart. But there are easier ways to select partial data ranges, and to make this selection less tedious than manually adjusting the chart’s data.

## Plotting the Entire Range

In the workbook named “MSFT Price.xlsx” (click to download) and its worksheet named “MSFT 5-week” I have a range and chart showing five weeks of Microsoft adjusted closing price data.

The series formula of the chart is:

``=SERIES('MSFT 5-week'!\$B\$1,'MSFT 5-week'!\$A\$2:\$A\$26,'MSFT 5-week'!\$B\$2:\$B\$26,1)``

Recall that the series formula includes the chart data as follows:

``=SERIES(Series Name, X Values, Y Values, Plot Order)``

and that the series can be edited right in the Formula Bar, just like any other Excel formula.

A commonly asked question is, How can we plot part of this data, based on some kind of lookup? We’ll use a technique known variously as “Names” (the official moniker), “Defined Names”, “Defined Ranges”, and “Named Ranges”. I’ll show three approaches, which increase in complexity but also in ease of use.

## Defined Names – By Index

This exercise is in a worksheet named “MSFT By Index”. The data is the same and the chart is nominally the same as above. We’ll use cells E2:E3 to contain the index of the first and last rows of the data range we want to plot. We will count rows in the data range and enter values into these cells.

To define names, go to the Formulas tab of the ribbon, click on the Define Name button, and select Define Name… from the dropdown menu.

The New Name dialog appears. You can name the name, define its scope to the entire workbook or to one of its worksheets, add a comment, and write a formula which the name refers to.

For the dates in our chart, we will define the following name:

``````Name: MSFT_Date_Index
Refers To:
=OFFSET('MSFT By Index'!\$A\$1,'MSFT By Index'!\$E\$2,0):
OFFSET('MSFT By Index'!\$A\$1,'MSFT By Index'!\$E\$3,0)``````

OFFSET takes three arguments: a reference range, the number of rows down from this reference (up for a negative number of rows), and the number of columns to the right of the reference (to the left for a negative number of columns). OFFSET may take two more arguments: the number of rows high and the number of columns wide the resulting range is; if height and width are not entered, the resulting range is the same size as the reference range.

This OFFSET:

``=OFFSET('MSFT By Index'!\$A\$1,'MSFT By Index'!\$E\$2,0)``

indicates the cell \$E\$2 rows down and zero columns right from \$A\$1, while this OFFSET:

``=OFFSET('MSFT By Index'!\$A\$1,'MSFT By Index'!\$E\$3,0)``

indicates the cell \$E\$2 rows down and zero columns right from \$A\$1. Combining the two OFFSETs, separated by a colon, indicates the range bracketed by the two cells.

For the values, we will use this simple OFFSET that returns the prices in the column immediately to the right of the dates defined by MSFT_Date_Index:

``````Name: MSFT_Close_Index
Refers To:
=OFFSET(MSFT_Date_Index,0,1)``````

To make the chart dynamic, replace the cell addresses of the X and Y values in the original series formula:

``=SERIES('MSFT By Index'!\$B\$1,'MSFT By Index'!\$A\$2:\$A\$26,'MSFT By Index'!\$B\$2:\$B\$26,1)``

with the names we’ve defined. Here is the series formula as edited in the formula bar:

``````=SERIES('MSFT By Index'!\$B\$1,'MSFT By Index'!MSFT_Date_Index,
'MSFT By Index'!MSFT_Close_Index,1)``````

Since the names were scoped to the workbook, the worksheet name in the series formula is replaced by the workbook name:

``````=SERIES('MSFT By Index'!\$B\$1,'MSFT Price.xlsx'!MSFT_Date_Index,
'MSFT Price.xlsx'!MSFT_Close_Index,1)``````

Here is the chart for an arbitrary pair of first and last index values:

Adjust the first and last indices in E2:E3, and the chart updates to reflect the new range.

This is a bit tedious in practice, since you need to count rows and enter your findings in the index cells. It is not hard to make the process easier.

## Defined Names – By Match

This exercise is in a worksheet named “MSFT By Match”. The data and the chart are the same as above. We’ll use cells F2:F3 to contain the first and last dates of the data range we want to plot. Formulas in E2:E3 will determine the index of these dates within the date range, so we can use the same formulas as above for our names. We will enter dates into cells F2:F3 and let Excel calculate the index values in E2:E3, which is a little nicer than counting rows and typing a number.

These formulas in E2:E3 determine the where the dates in F2:F3 fall in the overall list of dates:

``````Cell E2:  =MATCH(F2,\$A\$2:\$A\$26,-1)
Cell E3:  =MATCH(F3,\$A\$2:\$A\$26,-1)``````

The last argument (-1) in the functions is needed because the dates in column A are listed in descending order. Omit this argument, or use +1, for data sorted in ascending order. Use zero if the data are unsorted labels.

The name that includes the dates for our chart is:

``````Name: MSFT_Date_Match
Refers To:
=OFFSET('MSFT By Match'!\$A\$1,'MSFT By Match'!\$E\$2,0):
OFFSET('MSFT By Match'!\$A\$1,'MSFT By Match'!\$E\$3,0)``````

This is the same, except for the sheet name, as in the previous exercise. The corresponding name for the prices should also look familiar:

``````Name: MSFT_Close_Match
Refers To:
=OFFSET(MSFT_Date_Match,0,1)``````

The series formula for the dynamic chart looks like this as edited:

``````=SERIES('MSFT By Match'!\$B\$1,'MSFT By Match'!MSFT_Date_Match,
'MSFT By Match'!MSFT_Close_Match,1)``````

and like this when Excel replaces the sheet name with the workbook name for the workbook-scoped names:

``````=SERIES('MSFT By Match'!\$B\$1,'MSFT Price.xlsx'!MSFT_Date_Match,
'MSFT Price.xlsx'!MSFT_Close_Match,1)``````

Here is how the chart looks for an arbitrary pair of dates:

Adjust the first and last dates in F2:F3, and the chart updates to reflect the new range.

It’s much easier to enter dates than to count rows, especially if the overall data range extended beyond the number of rows visible in one screen.

## Defined Names – By Combo Box

This exercise is in a worksheet named “MSFT By Combo”. The data and the chart are the same as above. We’ll use combo box controls that let us select the first and last dates of the data range we want to plot. The combo boxes link to cells E2:E3, so we can again use the same formulas as above for our names. Now we’ll use the best method in this article: we’ll select the dates we want using the combo boxes.

To add a combo box control, go to the Developer tab, click Insert, then click the Combo Box from the set of Forms Controls. The cursor turns into a shape crosshair; use this to draw the combo box.

If the Developer tab is not visible, you have to change your settings. In Excel 2010 and 2013, click the green File tab, select Options, select Customize Ribbon, and in the long list of tabs on the right, check the box in front of Developer. In Excel 2007, click the big round Office button in the top left of the Excel window, click Excel Options at the bottom of the dialog, then check Show Developer Tab in the Ribbon.

Right click on the combo box, and choose Format Control from the pop-up. Select the input range (the range of dates that you want to appear in the dropdown) and the cell link (where the index of the selected date will appear).

With both combo boxes formatted, defining the names proceeds as above, with essentially the same formulas. The dates:

Name: MSFT_Date_Combo

``````Refers To:
=OFFSET('MSFT By Combo'!\$A\$1,'MSFT By Combo'!\$E\$2,0):
OFFSET('MSFT By Combo'!\$A\$1,'MSFT By Combo'!\$E\$3,0)``````

The price values:

``````Name: MSFT_Close_Combo
Refers To:
=OFFSET(MSFT_Date_Combo,0,1)``````

Here is the series formula as edited to reflect the names:

``````=SERIES('MSFT By Combo'!\$B\$1,'MSFT By Combo'!MSFT_Date_Combo,
'MSFT By Combo'!MSFT_Close_Combo,1)``````

and adjusted by Excel to show the workbook name for the workbook-scoped names:

``````=SERIES('MSFT By Combo'!\$B\$1,'MSFT Price.xlsx'!MSFT_Date_Combo,
'MSFT Price.xlsx'!MSFT_Close_Combo,1)``````

Adjust the first and last dates selected in the combo boxes, and the chart updates to reflect the new range.

## Polar Plots

Microsoft Excel offers a number of circular charts, but none of them is usually a particularly good choice for displaying data. You can search this blog for “pie chart” and see numerous examples of badly applied pie charts. If you hunt for “radar chart” or “spider chart” you’ll see a class of charts that’s even more deceptive. A major part of the deficiency of radar plots is that they pretend to show a physical, geographical relationship which isn’t present at all.

Polar Plots, on the other hand, can be used to map information that has a true geographical component. Ironically, this includes actual radar feedback. The data for a polar plot is given in polar coordinates, which is given as R-theta, where R is the distance from the origin (center of the plot) and theta is the angle from a reference angle, such as north or conversely the positive horizontal axis of overlaid cartesian coordinates.

A Polar Plot is not a native Excel chart type, but it can be built using a relatively simple combination of Donut and XY Scatter chart types. We need to build the grid using a donut chart, then overlay the physical data using applicable XY Scatter chart types.

## Preparing the Data

We’ll use a donut chart for the circular grid. The data we need is simple, as shown below. I have 9 columns for the 9 concentric donuts (the smallest donut hole is 10% of the diameter, so this hole plus 9 rings of 10% make 100%). Each ring has 12 segments, so each comprises 30° of the 360° circle of the chart.

Our data is provided in polar coordinates in columns A and B below, where R is the distance from the origin to the data point, and theta is the angle from our reference angle (due north) to the point. These are converted to X and Y in columns C and D. The formula in C2and D2 are:

``````C2:  =A2*SIN(B2/180*PI())
D2:  =A2*COS(B2/180*PI())``````

These are filled down to C14 and D14.

## Making the Chart

To create the grid, select the blue shaded cells in the top table, and insert a donut chart (below left). The default diameter of the donut hole is 75% of the diameter of the whole chart, so all of the rings are scrunched together. Select any of the donuts and press Ctrl+1 (numeral one) to open the Format Series dialog or task pane, and set Donut Hole Size to 10%, the smallest possible value (below right). While you’re at it, shrink the ridiculously large chart title, if you need it at all.

Format each donut series so it has no fill and uses a thin (0.75 point) light gray (25% gray) border (below left). Our grid is ready for real data.

Select the orange shaded range of XY values in the second table above, and copy. Select the chart, and click the Paste Special button on the Paste dropdown on the Home tab of the ribbon to add the data (below right). The data is added as another concentric donut on the outside of the chart.

Use the following settings in the Paste Special dialog: Add cells as New Series, Values in Columns, Series Names in First Row, and Categories in First Column.

Select the added ring of data, and choose Change Series Chart Type from the pop-up menu. Choose one of the XY types. Here I’ve selected the line and markers option (below left); if you were plotting the advance of alien spacecraft you’d probably want the markers only option.

Excel has plotted the XY data on secondary axes: the axis labels of both are plainly visible in the left chart below. Format each secondary axis scale in turn so the minimum and maximum are equal but with opposite signs; in this case min is -10 and max is +10. Format the axis so there are no tick marks and no tick labels, and use the same line style as the donut grid borders, 0.75 points thick and 25% gray (below right).

Remove the major vertical and horizontal gridlines (below left). Remove the unwanted legend entries; click once to select the legend, then once more to select the unwanted entry, then click Delete (below right). If there is only one series of XY points, you can probably dispense with the legend.

Expand the size of the plot area (below left), and format the series lines and markers if desired (bottom right).

This may be complete enough for you, but as always, there are embellishments available to the clever chartmonger.

## Modified Grid

You can change the grid if you like. If I use the following expanded data, the inner few donuts have only 4 arcs, each covering 90° of the ring. The next few have 12 arcs, as above, each covering 30°. The last few have 24 arcs, covering 15° each.

The resulting grid is shown without data below left, and with data below right.

You can show the central circle (donut hole) without the crosshairs if you format the secondary axes to use no line color instead of 25% gray.

## Compass Point Labels

Suppose this is an actual geographic representation and you want to label the points of the compass. Set up data as shown below left. Copy the green range, select the chart, and use Paste Special as above. This series is plotted using the same chart type as the previous paste series was converted to, XY scatter with lines and markers.

Add labels to the new series; the default Y values are used in the labels (below left). Remove the title and legend, or shrink the plot area to make room for the labels.

Change the label positions to Above (for the north label), Right (east), Below (south), and Left (west).

Change the labels as appropriate (below left). You can use one of these approaches:

• Select each label (click to select the series of labels, then click again to select the individual label), double click to edit the label’s text, and type the label you want.
• Select each label (click to select the series of labels, then click again to select the individual label), type an equals sign in the formula bar, and click on the cell containing the label you want. The formula bar will show the link, e.g., =WorksheetName!\$F\$2.
• Download and install Rob Bovey’s free Chart Labeler from http://appspro.com. This allows you to assign labels from a worksheet range to the points in a chart.
• If you’re using Excel 2013, you can format the labels to use Values from Cells, and select the range of cells containing your labels.

Finally, format the last data series so it uses no lines and no markers (below right).

## 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:

1. Data for each series is arranged in Columns (preferable to Rows)
2. First column is used for Categories (X axis labels)
3. First row is used for Series Names
4. Top left cell is blank
5. Data below series names is numeric (right-adjusted with no alignment specified)
6. There are no blank rows or blank columns within the data range
7. 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

``Option Explicit``

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:

``````Private Sub Chart_Activate()

End Sub``````

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:

```Private Sub Chart_Activate()
MsgBox "Welcome to my Chart!"
End Sub
```

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:

```Private Sub Chart_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)

End Sub
```

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:

```Private Sub Chart_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)

MsgBox "Element: " & ElementID & vbCrLf & "  Arg 1: " & Arg1 _
& vbCrLf & "  Arg 2: " & Arg2

End Sub
```

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:

```Private Sub Chart_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)

Dim sElement As String
Dim sArg As String

Select Case ElementID
Case xlChartArea
sElement = "Chart Area"
Case xlChartTitle
sElement = "Chart Title"
Case xlPlotArea
sElement = "Plot Area"
Case xlLegend
sElement = "Legend"
Case xlFloor
sElement = "Floor"
Case xlWalls
sElement = "Walls"
Case xlCorners
sElement = "Corners"
Case xlDataTable
sElement = "Data Table"
Case xlSeries
sElement = "Series " & Arg1
If Arg2 > 0 Then sArg = "Point " & Arg2
Case xlDataLabel
sElement = "Data Label"
sArg = "Series " & Arg1
If Arg2 > 0 Then sArg = sArg & ", Point " & Arg2
Case xlTrendline
sElement = "Trendline"
sArg = "Series " & Arg1 & ", Trendline " & Arg2
Case xlErrorBars
sElement = "Error Bars"
sArg = "Series " & Arg1
Case xlXErrorBars
sElement = "X Error Bars"
sArg = "Series " & Arg1
Case xlYErrorBars
sElement = "Y Error Bars"
sArg = "Series " & Arg1
Case xlLegendEntry
sElement = "Legend Entry"
sArg = "Series " & Arg1
Case xlLegendKey
sElement = "Legend Key"
sArg = "Series " & Arg1
Case xlAxis
sElement = IIf(Arg1 = 1, "Primary ", "Secondary ")
sElement = sElement & IIf(Arg2 = 1, "Category ", "Value ")
sElement = sElement & "Axis"
Case xlMajorGridlines
sElement = IIf(Arg1 = 1, "Primary ", "Secondary ")
sElement = sElement & IIf(Arg2 = 1, "Category ", "Value ")
sElement = sElement & "Major Gridlines"
Case xlMinorGridlines
sElement = IIf(Arg1 = 1, "Primary ", "Secondary ")
sElement = sElement & IIf(Arg2 = 1, "Category ", "Value ")
sElement = sElement & "Minor Gridlines"
Case xlAxisTitle
sElement = IIf(Arg1 = 1, "Primary ", "Secondary ")
sElement = sElement & IIf(Arg2 = 1, "Category ", "Value ")
sElement = sElement & "Axis Title"
Case xlDisplayUnitLabel
sElement = IIf(Arg1 = 1, "Primary ", "Secondary ")
sElement = sElement & IIf(Arg2 = 1, "Category ", "Value ")
sElement = sElement & "Axis Display Unit Label"
Case xlUpBars
sElement = "Up Bars"
sArg = "Group Index " & Arg1
Case xlDownBars
sElement = "Down Bars"
sArg = "Group Index " & Arg1
Case xlSeriesLines
sElement = "Series Lines"
sArg = "Group Index " & Arg1
Case xlHiLoLines
sElement = "High-Low Lines"
sArg = "Group Index " & Arg1
Case xlDropLines
sElement = "Drop Lines"
sArg = "Group Index " & Arg1
sArg = "Group Index " & Arg1
Case xlShape
sElement = "Shape"
sArg = "Shape Number " & Arg1
Case xlNothing
sElement = "Nothing"
End Select

MsgBox sElement & IIf(Len(sArg) > 0, vbCrLf & sArg, "")
End Sub
```

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:

```Private Sub Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, _
ByVal x As Long, ByVal y As Long)

End Sub
```

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.
```Private Sub Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, _
ByVal x As Long, ByVal y As Long)

Dim ElementID As Long, Arg1 As Long, Arg2 As Long
Dim myX As Variant, myY As Double

With ActiveChart
' Pass x & y, return ElementID and Args
.GetChartElement x, y, ElementID, Arg1, Arg2

' Did we click over a point or data label?
If ElementID = xlSeries Or ElementID = xlDataLabel Then
If Arg2 > 0 Then
' Extract x value from array of x values
myX = WorksheetFunction.Index _
(.SeriesCollection(Arg1).XValues, Arg2)
' Extract y value from array of y values
myY = WorksheetFunction.Index _
(.SeriesCollection(Arg1).Values, Arg2)

' Display message box with point information
MsgBox "Series " & Arg1 & vbCrLf _
& """" & .SeriesCollection(Arg1).Name & """" & vbCrLf _
& "Point " & Arg2 & vbCrLf _
& "X = " & myX & vbCrLf _
& "Y = " & myY
End If
End If
End With
End Sub
```

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

```Private Sub Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, _
ByVal x As Long, ByVal y As Long)

Dim ElementID As Long, Arg1 As Long, Arg2 As Long
Dim myX As Variant

With ActiveChart
' Pass x & y, return ElementID and Args
.GetChartElement x, y, ElementID, Arg1, Arg2

' Did we click over a point or data label?
If ElementID = xlSeries Or ElementID = xlDataLabel Then
If Arg2 > 0 Then
' Extract x value from array of x values
myX = WorksheetFunction.Index _
(.SeriesCollection(Arg1).XValues, Arg2)

' Don't crash if chart doesn't exist
On Error Resume Next
' Activate the appropriate chart
ThisWorkbook.Charts("Chart " & myX).Select
On Error GoTo 0
End If
End If
End With
End Sub
```

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:

```Private Sub Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, ByVal x As Long, ByVal y As Long)

' Don't crash if chart doesn't exist
On Error Resume Next
ThisWorkbook.Charts("Chart Drilldown").Select
On Error GoTo 0

End Sub```

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:

```Option Explicit
```

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.

```Public WithEvents EventChart As Chart
```

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:

```Private Sub EventChart_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)

End Sub
```

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:

```Option Explicit

' Declare object of type "Chart" with events
Public WithEvents EventChart As Chart

Private Sub EventChart_Select(ByVal ElementID As Long, _
ByVal Arg1 As Long, ByVal Arg2 As Long)

MsgBox "Element: " & ElementID & vbCrLf & "  Arg 1: " & Arg1 _
& vbCrLf & "  Arg 2: " & Arg2

End Sub
```

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:

```Option Explicit
```

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.

```Dim clsChartEvent As New CChartEvent
```

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:

```Set clsChartEvent.EventChart = ActiveChart
```

To deactivate the chart for events, you assign the EventChart property of the instance of the class to Nothing:

```Set clsChartEvent.EventChart = 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:

```Option Explicit

Dim clsChartEvent As New CChartEvent

Sub Set_This_Chart()
' Skip if no chart is selected to prevent an error
If Not ActiveChart Is Nothing Then
' Enable events for the active chart
' Works for chart sheets and embedded charts
Set clsChartEvent.EventChart = ActiveChart
End If
End Sub

Sub Reset_Chart()
' Disable events for chart previously enabled as active chart
Set clsChartEvent.EventChart = Nothing
End Sub
```

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:

```Option Explicit

Dim clsChartEvents() As New CChartEvent

Sub Set_All_Charts()
' Enable events for all charts embedded on a sheet
' Works for embedded charts on a worksheet or chart sheet
If ActiveSheet.ChartObjects.Count > 0 Then
ReDim clsChartEvents(1 To ActiveSheet.ChartObjects.Count)
Dim chtObj As ChartObject
Dim chtnum As Integer

chtnum = 1
For Each chtObj In ActiveSheet.ChartObjects
' Debug.Print chtObj.Name, chtObj.Parent.Name
Set clsChartEvents(chtnum).EventChart = chtObj.Chart
chtnum = chtnum + 1
Next ' chtObj
End If
End Sub

Sub Reset_All_Charts()
' Disable events for all charts previously enabled together
Dim chtnum As Integer
On Error Resume Next
Set clsChartEvent.EventChart = Nothing
For chtnum = 1 To UBound(clsChartEvents)
Set clsChartEvents(chtnum).EventChart = Nothing
Next ' chtnum
End Sub
```

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:

```Option Explicit

Dim clsChartEvent As New CChartEvent
Dim clsChartEvents() As New CChartEvent

Sub Set_All_Charts()
' Enable events for active sheet if sheet is a chart sheet
If TypeName(ActiveSheet) = "Chart" Then
Set clsChartEvent.EventChart = ActiveSheet
End If

' Enable events for all charts embedded on a sheet
' Works for embedded charts on a worksheet or chart sheet
If ActiveSheet.ChartObjects.Count > 0 Then
ReDim clsChartEvents(1 To ActiveSheet.ChartObjects.Count)
Dim chtObj As ChartObject
Dim chtnum As Integer

chtnum = 1
For Each chtObj In ActiveSheet.ChartObjects
' Debug.Print chtObj.Name, chtObj.Parent.Name
Set clsChartEvents(chtnum).EventChart = chtObj.Chart
chtnum = chtnum + 1
Next ' chtObj
End If
End Sub

Sub Reset_All_Charts()
' Disable events for all charts previously enabled together
Dim chtnum As Integer
On Error Resume Next
Set clsChartEvent.EventChart = Nothing
For chtnum = 1 To UBound(clsChartEvents)
Set clsChartEvents(chtnum).EventChart = Nothing
Next ' chtnum
End Sub
```

## 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:

1. all charts in one worksheet
2. all charts in one chart sheet
3. all charts on all sheets in one workbook
4. 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:

```Option Explicit

Private Sub Worksheet_Activate()
Set_All_Charts
End Sub

Private Sub Worksheet_Deactivate()
Reset_All_Charts
End Sub
```

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:

```Option Explicit

Private Sub Chart_Activate()
Set_All_Charts
End Sub

Private Sub Chart_Deactivate()
Reset_All_Charts
End Sub
```

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:

```Option Explicit

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Set_All_Charts
End Sub

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Reset_All_Charts
End Sub
```

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.

```Public WithEvents EventApp As Excel.Application
```

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:

```Option Explicit

Public WithEvents EventApp As Excel.Application

Private Sub EventApp_SheetActivate(ByVal Sh As Object)
Set_All_Charts
End Sub

Private Sub EventApp_SheetDeactivate(ByVal Sh As Object)
Reset_All_Charts
End Sub

Private Sub EventApp_WorkbookActivate(ByVal Wb As Workbook)
Set_All_Charts
End Sub

Private Sub EventApp_WorkbookDeactivate(ByVal Wb As Workbook)
Reset_All_Charts
End Sub
```

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:

```Dim clsAppEvent As New CAppEvent
```

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.

```Sub InitializeAppEvents()
Set clsAppEvent.EventApp = Application
Set_All_Charts
End Sub

Sub TerminateAppEvents()
Set clsAppEvent.EventApp = Nothing
Reset_All_Charts
End Sub
```

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:

```Private Sub Workbook_Open()
InitializeAppEvents
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
TerminateAppEvents
End Sub
```

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:

```Private Sub Workbook_AddinInstall()
InitializeAppEvents
End Sub

TerminateAppEvents
End Sub
```

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