Getting Cells with Formulas in Excel file

拟墨画扇 提交于 2019-12-11 02:54:01

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/29507584/getting-cells-with-formulas-in-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!