Home » excel » Drag formulas in excel from C#

Drag formulas in excel from C#

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a feeling that this question is very simple, but I just can’t find the answer.

I want to apply a column of formulas in column “C” based on information in col “A” and “B”. I want the formula to work as it would in excel when you write a formula, and then drag, creating row-relative formulas all the way down.

The method below works, but it’s very slow, since it writes each formula separately. I’m sure there’s a more efficient method out there somewhere.

Thanks

        using Excel = Microsoft.Office.Interop.Excel;

        ...


        object oOpt = System.Reflection.Missing.Value; //for optional arguments
        Excel.Application oXL = null;
        Excel.Workbook oWB = null;
        Excel.Worksheet oSheet = null;
        Excel.Range oRng = null;

        try
        {
            //Start Excel and get Application object.
            oXL = new Excel.Application();
            oXL.Visible = true;

            //Get a new workbook.
            oWB = (Excel.Workbook)(oXL.Workbooks.Add(Missing.Value));
            oSheet = (Excel.Worksheet)oWB.ActiveSheet;

            ...
            //Set numberOfRows
            //Load information to column A and B
            ...


            //Write the column of formulas
            for (int r = 2; r < numberOfRows + 2; r++)
            {
                oRng = oSheet.get_Range("C" + r, "C" + r);
                oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
            }


        }
        catch (Exception theException)
        {
            String errorMessage;
            errorMessage = "Error: ";
            errorMessage = String.Concat(errorMessage, theException.Message);
            errorMessage = String.Concat(errorMessage, " Line: ");
            errorMessage = String.Concat(errorMessage, theException.Source);

            MessageBox.Show(errorMessage, "Error");
        }
        finally
        {

            // Cleanup
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(oRng);
            Marshal.FinalReleaseComObject(oSheet);

            oWB.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(oWB);

            oXL.Quit();
            Marshal.FinalReleaseComObject(oXL);
       }
How to&Answers:

Use R1C1 formula, and replace :

    for (int r = 2; r < numberOfRows + 2; r++)
    {
        oRng = oSheet.get_Range("C" + r, "C" + r);
        oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
    }

with

    oRng = oSheet.get_Range("C2").get_Resize(100, 1);
    oRng.FormulaR1C1 = "=IF(AND(RC[-2]<> 0,RC[-1]<>2),\"YES\",\"NO\")";