简体   繁体   中英

Getting Cells with Formulas in Excel file

I am trying to read formulas of cells currently I am reading all cells in sheet which takes too much time. How can I only select those cells which have formulas.

Here is the code I am using

foreach (Excel.Worksheet workSht in xWorkBook.Worksheets)
{
    for (int rCnt = 1; rCnt <= workSht .Rows.Count; rCnt++)
    {
        for (int cCnt = 1; cCnt <= workSht .Columns.Count; cCnt++)
        {
            string str = (string)(workSht.Cells[rCnt, cCnt] as Excel.Range).Formula;
            if (str.Contains("_R*"))
            {
                if (File.Exists(excelFilePath))
                {
                    File.Delete(excelFilePath);
                }
                CloseExcelObject(ref xWorkBook, ref xApp);
                return "UnReviewedFile";
            }
        }
    }
}

In VBA you can select all the cells containing formulas with the following statement:

Sheet1.Cells.SpecialCells(xlCellTypeFormulas, 23).Select

where Sheet1 is a reference to the current sheet and xlCellTypeFormulas = -4123

That means you should be able to search through the cells with formulas with something like the following code (not tested):

foreach (Excel.Worksheet workSht in xWorkBook.Worksheets)
{
    foreach (var cell in workSht.Cells.SpecialCells(-4123, 23)) {
        // your code here
    }  
}     

keeping @Gedde's answer in view I tried to get special cells and it worked

Here's the devil...

foreach (var cell in workSht.Cells.SpecialCells(XlCellType.xlCellTypeFormulas, 23))
     {
      str = (string)(cell as Excel.Range).Formula;
     } 

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