LoginSignup
0
1

Googleスプレッドシートの条件付き書式をGAS上で全シートに設定させる

Last updated at Posted at 2024-01-01

自分用のメモ
・少し工夫すれば、特定のシートの条件を全シートにコピーできるのでしょうが、時間なくてできない
・copyAndOverrideConditionalFormats側に、シート名を指定し、sheet.getConditionalFormatRules();してパラメータで渡すことができれば、特定シートの条件を全シートのコピーが可能となる

GAS
// 概要
// 指定したシートの全条件付き書式を、ほかの全シートに上書きコピーする関数
function copyAndOverrideConditionalFormats() {
  format = '=$A1:$A800="#"';
  insertFormulaToAllSheets_(format);

  format = '=OR(isnumber(A1:A800),(A1:A800<>""))';
  insertFormulaToAllSheets_(format);
}

/**
 * 全シートに対して、指定した条件付き書式を上書きして挿入する
 * @param {string} 条件付き書式
 */
function insertFormulaToAllSheets_(format) {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = spreadsheet.getSheets();

  sheets.forEach(function (sheet) {
    const activeRange = sheet.getDataRange();
    const existingRules = sheet.getConditionalFormatRules(); // 既存の条件付き書式を取得

    // 新しい条件付き書式を追加
    if (format === '=$A1:$A800="#"') {
      newRule = SpreadsheetApp.newConditionalFormatRule()
        .whenFormulaSatisfied(format)
        .setBackground('#cfe2f3') // 背景色を水色にする
        .setRanges([sheet.getRange('A1:AF800')])
        .build(); // 条件を確定
    } else if (format === '=OR(isnumber(A1:A800),(A1:A800<>""))') {
      newRule = SpreadsheetApp.newConditionalFormatRule()
        .whenFormulaSatisfied(format)
        .setBackground('#cfe2f3') // 背景色を水色にする
        .setRanges([sheet.getRange('A1:A800')])
        .build(); // 条件を確定
    }

    // 既存の条件付き書式に新しい条件付き書式を追加
    existingRules.push(newRule);
    
    // 修正された条件付き書式をシートに再設定
    sheet.setConditionalFormatRules(existingRules);
  });
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1