如何在ExcelDNA XLL UDF中处理Excel数组公式



我真的很难理解如何允许UDF作为数组公式输入的可能性。我看了各种帖子的答案,但我想我的理解一定有差距。

使用ExcelDNA教程double MultiplyThem(double x, double y)作为示例进行演示。

如果我选择一个单元格范围并输入{=MultiplyThem({1;2;3;4},5)}作为数组公式,我希望看到所选的列范围被

填充

5101520

但是

,我得到的都是5s。此外,如果我的目标范围大于可用值的数量,我希望看到#N/A值,但我还是只看到值5。

如何处理数组公式?我是否需要UDF重载返回双精度[,],或者有一些内置的Excel功能,将重复调用我的UDF与适当的数组值。

Excel udf可以接受数组作为输入,并返回数组作为结果,但这必须显式地完成。不支持在数组上自动扩展标量函数。

如果您将MultiplyThem函数的签名更改为

public static object MuliplyThem(object x, object y) {…}

你的函数将在调用{=MultiplyThem({1,2,3,4},5)}时接收完整的数组。

然后需要在函数中添加类型检查,以确保正确处理不同的选项。(当您将参数声明为"double"时,Excel将尝试转换输入,如果不兼容则返回#VALUE。这里必须处理类型检查和转换。)

一个详尽的例子,你可以得到一个' object '参数的所有值如下所示:

[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[,]数组。如果输入不是可以处理的类型,则可以返回错误,最可能的是ExcelError.ExcelErrorValue

最新更新