问题
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