在macros中调用Excel加载macros函数

我正在开发Excel 2013的加载项,并在Excel加载项中创build了一个函数,如下所示

public string ExcelReturnString() { return "This is the string: hi"; } 

我已经使用下面的代码来调用该函数,但它会引发错误。

 Application.Run(ExcelReturnString) 

我怎样才能在macros中调用外接function?

这是关于最直接的最远的事情,但这是你如何完成任务。 我会尽可能的明确,因为我试图这样做的前两三次,我错过了很多。

首先,当您创build承载ExcelReturnString()的类时,需要使用具有以下属性的接口来修饰类,然后还要标记每个要公开的方法的属性。 为了这个例子,我创build了附加类“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年的时间来解决这个问题,我也不会这样做。 其实,Rosetta石头上的MSDN值得信赖:

https://msdn.microsoft.com/en-us/library/bb608621.aspx?f=255&MSPPError=-2147217396

除了上面的DaveMac的注意事项,在调用另一个例程时还要记住几点:

如果您从驻留在与该例程相同的工作簿/插件的例程中调用macros,则不必使用Application.Run。 你可以用它的名字来调用它:

 MyMacro 

如果您正在调用不同工作簿中的macros,那么您确实需要使用Application.Run,​​但是您也希望在macros所在的位置使用工作簿名称,否则VBA将不知道应该在哪里查找macros:

 Application.Run "'My Fancy Spreadsheet.xlsm!'MyMacro" 

您的代码似乎是Java。

例如,Excel使用Visual Basic。

 Function excelreturnstring() excelreturnstring = "this is the string: hi" End function