4

I'm developing an Excel 2010 application-level addin. I need to write handlers for some of the Application events connected with the Workbook interface, especially NewWorkbook event.

So in ThisAddIn_Startup handler I added code like this:

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

It works fine when the new Workbook is created within running Excel instance. But when I run new Excel instance (which, in standard cases, implies creating new Workbook) this event isn't catched by my handler. I suppose then that when I run new Excel instance the NewWorkbook event occurs before the ThisAddIn_Startup event.

In case of the WorkbookOpen event application behaves just like I would expect - event is catched when I open existing Workbook within the running Excel instance as well as when I just double-click the file. I'm wondering why these events are handled differently?

What should I do in this case? I need to recognize if a new Workbook was created or an existing one was opened regardless of whether Excel is already running or not.

4

2 回答 2

1

How about performing your action on all the workbooks that are open when your add-in loads?

Something like the following in the ThisAddIn_Startup handler? (no IDE here, so written by hand):

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

Then use your event handling to catch any workbooks that open subsequently.

于 2013-08-06T15:27:34.353 回答
1

In the WorkbookOpen event check for

string.IsNullOrEmpty(application.ActiveWorkbook.Path)

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

于 2013-08-06T15:54:16.563 回答