2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[GAS][スプレッドシート]指定した背景色のセルの合計を計算する

Last updated at Posted at 2020-03-25

参考にしたソース

しゃのんあどべんとかれんだー 2日目 (忘年会幹事のちょっとしたお悩みをちょっと解決してくれるかもしれない GAS)

スクリプトエディタを開く

image.png

スクリプトを書く

// 指定範囲のセル背景色に合致するセルの合計数を返します
// color: 背景色    rangeSpecification: 範囲指定文字列
function countCellsWithBackgroundColor(color, rangeSpecification) {
  
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(rangeSpecification);
  
  var x = 0;
  var i = 0;
  var j = 0;
  var cell;
  for (i = 1; i <= range.getNumRows(); i++) {
    for (j = 1; j <= range.getNumColumns(); j++) {
      
      cell = range.getCell(i, j);
      
      if(cell.getBackgroundColor() == color)
        if (+cell.getValue())
          x += cell.getValue();
    }
  }
  
  return x;
}

// 指定範囲のセル背景色に合致するセルの合計数を返します
// color: 背景色    rangeSpecification: 範囲指定文字列
function countCellsWithoutBackgroundColor(color, rangeSpecification) {
  
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(rangeSpecification);
  
  var x = 0;
  var i = 0;
  var j = 0;
  var cell;
  for (i = 1; i <= range.getNumRows(); i++) {
    for (j = 1; j <= range.getNumColumns(); j++) {
      
      cell = range.getCell(i, j);
      
      if(cell.getBackgroundColor() != color)
        if (+cell.getValue())
          x += cell.getValue();
    }
  }
  
  return x;
}

// 指定セルの背景色を取得します。
function getBackgroundColor(rangeSpecification) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  return sheet.getRange(rangeSpecification).getBackgroundColor();
}

セルに関数を設定

参考元のサイトには一色のケースしか載っていなかったのと、
セルの指定が文字列のため、オートフィルが難しかったり行列の削除でずれたりするため、改良しました。

image.png

例えば複数の色を合計する必要がある場合、ホワイトリスト(加算)の場合は以下のようにします。

=countCellsWithBackgroundColor(getBackgroundColor(CELL("address", $A$1)), CELL("address", C2)&":"&CELL("address", C13))
+countCellsWithBackgroundColor(getBackgroundColor(CELL("address", $A$2)), CELL("address", C2)&":"&CELL("address", C13))

ブラックリストの場合は以下のようにします。

=SUM(C2:C13)-countCellsWithBackgroundColor(getBackgroundColor(CELL("address", $A$3)), CELL("address", C2)&":"&CELL("address", C13))
2
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?