Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count the number of cells with a background color in Google Sheets (Google Apps Script)
function CountFormattedCells() {
// Output the number of formatted cells somewhere in your spreadsheet
var outputNumberOfFormattedCells = 'C52'
// Cell that contains the color you want to count. Default is blank.
var cellWithFormatToCount = ''
var spreadsheet = SpreadsheetApp.getActive();
var currentRangeColors = spreadsheet.getActiveRange().getBackgrounds();
if (cellWithFormatToCount !== '') { var cellWithFormat = spreadsheet.getRange(cellWithFormatToCount).getBackground(); }
var formattedCellCount = 0
for (var i in currentRangeColors) {
for (var j in currentRangeColors[i]) {
if (currentRangeColors[i][j] !== '#ffffff' && cellWithFormatToCount == '') {
formattedCellCount++
} else if (cellWithFormatToCount !== '' && currentRangeColors[i][j] == cellWithFormat) {
formattedCellCount++
}
}
}
if (outputNumberOfFormattedCells != '') {
spreadsheet.getRange(outputNumberOfFormattedCells).setValue(formattedCellCount)
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment