Detect When an Excel Chart is Deleted

A customer of mine (thanks Simon! Hot smile) contacted me with a solution he discovered while trying to determine if a user deleted a chart from a workbook. The following code belongs in a Ribbon.cs with a button to insert the chart.

When the user clicks the button to add the chart, the deactivate event is then attached to the chart. The trick is to throw an exception to detect the deletion. When the chart is deleted, the deactivate event will fire, but any attempt to reference any property of the chart will fail with an exception.In this case an attempt is made to access the “.Name” property of the chart. If it is deleted, it will throw an exception and tell you the chart was deleted. Here is the code:

Excel.Chart chart;
private void button1_Click(object sender,
                           RibbonControlEventArgs e)
{
    try
    {
        // hook the deactivate event
        chart = Globals.ThisAddIn.Application.ActiveChart;
        if (chart != null)
        {
            chart.Deactivate += new
                Excel.ChartEvents_DeactivateEventHandler(
                        chart_Deactivate);
        }
    }
    catch (Exception ex)
    { }
}

/// <summary>
/// Caused when a selected chart is deactivated.
/// </summary>
void chart_Deactivate()
{
    try
    {
        string a = chart.Name;
        MessageBox.Show("Chart has been deselected " +
                        " but it is still around");

    }
    catch
    {
        MessageBox.Show("Chart has been deleted!");
        return;
    }
}

1 thought on “Detect When an Excel Chart is Deleted”

  1. That’s what I used in the end. Seems there is no other way than accessing some property inside a try catch. Thanks for the tip.

Leave a Reply