Application.ActiveWorkbook是Excel加载项空 [英] Application.ActiveWorkbook is null in Excel Addin

查看:1384
本文介绍了Application.ActiveWorkbook是Excel加载项空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个Excel外接程序。下面是我的代码

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;
}

当我调试,一切都很正常。但是当我打开一个Excel直接从我的硬盘文件,然后我得到 Application.ActiveWorkbook 。任何人可以帮助我理解这一点。

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.

我要开始我的外接一个excel文件打开时。基本上我的加载项跟踪工作簿的Excel工作表的变化,做一些所需的操作。

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.

如果它的事项,我使用Office 2007时,Visual Studio 2012年我能够改变项目文件和更换后运行解决方案的Office 14 12

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.

推荐答案

我假定你的意思 ThisAddIn_Startup 键,而不是 ThisAddInStartup 。如果没有,那么这可能是一个问题。

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

建议您不要尝试访问ThisAddin_Startup方法中的文件。这是因为Office并不总是有一个文档准备好时,这种方法运行,所以你可能会遇到一些奇怪的行为。相反,挂钩到一个事件将触发当用户打开一个文档,还有运行代码。它应该是这个样子(注:我没有测试代码,但它应该工作):

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.
}



查看上写应用程序级加载项MSDN文章。特别要注意,讨论有关访问应用程序启动时的文件的部分。

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

这篇关于Application.ActiveWorkbook是Excel加载项空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆