How to Get an Excel VSTO Workbook Closed Event

In an Excel add-in the Application class exposes several workbook related events. The workbook open event is one of them, however its direct counterpart, workbook closed event, is missing.

We could resort to the WorkbookBeforeClose event, but for a modified workbook Excel will allow the user to save/discard changes or cancel the close operation. Since this logic occurs after the before close event you have no guarantees that the workbook will in fact be closed.

Not wanting to override the native save changes dialog I ended up implementing a monitor that when associated to the Excel application can correctly trigger workbook closed events.

You can download the monitor implementation from GitHub and use it like illustrated in the following snippet:

private WorkbookClosedMonitor Monitor { get; set; }

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Monitor = new WorkbookClosedMonitor(this.Application);

    this.Monitor.WorkbookClosed += Monitor_WorkbookClosed;
}

void Monitor_WorkbookClosed(object sender, WorkbookClosedEventArgs e)
{
    Debug.WriteLine(String.Format("Closed workbook: {0}", e.Name));
}
Advertisement

5 thoughts on “How to Get an Excel VSTO Workbook Closed Event”

  1. Good stuff!
    BUT, there’s a BUG in your code 😀
    The first workbook opened is not raising the event in a determined situation. This is how you can reproduce it:
    Using Excel 2010, open up Excel, it will open “Book1”.
    Without changing anything, open a recent Workbook. (File/Recent/*.xls)
    “Book1” will be closed but no event is raised.
    I have a solution for it, and can email it to you if you want, but it would be more fun to see what solution you’d come up with.
    Cheers

    1. Thanks for the feedback, I’ll try to look into it but as things go it will not be in a near future.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s