我正在使用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(); string [] 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中可见的任何建议?
答案 0 :(得分:0)
这里不需要VSTO。由于您打算从VBA运行功能,因此无需运行内部版本即可与Excel进行通信,而只需与VBA及其需要时进行通信即可。
最好是创建一个类库项目(DLL),然后可以从VBA中引用它。