V
V
Vilker2018-07-11 15:03:15
Google Sheets
Vilker, 2018-07-11 15:03:15

Is there a working script to sum cells of a specific color in Google Sheets?

Hello.
I really need a script to work with Google Sheets.
The crux of the matter is, there are many cells in a column of different colors. It is necessary to automate the process of counting cells, let's say red or any other.
Here is the script for this question
. I will paste the code here:

function getBackgroundColor(rangeSpecification) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  return sheet.getRange(rangeSpecification).getBackgroundColor();
}

function sumWhereBackgroundColorIs(color, rangeSpecification) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(rangeSpecification);
  var x = 0;
  for (var i = 1; i <= range.getNumRows(); i++) {
    for (var j = 1; j <= range.getNumColumns(); j++) {
      var cell = range.getCell(i, j);
      if(cell.getBackgroundColor() == color)
        x += parseFloat(cell.getValue());
    }
  }
  return x;
}

function countCellsWithBackgroundColor(color, rangeSpecification) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(rangeSpecification);
  var x = 0;
  for (var i = 1; i <= range.getNumRows(); i++) {
    for (var j = 1; j <= range.getNumColumns(); j++) {
      var cell = range.getCell(i, j);
      if(cell.getBackgroundColor() == color)
        x++;
    }
  }
  return x;
}

There are three commands
1) =countCellsWithBackgroundColor("white", "B2:F13")
2) =sumWhereBackgroundColorIs("white", "B2:F13")
3) =getBackgroundColor("B9")
Only the third option works, the first and second no. How can this be done or is there another way?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2018-08-11
@Iv_and_S

https://toster.ru/q/484012?e=6098875#answer_item_1...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question