c# – 制作MS Excel用户定义函数

我正在尝试在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

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

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

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

最佳答案 你可以尝试这个库
https://exceldna.codeplex.com,它简化了很多UDF的创建.

点赞