How do I create an Excel automation add-in in C# t

2019-04-02 04:11发布

I have a working RtdServer-based automation add-in:
How do I create a real-time Excel automation add-in in C# using RtdServer?.

Creating a VBA wrapper is trivial:

Function RtdWrapper(start)
    RtdWrapper = Excel.Application.WorksheetFunction.RTD("StackOverflow.RtdServer.ProgId", "", start)
End Function

This works. I have attempted to create a C# wrapper as follows:

[ClassInterface(ClassInterfaceType.AutoDual)]
public class RtdWrappers
{
    private readonly Microsoft.Office.Interop.Excel.Application _application = new Application();

    public object Countdown(object startingCount)
    {
        var start = Convert.ToInt32(startingCount.ToString());
        return _application.WorksheetFunction.RTD("StackOverflow.RtdServer.ProgId", string.Empty, start);
    }

    [ComRegisterFunctionAttribute]
    public static void RegisterFunction(Type t)
    {
        Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("CLSID\\{" + t.GUID.ToString().ToUpper() + "}\\Programmable");
    }

    [ComUnregisterFunctionAttribute]
    public static void UnregisterFunction(Type t)
    {
        Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey("CLSID\\{" + t.GUID.ToString().ToUpper() + "}\\Programmable");
    }
}

When I enter "=Countdown(150)" into a cell in Excel it shows the initial value of 150 which is returned by ConnectData but never updates. Is there some callback that I should register? Am I instantiating the Application object correctly? What am I missing?

Thanks,

Frank

1条回答
小情绪 Triste *
2楼-- · 2019-04-02 04:40

Indeed, you are not getting hold of the right Application object. One solution is to implement the IDTExtensibility2 interface in your add-in. This interface has an OnConnection method that Excel will call when loading your add-in. In this method you are passed the Application object which you can keep in a local variable for later use.

查看更多
登录 后发表回答