【发布时间】:2019-07-07 03:51:39
【问题描述】:
我正在使用 VSTO 使一堆用 C# 编写的函数可以从 Excel VBA 访问。创建具有多个属性的类型(例如,一个类)会很方便,这样我就可以将单个类传入和传出 excel。
VSTO 覆盖 RequestComAddInAutomationService 方法以公开一个包含我要公开的方法的类。因此,我无法弄清楚如何公开第二个类或结构等。我的类使用接口将其方法公开给 vba,但您不能在接口中定义类型。我试图在我的主类中创建类型类,但无法让 vba 识别它。
这是“ThisAddIn.cs:”中的代码:
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO 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(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
private AddInUtilities utilities;
protected override object RequestComAddInAutomationService()
{
if (utilities == null) utilities = new AddInUtilities();
return utilities;
}
}
在 AddInUtilities.cs 中:
[ComVisible(true)] 公共接口 IAddInUtilities { 字符串[] ListKeyMetrics(); 字符串[] ListSetptMetrics(); AddInUtilities.testStruct myTest(); 双重测试{得到;放; } }
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class AddInUtilities : IAddInUtilities
{
public class testStruct
{
private double _x;
private double _y;
public testStruct(int z)
{
_x = 0;
_y = 0;
}
public double x
{
get { return _x; }
set { _x = value; }
}
public double y
{
get { return _y; }
set { _y = value; }
}
}
public double test
{
get; set;
} = 5;
public string[] ListKeyMetrics()
{
string[] ret = { "SCz", "SCx", "etc" };
return ret;
}
public string[] ListSetptMetrics()
{
string[] ret = { "FRH", "RRH", "etc" };
return ret;
}
public testStruct myTest()
{
testStruct ret = new testStruct(0);
ret.x = 1;
ret.y = 2;
return ret;
}
}
关于如何在 VSTO 中创建类型并使其在 vba 中可见的任何建议?
【问题讨论】:
-
这可能会有所帮助 - stackoverflow.com/questions/41162601/…
-
FWIW,我要补充一点,我没有看到您在这里需要 VSTO 的原因。这可以通过在 VBA 项目中引用的普通 C# DLL 来完成,正如 @Vityata 链接到的那样。通常,您使用 VSTO 是因为您想要自定义主机,在 Office 主机上公开一些自定义功能或类似的东西。但是对于一堆功能呢? VSTO 只是让你变得更复杂。 COM 互操作是您所需要的。