是否可以选择条件格式为真的所有单元格?

时间:2017-02-06 13:44:52

标签: c# excel vsto

如果任何单元格的条件格式为true,我想检查excel工作表。我有多种格式来格式化不同颜色的单元格,但我只是希望能够看到是否有任何条件是真的(不关心哪种情况)。这个例子不起作用,但我想知道我是否在正确的轨道上,甚至可能做我要问的事情。

var lastCell = Globals.ThisAddIn.Application.ActiveCell.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
var firstCell = ((Worksheet)Globals.ThisAddIn.Application.ActiveSheet).Cells[2,1];
var range = ((Worksheet)Globals.ThisAddIn.Application.ActiveSheet).Range[firstCell, lastCell]
var r = range.SpecialCells(XlCellType.xlCellTypeAllFormatConditions, true);

1 个答案:

答案 0 :(得分:0)

由于范围的FormatConditions集合适用于整个范围,因此我不相信有一种机制可以确定范围内每个单元格的值。我认为你最好的选择是测试感兴趣的细胞中的Formula我确定这不是你想听到的

使用this answer获取使用范围。当然,将xlWorkSheet替换为((Worksheet)Globals.ThisAddIn.Application.ActiveSheet)

然后,假设您将其设置为range,循环遍历范围...

for (int r = 1; r <= range.Rows.Count; r++)
{
    for (int c = 1; c <= range.Columns.Count; c++)
    {

...暂时替换公式/值(前言:我几乎保证此代码不起作用)......

        string formula = range[r, c].Formula; //or Value, check HasFormula
        for (int i = 1; i <= range.FormatConditions.Count; i++)
        {
            range[r, c].Formula = range.FormatConditions[i].Formula1; // or Formula2 (?)
        }
        bool condition = range[r, c].Value;
        // do work based on the condition

        range[r, c].Formula = formula;

...并关闭循环。

    }
}