LoginSignup
2
3

More than 1 year has passed since last update.

【スプレッドシート】隣のセルより大きかったら色を染める(条件付き書式・GAS)

Last updated at Posted at 2022-04-10

概要

スプレッドシートで隣のセルと比較して大きければ色付けする方法を記載します。
私は企業の毎年の利益などを比較するために使っています。

○イメージ(前の年より利益が上がっていればセルの色を染める)
image.png

##まずは手動で設定

①設定したい範囲を選択
image.png

②「表示形式」⇨「条件付き書式」
image.png

③右端に表示される条件付書式ルールで「書式ルール」を「カスタム書式」
「=R3<S3」と入力。色の指定などをする
※カスタム書式に入れる式は一つだけでOK。私は1番左上のセルを設定しました

image.png

GASで実行する場合

先ほどの処理をGASでやる場合は以下のようにする
※マクロで記録した後に余分なコードを削除しました
変数などを使用して適用する範囲などを変えれば汎用性が持てる

const spreadsheet = SpreadsheetApp.openById("スプレッドシートのID");
const sheet = spreadsheet.getSheetByName("シート名");

function test(){
  var conditionalFormatRules = sheet.getConditionalFormatRules();
  conditionalFormatRules.splice(conditionalFormatRules.length - 1, 1, SpreadsheetApp.newConditionalFormatRule()
  .setRanges([sheet.getRange('S3:U4')])
  .whenFormulaSatisfied('=R3<S3')
  .setBackground('#B7E1CD')
  .build());
  sheet.setConditionalFormatRules(conditionalFormatRules);
}

追記

初めに条件付書式を初期化したい場合はこのようにする

var conditionalFormatRules = industrySheet.getConditionalFormatRules();
//条件付書式の状態を配列で取得して、配列の長さ分削除(要素の削除)
  conditionalFormatRules.splice(0, conditionalFormatRules.length);
2
3
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
2
3