Skip to content

Instantly share code, notes, and snippets.

@marcup
Last active February 13, 2019 11:40
Show Gist options
  • Save marcup/e4aaa3f054afd7c942d1a51201c2424e to your computer and use it in GitHub Desktop.
Save marcup/e4aaa3f054afd7c942d1a51201c2424e to your computer and use it in GitHub Desktop.
Google Docs Script to count number of cells in a sheet that don't match with a specified background colour
/**
* @param {range} countRange Range to be evaluated
* @param {range} colorRef Cell without background color to be searched for in countRange
* @return {number}
* @customfunction
*/
function countNonMatchingColoredCells(countRange,colorRef) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formula = activeRange.getFormula();
var rangeA1Notation = formula.match(/\((.*)\,/).pop();
var range = activeSheet.getRange(rangeA1Notation);
var bg = range.getBackgrounds();
var values = range.getValues();
var colorCellA1Notation = formula.match(/\,(.*)\)/).pop();
var colorCell = activeSheet.getRange(colorCellA1Notation);
var color = colorCell.getBackground();
var count = 0;
for(var i=0;i<bg.length;i++)
for(var j=0;j<bg[0].length;j++)
if( bg[i][j] != color && values[i][j] != "" ) {
count=count+1;
}
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment