如何在ExcelDNA XLL UDF中处理Excel数组公式
我真的很难理解如何让我的UDF作为数组公式input。 我已经通过各种职位看了答案,但我认为我的理解必须有一个差距。
以ExcelDNA教程 double MultiplyThem(double x,double y)为例进行说明。
如果我select一个单元格范围,并input{= MultiplyThem({1; 2; 3; 4},5)}作为数组公式,我期望看到填充的选定列范围
5 10 15 20
不过,我得到的全是5秒。 此外,如果我的目标范围大于可用值的数量,我期望看到#N / A值,但是我再次看到值5。
我该如何处理数组公式? 我是否需要UDF重载,返回一个double [,],还是有一些内置的Excelfunction,将重复调用我的UDF与适当的数组值。
Excel UDF可以将数组作为input,并将数组作为结果返回,但这必须明确地完成。 不支持自动扩展标量函数来处理数组。
如果您将MultiplyThem
函数的签名更改为
public static object MuliplyThem(object x, object y) {…}
当你的函数调用{=MultiplyThem({1,2,3,4},5)}
时,你的函数将会得到完整的数组。
然后您需要在函数中添加一个types检查,以确保正确处理不同的选项。 (当你声明参数为'double'时,Excel将尝试转换input,如果不兼容则返回#VALUE
,这里你必须处理types检查和转换。
所有可以获得的“对象”参数的值的详尽例子如下所示:
[ExcelFunction(Description="Describes the value passed to the function.")] public static string Describe(object arg) { if (arg is double) return "Double: " + (double)arg; else if (arg is string) return "String: " + (string)arg; else if (arg is bool) return "Boolean: " + (bool)arg; else if (arg is ExcelError) return "ExcelError: " + arg.ToString(); else if (arg is object[,]) // The object array returned here may contain a mixture of different types, // reflecting the different cell contents. return string.Format("Array[{0},{1}]", ((object[,])arg).GetLength(0), ((object[,])arg).GetLength(1)); else if (arg is ExcelMissing) return "<<Missing>>"; // Would have been System.Reflection.Missing in previous versions of ExcelDna else if (arg is ExcelEmpty) return "<<Empty>>"; // Would have been null else return "!? Unheard Of ?!"; }
在你的情况下,你会以一种特殊的方式处理object[,]
数组,并在适当时返回一个double[,]
数组或object[,]
数组。 它的input不是你可以处理的types,你可以返回一个错误,很可能是ExcelError.ExcelErrorValue
。