Skip to content

Instantly share code, notes, and snippets.

@jeffdgr8
Forked from clupasq/subByColor.js
Last active December 15, 2018 22:25
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jeffdgr8/1553faa6360ad04e9c17 to your computer and use it in GitHub Desktop.
Save jeffdgr8/1553faa6360ad04e9c17 to your computer and use it in GitHub Desktop.
function getBackgroundColor(rangeSpecification) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
return sheet.getRange(rangeSpecification).getBackground();
}
function getForegroundColor(rangeSpecification) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
return sheet.getRange(rangeSpecification).getFontColor();
}
function sumWhereBackgroundColorIs(color, rangeSpecification) {
var condition = function (cell) { return cell.getBackground() == color; };
return sumByCondition(color, rangeSpecification, condition);
}
function sumWhereBackgroundColorIsNot(color, rangeSpecification) {
var condition = function (cell) { return cell.getBackground() != color; };
return sumByCondition(color, rangeSpecification, condition);
}
function sumWhereForegroundColorIs(color, rangeSpecification) {
var condition = function (cell) { return cell.getFontColor() == color; };
return sumByCondition(color, rangeSpecification, condition);
}
function sumWhereForegroundColorIsNot(color, rangeSpecification) {
var condition = function (cell) { return cell.getFontColor() != color; };
return sumByCondition(color, rangeSpecification, condition);
}
function sumByCondition(color, rangeSpecification, condition) {
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(condition(cell)) {
var cellVal = parseFloat(cell.getValue());
if (isFinite(cellVal))
x += cellVal;
}
}
}
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment