# ConditionalFormatRule

{% tabs %}
{% tab title="🔴 主題" %}

* [sheet.appendconditionalformatrule](https://lochiwei.gitbook.io/web/appendix/gas/app/prototypes/app.sheet.prototype/sheet.appendconditionalformatrule "mention")
  {% endtab %}

{% tab title="💈範例" %}

```javascript
// cells in A1:B3 will turn red if 1 <= value <= 10
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:B3");

var rule = SpreadsheetApp
    .newConditionalFormatRule()    // ⭐️ ConditionalFormatRuleBuilder
    .whenNumberBetween(1, 10)      // - 🔸 condition
    .setBackground("#FF0000")      // - 🔸 formats
    .setRanges([range])            // - 🔸 ranges
    .build();                      // ⭐️ ConditionalFormatRule
    
// append new rule to existing rules (instead of overwriting it)
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
```

{% endtab %}

{% tab title="🧨 雷區" %}
{% hint style="danger" %}
⭐️ 注意：

當使用 [whenNumberBetween(start, end)](https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder#whenNumberBetween\(Number,Number\)), [whenNumberEqualTo(number)](https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder#whenNumberEqualTo\(Number\)) ... 等這些與<mark style="color:yellow;">**數字相關**</mark>的條件時，<mark style="color:yellow;">**儲存格的值**</mark>必須是「[<mark style="color:red;">**數字格式**</mark>](https://lochiwei.gitbook.io/web/appendix/gas/classes/range/number-format)」才行，否則前面設的那些條件<mark style="color:red;">**都沒有用**</mark>❗️
{% endhint %}
{% endtab %}

{% tab title="📘 手冊" %}

* [ConditionalFormatRule](https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule)
* [ConditionalFormatRuleBuilder](https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder) ⭐️
* SpreadsheetApp ⟩&#x20;
  * [newConditionalFormatRule()](https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#newconditionalformatrule) - returns [ConditionalFormatRuleBuilder](https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder)
    {% endtab %}

{% tab title="👥 相關" %}

* [number-format](https://lochiwei.gitbook.io/web/appendix/gas/classes/range/number-format "mention") - 使用條件時，要注意儲存格「[值的格式](https://lochiwei.gitbook.io/web/appendix/gas/classes/range/number-format)」。
  {% endtab %}
  {% endtabs %}
