Generate a flat list of all excel cell formulas

前端 未结 5 1063
离开以前
离开以前 2021-01-06 14:10

I have a massive program written with VBA and cell formulas. I am tasked to reverse engineer it into C# winforms. I figured for a start, I need to see all the cell formulas

5条回答
  •  失恋的感觉
    2021-01-06 14:49

    With help from brettdj, I managed to whip up a quad tree search at the moment

    private static void FindFormula(Excel excel, TextWriter writer, int rowstart, int rowend, int colstart, int colend)
    {
        // Select the range
        excel.Range(rowstart, rowend, colstart, colend);
    
        // Check whether this range has formulas
        if (!excel.RangeHasFormula())
            return;
    
        // Check if we only have a single cell
        if (excel.RangeCellCount() == 1)
        {
            Console.WriteLine(excel.CellFormula(rowstart, colstart));
            return;
        }
    
        int r1, r2, r3, r4;
        int c1, c2, c3, c4;
    
        r1 = rowstart;
        r2 = rowstart + (rowend - rowstart + 1) / 2 - 1;
        r3 = r2 + 1;
        r4 = rowend;
    
        if (colstart == colend)
        {
            c1 = c2 = c3 = c4 = colstart;
    
            FindFormula(excel, writer, r1, r2, c1, c2);
            FindFormula(excel, writer, r3, r4, c1, c2);
        }
        else
        {
            c1 = colstart;
            c2 = colstart + (colend - colstart + 1) / 2 - 1;
            c3 = c2 + 1;
            c4 = colend;
    
            FindFormula(excel, writer, r1, r2, c1, c2);
            FindFormula(excel, writer, r1, r2, c3, c4);
            FindFormula(excel, writer, r3, r4, c1, c2);
            FindFormula(excel, writer, r3, r4, c3, c4);
        }
    }
    

提交回复
热议问题