制作MS Excel用户定义函数

时间:2013-12-20 02:13:21

标签: c# excel user-defined-functions

我正在尝试在C#中为MS Excel创建用户定义函数。

但无论我尝试什么,当我尝试将外接程序添加到Excel时,我总是得到臭名昭着的“您选择的文件不包含新的自动化服务器,或者您没有足够的权限注册自动化服务器“错误。

以下是我从中获取的代码和在线示例,以便尝试一下:

// C#

using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace AutomationAddin
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class MyUdf
    {
        public MyUdf()
        {
        }

        public double addMeTest(double x, double y)
        {
            return x + y;
        }

        [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");
        }
    }
}

我在 Excel 2013 x64 Excel 2010 x86

上使用 MS Visual Studio 2012 进行了尝试

解决方案我发现并尝试过没有成功:

  • [ClassInterface(ClassInterfaceType.AutoDual)],如代码所示
  • [ComRegisterFunctionAttribute]和[ComUnregisterFunctionAttribute],如代码所示
  • regasm / codebase也没有做任何事情
  • 打开/关闭“注册COM互操作”(VS在建设时以管理员身份运行)
  • [assembly:ComVisible(true)]设为true
  • 尝试了网络上的不同代码示例
  • 在stackoverflow上阅读:How to get COM Server for Excel written in VB.NET installed and registered in Automation Servers list?
  • 我也一起尝试了以上所有 - 这里没有运气
  • 以管理模式运行Excel

所以请大家,如果你能告诉我在这里我错过了什么,甚至可以告诉我应该怎样做才能让它发挥作用我会非常感激!提前谢谢!

如果需要,我很乐意提供任何其他信息。

P.S。现在两个晚上都没有睡过,所以我可能会以一种非常愚蠢的方式搞砸了。如果有人可以测试这个代码是否有效,并告诉我他们的项目设置,它可能会有帮助。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用此库https://exceldna.codeplex.com,它可以简化UDF的创建。