This code works to count colored cells when using a reference cell. When embedding this into an if or countifs statement I often but not always get a range not found error. Usually the first time after opening the document it will work properly for example.
if(countcolored(c131:j133,d146)>0,"1","0") should return a value of 1
/**
* counts colored cells.
*
* @param {range, cell} looks at the range and compares its color.
* @return A count of all the cells with that color
* @customfunction
*/
function COUNTCOLORED(countRange,colorRef) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var activeformula = activeRange.getFormula();
var rangelocation = activeformula.match(/\((.*)\,/).pop();
var range = activeSheet.getRange(rangelocation);
var bg = range.getBackgrounds();
var values = range.getValues();
var colorCellLocation = activeformula.match(/\,(.*)\)/).pop();
var colorCell = activeSheet.getRange(colorCellLocation);
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 )
count=count+1;
return count;
}
The error that I am getting is error range not found line 13 which I assume is in reference to line 13 of my script, I'm not sure why it isn't getting the range though.
The goal is to count a row of any of the cells in the range contain a certain color, the range isn't huge it's from c5 to j200. This is a fairly simple operation in excel but we're using a shared live document on sheets. Any assistance would be appreciated. I'm relatively new to scripting in sheets.