我的目标是在运行时在ExcelDNA AddIn中动态构建和注册Excel用户定义的函数。
下面是一个例子由ExcelDNA作者提供,它突出了如何从简单的C#代码字符串编译UDF。
如您所见,这段代码是通过从AddIn的RegisterMyClass
方法中调用AutoOpen
来执行的;而且一切都很完美。
但是,如果将RegisterMyClass
方法移动到(例如)丝带按钮的操作方法中,则动态UDF的注册不起作用,并导致以下错误:
Registration [Error] xlfRegister call failed for function or command: 'MyDynamicAdd'
实际上,对ExcelIntegration.RegisterMethods
的任何调用似乎都会在上面的错误消息中失败--除非它们是从AutoOpen
方法中调用的。
我的问题是:
我如何在运行时动态注册一个新的UDF,并通过单击丝带按钮触发它呢?
为了完整性起见,引用了Gist代码:
<DnaLibrary Name="ExcelDna Test Dynamic Method" Language="C#">
<Reference Name="System.Windows.Forms" />
<![CDATA[
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.CSharp;
using ExcelDna.Integration;
public class Test : IExcelAddIn
{
// Just to test that we are loaded.
public static double MyAdd(double d1, double d2)
{
return d1 + d2;
}
public void AutoOpen()
{
RegisterMyClass();
}
public void AutoClose()
{
}
private void RegisterMyClass()
{
string code =
@"
public class Script
{
public static double MyDynamicAdd(double d1, double d2)
{
return d1 + d2;
}
}";
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
cp.TreatWarningsAsErrors = false;
cp.ReferencedAssemblies.Add("System.dll"); //, "System.Windows.Forms.dll", "ExcelDna.Integration.dll" );
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults cr = provider.CompileAssemblyFromSource(cp, new string[] { code });
if (!cr.Errors.HasErrors)
{
Assembly asm = cr.CompiledAssembly;
Type[] types = asm.GetTypes();
List<MethodInfo> methods = new List<MethodInfo>();
// Get list of MethodInfo's from assembly for each method with ExcelFunction attribute
foreach (Type type in types)
{
foreach (MethodInfo info in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
methods.Add(info);
}
}
Integration.RegisterMethods(methods);
}
else
{
MessageBox.Show("Errors during compile!");
}
}
}
]]>
</DnaLibrary>
发布于 2018-08-25 16:12:03
注册函数的代码需要在C可用的上下文中。它不会在带状回调或任何其他COM事件处理程序中工作。
切换到call可用的宏上下文的一个选项是调用ExcelAsyncUtil.QueueAsMacro
助手,并在传入的委托中运行注册代码。
https://stackoverflow.com/questions/52018596
复制相似问题