Google-sheets – Sum cells according to cell colour

google sheetsgoogle-apps-script

I want to sum cells only with a specific cell colour.

I'm using this code:

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; 
}

Best Answer

The problem with your code is that your using the function getBackgroundColor() which doesn't exist. Use getBackground() instead.

And make sure you're passing both range and color code as strings (enclosed with "). Also make sure to pass color codes in lower case ("#ffffff", not "#FFFFFF").