为了拥有允许传入一个 Excel-DNA 函数unknown运行时参数的数量,您需要使用params object[]
在你的函数参数中。
public static class MyFunctions
{
[ExcelFunction]
public static object Hello(params object[] values)
{
return "Hello " + DateTime.Now;
}
}
那么,如果您使用硬编码值调用它并不重要,例如=Hello(10, 20)
或者如果您使用单元格引用,例如=Hello(A1,A5,A10)
.
但是,Excel-DNA 不支持开箱即用的参数数量可变,因此您必须使用ExcelDna.Registration https://github.com/Excel-DNA/Registration帮助程序库以注册您的函数。
安装ExcelDna.注册NuGet包 https://www.nuget.org/packages/ExcelDna.Registration/,然后在你的里面.dna
文件,标记要使用的加载项程序集引用ExplicitRegistration
e.g.:
<?xml version="1.0" encoding="utf-8"?>
<DnaLibrary Name="My Add-In" (...)>
<ExternalLibrary Path="MyAddIn.dll" ExplicitRegistration="true" (...) />
</DnaLibrary>
然后,在你的AutoOpen
,您可以使用以下函数注册函数ProcessParamsRegistrations
打电话...例如
public class AddIn : IExcelAddIn
{
public void AutoOpen()
{
ExcelRegistration
.GetExcelFunctions()
.ProcessParamsRegistrations()
.RegisterFunctions();
// ...
}
public void AutoClose()
{
// ...
}
}
函数的隐式与显式注册
默认情况下,Excel-DNA 搜索每个public static
程序集中的方法,并将它们注册为 Excel 的函数。这就是implicit注册过程。
ExplicitRegistration="true"
turns off隐式注册,因此没有任何内容会自动注册 - 你必须自己做 - 这就是我在AutoOpen
上面与... RegisterFunctions()
call. 如果你不关闭implicit注册,然后函数最终被注册两次(一次通过隐式过程,然后再次通过您的代码)你会收到错误消息