Excel VSTO NewWorkbook event does not occur at startup

I am developing an Excel 2010 application at the application level. I need to write handlers for some application events related to the workbook interface, especially the NewWorkbook event.

So, in the ThisAddIn_Startup handler, I added the following code:

Microsoft.Office.Interop.Excel.AppEvents_Event app = Globals.ThisAddIn.Application; app.NewWorkbook += MyApp_NewWorkbook; 

It works great when a new workbook is created during the start of an Excel instance. But when I start a new instance of Excel (which in standard cases means creating a new workbook), this event is not caught by my handler. I believe that when I start a new instance of Excel, the NewWorkbook event fires before the ThisAddIn_Startup event.

In the event that the WorkbookOpen event application behaves as I expected, the event is caught when I open an existing workbook in the current Excel instance, and also when I simply double-click the file. I wonder why these events are handled differently?

What should I do in this case? I need to find out if a new workbook has been created or if an existing one exists, regardless of whether Excel is running or not.

+4
source share
2 answers

How about performing your actions on all the books that open when the add-in loads?

Something like the following in the ThisAddIn_Startup handler? (there is no IDE, therefore it is written by hand):

 foreach (var workbook in Globals.ThisAddIn.Application.Workbooks) { // Do your thing } 

Then use event handling to catch any books that subsequently open.

+1
source

In checking the WorkbookOpen event for

 string.IsNullOrEmpty(application.ActiveWorkbook.Path) 

which means your book is never saved. The whole new workbook created when you open Excel will be true for the above line.

+1
source

Source: https://habr.com/ru/post/1495560/


All Articles