Excel 函数在代码后面设置时抛出异常。在 excel 中使用时有效

Excel function throws exception when set by code behind. Works when used in excel

我定义了自己的 Excel 函数(称为 ADXExcelFunctionDeescriptor)。方法存根如下所示:

public static object ExecuteMyFunction(object values, object tagName)
{ // Some code here }

该方法接收一个双精度值数组和一个名为 name 的字符串。
在设计视图中,我的 ADXExcelFunctionDeescriptor 如下所示:

我通过以下代码行调用和设置函数:

var formula = string.Format(@"={0}({1};{2})", Temp.FORMULA_NAME, this.DataRangeTextBox.Text, tagCaption);
resultRange.set_Value(Type.Missing, formula);
resultRange.Formula = resultRange.Value;

这将导致异常!异常如下所示:

System.Runtime.InteropServices.COMException occurred
  HResult=-2146827284
  Message=Ausnahme von HRESULT: 0x800A03EC
  Source=""
  ErrorCode=-2146827284
  StackTrace:
       bei System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       bei Microsoft.Office.Interop.Excel.Range.set_Value(Object RangeValueDataType, Object )
       bei bb.ExcelToolbar.Controls.bbControl.ApplyFormula(Object sender, EventArgs e) in c:\xx\yy\zz\bb\bb.ExcelToolbar\Controls\bbControlcs:Zeile 88.
  InnerException: 

此外,如果我不将 tagName 参数传递给函数 returns,结果将不会出现任何异常或错误。

var formula = string.Format(@"={0}({1})", Temp.FORMULA_NAME, this.DataRangeTextBox.Text, tagCaption);
resultRange.set_Value(Type.Missing, formula);
resultRange.Formula = resultRange.Value;

所以我觉得跟字符串参数有关系。 我还尝试用 " 或 ' 字符包围字符串参数,但到目前为止没有变化。

此外,如果我将函数直接键入 Excel,它可以毫无问题地工作。因此,例如,如果我在 Excel:

中输入以下公式
=Temp.DoSomething(B2:B13;"Flow")

也许我漏掉了什么或做错了什么?

您似乎没有在构造的 UDF 字符串公式中为第二个参数 tagCaption 添加引号。该值应该有引号。

var formula = string.Format(@"={0}({1};""{2}"")",Temp.FORMULA_NAME, 
                              this.DataRangeTextBox.Text, tagCaption);

另外:请在此处查看 Chris Neilsen 的评论:Excel - Inserting formula with VBA

in VBA .Formula, .FormulaArray and .FormulaR1C1 use international seperator (ie ,) and .FormulaLocal, and .FormulaR1C1Local use the language of the user (so can use ; if that is your language setting). So for this OP assigning to .FormulaArray it is correct to say always use ,