Application.ActiveWorkbook is null in Excel Addin

2019-07-21 20:44发布

问题:

I am writing an Excel Add-in. Following is my code

private void ThisAddInStartup(object sender, EventArgs e)
{
    Excel.Sheets sheets = Application.ActiveWorkbook.Sheets;
    _worksheet = (from Excel.Worksheet sheet in sheets where sheet.Name.Contains(SheetName) select sheet).FirstOrDefault();

    Application.SheetChange += ApplicationSheetChange;
}

When I debug, everything works great. But When I open an excel file directly from my hard drive then I am getting Application.ActiveWorkbook as null. Can anybody help me to understand this.

I want to start my add-in as when an excel file opens. Basically my add-in is tracking change in excel sheet of workbook and doing some required action.

If it matters, I am using Office 2007, Visual Studio 2012. I am able to run the solution after changing the project file and replacing Office 14 part with 12.

回答1:

I assume you mean ThisAddIn_Startup and instead of ThisAddInStartup. If not then that is probably a problem.

It is recommended that you don't try to access a document inside the ThisAddin_Startup method. This is because Office doesn't always have a document ready when this method is run so you could run into some strange behavior. Instead, hook into an event that fires when the user opens a document and run your code there. It should look something like this (Note: I haven't tested this code but it should work):

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    // Hook into the workbook open event
    this.Application.WorkbookOpen += new AppEvents_WorkbookOpenEventHandler(WorkWithWorkbook);
}

private void WorkWithWorkbook(Microsoft.Office.Interop.Excel.Workbook workbook)
{
    // Workbook has been opened. Do stuff here.
}

Check out the MSDN article on writing Application-Level addins. Specifically pay attention to the part that talks about accessing a document when the application starts.

http://msdn.microsoft.com/en-us/library/vstudio/bb157876.aspx