简体   繁体   中英

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

I want to pass a range (1d at this point) into my function, and return an array of strings which contain the formulas of the range.

Here's my (not working) code so far:

    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;
    }

The GET.FORMULA (xlfGetFormula) function is allowed on macro sheets only. To call it from a worksheet, your Excel-DNA function should be marked as IsMacroType=true , like this:

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

Also, you need to be a bit careful when constructing the new ExcelReference in your loop. By default, the sheet referred to in the reference will be the current sheet, and not the sheet of the passed in reference. You should probably pass the SheetId into the new ExcelReference explicitly. There's also something funny with your indexing - perhaps the o.GetLength(1) is not what you intend.

The following version seemed to work:

[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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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