簡體   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