【问题标题】:Google Apps Script: How to get the conditional format rules in a sheet, including the values for each ruleGoogle Apps 脚本:如何在工作表中获取条件格式规则,包括每个规则的值
【发布时间】:2026-02-03 14:45:01
【问题描述】:

我似乎无法弄清楚如何获取工作表中的所有条件格式,尤其是获取在条件内设置的值。

我有一张包含数量列的表格。每个数量都有一个唯一的条件格式值集,因此如果单元格中的数量值低于此阈值(设置在条件格式内),则单元格的背景变为红色。

这一切都很好。

问题是我需要通过条件格式访问为每个单元格设置的唯一阈值。

我尝试了许多不同的变体 var rules = sheet.getConditionalFormatRules() 等然后循环通过这些规则只得到奇怪的Logger.log 结果,看起来像这样:

com.google.apps.maestro.server.beans.trix.impl.ConditionalFormatRuleApiAdapter@17521c6a

完全按照以下文档进行操作,但也失败了:

https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule#getBooleanCondition()

https://developers.google.com/apps-script/reference/spreadsheet/boolean-condition

【问题讨论】:

  • 其他列有条件格式吗?
  • 嗨,谢谢您的回复,不,我不知道。只有一列

标签: google-apps-script google-sheets gs-conditional-formatting


【解决方案1】:

编辑:我知道该行是您的日志结果...

看起来像这样是因为它是一个对象,当您尝试在没有 A1Notation() 的情况下记录范围时,它也会这样做。这只是意味着您没有使用返回数组或值的方法。

按照您链接的文档,getCriteriaValues() method 应该可以满足您的需求。像这样为我工作:

function findThresholds() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();;
  var formats = sheet.getConditionalFormatRules();
  var thresholds = [];
  formats.forEach(function(format, i) {
    var booleanCondition = format.getBooleanCondition();
    if (booleanCondition) {
      var threshold = booleanCondition.getCriteriaValues();
      thresholds.push(threshold[0]) //if you have more than one value per contional format, omit [0]
    }
  });
  return thresholds

这会将它们推送到一个数组中,但您也可以直接对它们做一些事情。

编辑2:因为知道阈值在哪一行是相关的: 对于每种格式,您都可以使用 .getRanges() 方法。然后,在每个范围上,您将使用 .getRow() 了解该范围从哪一行开始。如果该范围超过一行高,您将需要 getValues(),以便能够通过将行的索引值添加到您之前获得的起始行来计算每一行。最后,您可以将该值作为键推送,并将阈值作为 dict 中的值推送,您将能够调用该行来获取您的阈值。

function findThresholds() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(<sheet name>);
  var formats = sheet.getConditionalFormatRules();
  var thresholds = {};
  formats.forEach(function(format) {
    var booleanCondition = format.getBooleanCondition();
    var ranges = format.getRanges();
    if (booleanCondition) {
      var threshold = booleanCondition.getCriteriaValues();
      ranges.forEach(function(range) {
        var rowStart = range.getRow();
        var rows = [];
        var vals = range.getValues(); //if every format only apply to one row, you may omit this part and just use 'rowStart' as 'row'
        for(var i = 0; i < vals.length; i++){
          var row = (rowStart+i);
          thresholds[row] = threshold[0]
        }
      });
    }
  });
  return thresholds
}

【讨论】:

  • 这行得通!但是我遇到了一个奇怪的问题,我看到了阈值,但是它们超出了预期的顺序?就好像阈值可能是我最初创建它们的顺序(我不认为我从工作表上的第 1 行开始一个一个地创建它们),而不是电子表格的顺序(即第 1 行有条件阈值将是数组中的第一个阈值等)。
  • 是的,我确实认为它们是按这个顺序排列的。但是,如果你有条件,我正在检查如何获得它。在多列中格式化,您实际上可以获得条件格式的范围,因此您可以将行索引与阈值推送到字典或其他东西中,然后能够逐行获取它们。每一行都有自己的还是分享他们的?
  • 列中的每个单元格都有自己的条件格式规则和自己的阈值。我还没有测试你的 findThresholds() 函数,但现在我知道你可以使用 getRanges(),我相信它会起作用!会试一试,让你知道。非常感谢!
最近更新 更多