Search code examples
c#excelexcel-dna

In a C# XLL (Excel add-in using ExcelDNA), how do I detect when a Workbook is closing?


I have an XLL built using ExcelDNA in C#, that contains some UDFs for calculations to use in plain XLSX workbooks. There are some actions I want the add-in to perform on the BeforeClose event in the Workbooks themselves, without having to change the Workbooks to XLSM files with their own event handlers. How do I get my XLL to catch the "workbook is closing" event from the Excel application, and then grab a reference to that Workbook (actually just its filename will do), so that I can run some actions on the file before it actually closes?


Solution

  • I found an alternative to this just using Microsoft.Office.Interop.Excel (which I am already using for some very light interaction with Excel anyway). I just defined a method for the event handler:

    public void Event_Application_WorkbookBeforeClose(xl.Workbook workbook, ref bool Cancel)
    { // Excel BeforeClose event handler - use to tidy up
        // Do some stuff
    }
    

    Then I use the following in one of my bits of code that runs pretty early (after loading the XLL):

    if (!eventHandlerLoaded) { app.WorkbookBeforeClose += Event_Application_WorkbookBeforeClose; eventHandlerLoaded = true; }
    

    Where I use a static bool "eventHandlerLoaded" to check if I have already appended the event handler yet or not.

    Turns out it was pretty simple.