繁体   English   中英

如何使用ExcelDNA从范围中获取Excel公式?

[英]how do you get Excel formulas from a range using ExcelDNA?

我想将一个范围(此时为1d)传递给我的函数,并返回一个包含范围公式的字符串数组。

到目前为止,这是我的(不工作)代码:

    public static object[,] ReadFormulas([ExcelArgument(AllowReference=true)]object arg)
    {
        ExcelReference theRef = (ExcelReference)arg;
        object[,] o = (object[,])theRef.GetValue();
        string[,] res = new string[o.GetLength(1),1];
        for(int i=0;i<o.GetLength(1);i++) 
        {
            ExcelReference cellRef = new ExcelReference(theRef.RowFirst+i, theRef.ColumnFirst);
            res[i,0] = XlCall.Excel(XlCall.xlfGetFormula, cellRef) as string;   //Errors here
        }
        return res;
    }

仅在宏表上允许使用GET.FORMULA(xlfGetFormula)函数。 要从工作表中调用它,您的Excel-DNA函数应标记为IsMacroType=true ,如下所示:

[ExcelFunction(IsMacroType=true)]
public static object[,] ReadFormulas(
        [ExcelArgument(AllowReference=true)]object arg) {...}

此外,在循环中构造新的ExcelReference时需要小心。 默认情况下,引用中引用的工作表将是当前工作表,而不是传入引用的工作表。 您应该明确地将SheetId传递给新的ExcelReference。 你的索引也有一些有趣的东西 - 也许o.GetLength(1)不是你想要的。

以下版本似乎有效:

[ExcelFunction(IsMacroType=true)]
public static object[,] ReadFormulasMacroType(
        [ExcelArgument(AllowReference=true)]object arg)
{
    ExcelReference theRef = (ExcelReference)arg;
    int rows = theRef.RowLast - theRef.RowFirst + 1;
    object[,] res = new object[rows, 1];
    for(int i=0; i < rows; i++) 
    {
        ExcelReference cellRef = new ExcelReference( 
            theRef.RowFirst+i, theRef.RowFirst+i, 
            theRef.ColumnFirst,theRef.ColumnFirst,
            theRef.SheetId );
        res[i,0] = XlCall.Excel(XlCall.xlfGetFormula, cellRef);
    }
    return res;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM