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?
In a C# XLL (Excel add-in using ExcelDNA), how do I detect when a Workbook is closing?
106 Views Asked by RobBaker At
2
There are 2 best solutions below
0
On
Install the NetOffice Framework via nuget:
Now in your add-in's AutoOpen you can create an Application object that gives you access to all the COM stuff, including events.
I'm working in F#, not C#, but here's how it looks for me:
open NetOffice.ExcelApi
open NetOffice.ExcelApi.Enums
module AddIn =
let mutable private myApp : Application = null
let beforeClose = Application_WorkbookBeforeCloseEventHandler (fun sender e ->
// do something here - sender is the workbook
())
// I call this from my type I define that implements IExcelAddIn
let autoOpen() =
myApp <- new Application (null, ExcelDnaUtil.Application)
myApp.add_WorkbookBeforeCloseEvent beforeClose
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:
Then I use the following in one of my bits of code that runs pretty early (after loading the XLL):
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.