Count the cells with same color in google spreadsheet

后端 未结 5 462
夕颜
夕颜 2021-01-03 21:15

I\'m trying count the number of cells with the same background color and put the result in other cell with a script in google apps script, but I can\'t do it. I have the nex

5条回答
  •  粉色の甜心
    2021-01-03 21:39

    The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells. You can find a detailed description here: Google Script count coloured with reference, but the code is below:

    function countColoured(reference) {
      var sheet = SpreadsheetApp.getActiveSheet();
      var formula = SpreadsheetApp.getActiveRange().getFormula();
      var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
      try {
        if (args.length == 1) {
          var range = sheet.getRange(args[0]);
        }
        else {
          sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
          range = sheet.getRange(args[1]);
        }
      }
      catch(e) {
        throw new Error(args.join('!') + ' is not a valid range');
      }
      var c = 0;
      var numRows = range.getNumRows();
      var numCols = range.getNumColumns();
      for (var i = 1; i <= numRows; i++) {
        for (var j = 1; j <= numCols; j++) {
          c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
        }
      }
      return c > 0 ? c : "" ;
    }
    

提交回复
热议问题