获取 excel 文件名和路径错误 - C#

Get excel filename and path error - C#

我遇到了一个非常愚蠢的错误。我是 VSTO 的新手,我需要在我的插件中的某个变量中获取 Excel 文件的位置。

string name = ActiveWorkbook.FullName;

我在 ActiveWorkbook 下方收到一条红线,错误为:

The name ActiveWorkBook does not exist in the current context.

我在代码中添加了对 Microsoft.Office.Interop.Excel 的引用,但它显示此错误。我是新来的..我错过了什么吗?

ActiveWorkbook is not a class. It's the property of the Application界面。您不能以 class-name 方式调用它。

然后,您需要将代码更改为 this.Application.ActiveWorkbook.FullName;

在 Excel VSTO 中,您需要使用 Globals.ThisAddIn.Application 来访问 Excel 应用程序模型,见下文:

   var wb = Globals.ThisAddIn.Application.ActiveWorkbook;
   string name = wb.FullName;
  

另见 Programming VSTO Add-ins

如果你的代码在ThisAddInclass里面你可以直接调用:this.Application.ActiveWorkbook