Skip to main content
 首页 » 编程设计

c#之如何使用 ExcelDNA 从范围中获取 Excel 公式

2024年02月20日11emanlee

我想将一个范围(此时为 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; 
}