c# - 从 C# 中拖动 excel 中的公式

标签 c# excel excel-formula

感觉这个问题很简单,就是找不到答案。

我想根据列“A”和“B”中的信息在列“C”中应用一列公式。当您编写公式,然后拖动,一直向下创建行相关公式时,我希望公式能够像在 Excel 中那样工作。

下面的方法可行,但速度很慢,因为它是分别编写每个公式的。我确信在某处有更有效的方法。

谢谢

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

最佳答案

使用 R1C1 公式,并替换:

    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\")";
    }

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

关于c# - 从 C# 中拖动 excel 中的公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6982545/

相关文章:

excel - Wix - 检测 Excel 是 32 位还是 64 位

excel - 我需要在 vba 中解释 activecell.offset

excel - Excel 的工作日错误

excel - 如何在 Excel 中复制不同的行?

c# - 为不同的 ViewModel 但相同的属性动态显示不同的 View

c# - 获取访问点列表并使用 Linux Mono/C# 进行连接

excel - 如何使用 VBA for Excel for MacOS 创建文本文件

excel - 减少字符串并保持零完整

c# - NET 4.0 SpinWait 方法与 4.0 之前的 SpinWait() 有何不同?

c# - 使用 Linq to SQL 为 objectContext 过滤查询