【发布时间】:2016-07-04 04:41:26
【问题描述】:
我创建了一个新的 VSTO Excel 工作簿项目,并且只尝试使用“ThisWorkbook”获取运行宏的工作簿
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
namespace TestWorkbook
{
public partial class Sheet1
{
Excel.Workbook mWorkBook;
private void Sheet1_Startup(object sender, System.EventArgs e)
{
mWorkBook = this.Application.ThisWorkbook;
}
private void Sheet1_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(Sheet1_Startup);
this.Shutdown += new System.EventHandler(Sheet1_Shutdown);
}
#endregion
}
}
代码只是VS创建的默认代码。我只添加了带有mWorkbook 变量的两行。
当我运行时,我得到了 COM 异常:
System.Runtime.InteropServices.COMException 发生 HRESULT: 0x800A03EC
在调试器中,查看 this.Application.ThisWorkbook 时,值为:
{System.Reflection.TargetInvocationException: 出现异常 由调用的目标抛出。 ---> System.Runtime.InteropServices.COMException:来自 HRESULT 的异常: 0x800A03EC --- 内部异常堆栈跟踪结束 --- 在 System.RuntimeType.InvokeDispMethod(字符串名称,BindingFlags invokeAttr,对象目标,Object[] args,Boolean[] byrefModifiers, Int32 文化,String[] namedParameters) 在 System.RuntimeType.InvokeMember(字符串名称,BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] 修饰符、CultureInfo 文化、String[] 命名参数)在 System.Dynamic.IDispatchComObject.GetMembers(IEnumerable`1 名称)}
我发现唯一接近答案的是“有时这对其他用户来说会消失”和“更新 .Net”。任何想法接下来要尝试什么?谢谢!
更新 我昨天刚刚安装了 Office 开发工具。今天,我注意到我可以创建和启动一个项目。如果我关闭它,由于版本不兼容问题,我无法重新打开。与此相关的 MS 帮助根本没有帮助。大约一个月前,我全新安装了 Windows 10,以及 VS 社区版,其中包含两者的所有更新。我真的没有时间为这项任务追查 MS 版本的问题,我想我现在只想以蛮力的方式构建我的工作簿。有点沮丧,但在这上面浪费了太多时间。如果我找到答案,稍后会回到它并发布。
【问题讨论】:
-
如果您想获取活动工作簿,您可以尝试
this.Application.ActiveWorkbook。我相信Application.ThisWorkbook是针对宏的。 -
我在发布之前尝试了您的“Application.ActiveWorkbook”并遇到了类似的错误。不过还是谢谢。
-
您可以尝试的另一件事是附加到
Application上的WorkbookOpen事件。我过去曾看到 VSTO 在 Excel 准备好之前尝试获取工作簿时抛出异常。 -
我会尝试一下,一旦我回到这个。谢谢。
标签: c# .net excel comexception vba