Skip to content

Instantly share code, notes, and snippets.

@leosoto
Last active June 11, 2020 21:29
Show Gist options
  • Save leosoto/d3a4fdd7e6f2e61bc5c94aebc6ab4816 to your computer and use it in GitHub Desktop.
Save leosoto/d3a4fdd7e6f2e61bc5c94aebc6ab4816 to your computer and use it in GitHub Desktop.
// Script for Google Spreadsheet
//
// Counts the number of cells inside countRange (string)
// which have the same color as the cell pointed out by
// colorRef (also as string). If a cell is merged then
// they are counted as mergeWeight cells instead of 1.
function COUNTCOLOR(countRange,colorRef,mergeWeight,_) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var range = activeSheet.getRange(countRange);
var colorCell = activeSheet.getRange(colorRef);
var color = colorCell.getBackground();
var count = 0;
for(var row = 1; row <= range.getNumRows(); row++) {
for(var column = 1; column <= range.getNumColumns(); column++) {
cell = range.getCell(row, column)
if (cell.getBackground() == color) {
count += (cell.isPartOfMerge() ? mergeWeight : 1)
}
}
}
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment