在 Application.Evaluate 中使用多个 UDF 函数

Using multiple UDF functions in Application.Evaluate

我用 C# 构建了 Excel-Dna Addin。在某些情况下,我需要 运行 几个 UDF 函数。 我的单元格包含具有不同参数的 UDF,我在这里显示简化版本。

我正在为此使用 Application.Evaluate 函数。

我的 UDF:

[ExcelFunction(Name = "Test.TestMe", Description = "Some test", IsHidden = false)]
public static int TestMe(int i)
{
    return i + 1;
}

如果我调用 Application.Evaluate("=Test.TestMe(1)") 我得到结果 2.

如果我尝试以下操作:Application.Evaluate("=Test.TestMe(1)+Test.TestMe(2)") none 我的 UDF 函数未被调用。

求值函数returns:-2146826259 = #Name?

我试过以下方法:

  1. 在函数名称 "Test.TestMe(1)+Test.TestMe(2)"
  2. 之前删除了 =
  3. 以完全限定名称调用。 "myexcel.xlsx!Test.TestMe(1)+Test.TestMe(2)"
  4. 我知道 Application.Evaluate 限制为 255 个字符。

我想避免逐一解析公式和调用我的 UDF。

有什么想法吗?

Charles Williams (https://fastexcel.wordpress.com/2011/11/02/evaluate-functions-and-formulas-fun-how-to-make-excels-evaluate-method-twice-as-fast/) 在描述此限制时指出了一篇(现已丢失)知识库文章:

If the string formula contains a reference to both a UDF and a name it will fail with an error 2029 if the name reference occurs AFTER the UDF reference:

  • If fred is a named range and xyz() is a user defined VBA function then this statement returns error 2029 [i.e. #NAME?]: Application.Evaluate("=xyz(b1)+fred")
  • This statement returns the correct value: Application.Evaluate("=fred+xyz(b1)")
  • Microsoft KB article 823604 [which I couldn't find] identifies this problem but does not correctly diagnose the circumstances that cause it.

由于您的 UDF 名称也是 Excel 中的 'name',它可能受到相同的怪癖,给您这个 #NAME? 错误。

所以我认为您 运行 陷入了一个长期存在的 Excel 怪癖,您可能想通过 文件 -> 反馈 -> 向 Microsoft 报告此问题'Send a Frown' 按钮。