D
D
Danil Samodurov2022-01-24 10:31:49
JavaScript
Danil Samodurov, 2022-01-24 10:31:49

Why is the number of colored cells in Google Sheets incorrectly counted?

Hello. I found a script on the Internet how to calculate the number of filled cells in a range of a certain color in google sheets. I create a function countColoredCells(countRange, colorRef) in Apps Script, where countRange is essentially a range in which colorRef color cells are counted:

function countColoredCells(countRange,colorRef) {
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();

  var rangeA1Notation = formula.match(/\((.*)\;/).pop().trim();
  var range = activeSheet.getRange(rangeA1Notation);
  var bg = range.getBackgrounds();
  var values = range.getValues();

  var colorCellA1Notation = formula.match(/\((.*)\;/).pop().trim();
  var colorCell = activeSheet.getRange(colorCellA1Notation);
  var color = colorCell.getBackground();

  var count = 0;

  for(var i=0;i<bg.length;i++)
    for(var j=0;j<bg[0].length;j++)
      if( bg[i][j] == color )
        count=count+1;
  return count;
};

But for some reason it's wrong. The count is based on the color that is first in the countRange, and colorRef is not used at all. How to fix the script?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grigory Boev, 2022-01-24
@samodurOFF

There is a copypasta and an error. Takes also the 1st argument, not the 2nd

var colorCellA1Notation = formula.match(/\((.*)\;/).pop().trim();

Necessary:
var colorCellA1Notation = formula.match(/\(.*?\;(.+)\)/).pop().trim();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question