【发布时间】:2014-01-08 19:37:47
【问题描述】:
我正在尝试在 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] AND [ComUnregisterFunctionAttribute] 如代码所示
- regasm /codebase 什么也没做
- 打开/关闭“注册 COM 互操作”(VS 在构建时以管理员身份运行)
- [程序集:ComVisible(true)] 设置为 true
- 尝试了来自网络的不同代码示例
- 在 stackoverflow 上阅读此内容:How to get COM Server for Excel written in VB.NET installed and registered in Automation Servers list?
- 我还尝试了以上所有方法 - 这里没有运气
- 在管理员模式下运行 Excel
所以请大家,如果你能告诉我我在这里缺少什么,甚至可以告诉我应该怎么做才能让它工作,我将非常感激!提前致谢!
如果需要,我很乐意提供任何其他信息。
附:现在已经有两个晚上没有睡觉了,所以我可能会以一种非常愚蠢的方式搞砸一些事情。如果有人可以测试此代码是否有效并告诉我他们的项目设置,它可能会有所帮助。
【问题讨论】:
-
远射,你试过在管理员模式下运行 excel 吗?
-
我忘了说我做了。所以是的,但无济于事。
-
codeproject.com/Articles/7753/… 似乎解决了您的问题,希望对您有所帮助!
-
@JuStDaN 谢谢,但我问题中的代码示例正是针对该页面的,我已经尝试了他们的解决方案。
-
@Janisimo,你为 AnyCPU 平台编译你的程序集吗?
标签: c# excel user-defined-functions