I modified your code and it will count multiple colors on the Active Range
or Highlighted Cells
based on the code given.
function countColoredCells() {
const activeRange = SpreadsheetApp.getActiveRange();
const activeSheet = activeRange.getSheet();
const formula = activeRange.getA1Notation()
const range = activeSheet.getRange(formula);
const bg = range.getBackgrounds();
let count = {};
for (let i = 0; i < bg.length; i++) {
bg[i].forEach(x => {
const findObject = Object.keys(count).find((y) => { return y == x });
count[x] = findObject ? count[x] + 1 : 1;
})
}
console.log(count);
return count
}
Sample Colored Cells:
Note: Image is for visibility only.
Sample Output:
{ '#00ffff': 3,
'#0000ff': 4,
'#ff0000': 7,
'#ffff00': 6,
'#00ff00': 1 }
Reference: