【问题标题】:Is it possible to select all cells where a conditional format is true?是否可以选择条件格式为真的所有单元格?
【发布时间】:2017-02-06 13:44:52
【问题描述】:

如果任何单元格的条件格式为真,我想检查一个 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);

【问题讨论】:

  • 循环遍历单元格并将它们添加到列表中(如果它们符合条件)?或者尽可能使用 linq

标签: c# excel vsto


【解决方案1】:

由于范围的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;

...并关闭循环。

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多