这与直截了当的事情相去甚远,但这就是您完成任务的方式。我会尽可能明确,因为前两三次我试图这样做,我错过了很多。
首先,当您创建承载ExcelReturnString() 的类时,您需要使用具有以下属性的接口来装饰该类,然后还标记要公开的每个方法的属性。为了这个示例,我制作了加载项类“TestExcelAddIn”:
using System.Data;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace TestExcelAddIn
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IStringGetter
{
string ExcelReturnString();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class StringGetter : IStringGetter
{
public string ExcelReturnString()
{
return "This is the string: hi";
}
}
}
然后,在项目中与“Excel”相关联的主类中,您必须按以下方式覆盖RequestComAddInAutomationService。再一次,我包含了所有内容,所以你知道哪个类是哪个(我第一次读的时候不知道)。
namespace TestExcelAddIn
{
public partial class ExcelTest
{
private StringGetter myAddIn;
protected override object RequestComAddInAutomationService()
{
if (myAddIn == null)
myAddIn = new StringGetter();
return myAddIn;
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
#endregion
}
}
现在 VBA 已准备好以下列方式使用此方法:
Sub Test()
Dim addin As Office.COMAddIn
Dim automationObject As Object
Dim returnString As String
Set addin = Application.COMAddIns("TestExcelAddIn")
Set automationObject = addin.Object
returnString = automationObject.ExcelReturnString
End Sub
你本可以给我 100 年的时间来解决这个问题,而我不会。实际上归功于 MSDN 上的罗塞塔石碑:
https://msdn.microsoft.com/en-us/library/bb608621.aspx?f=255&MSPPError=-2147217396