custom apps script not returning values correctly when used inside other formulas

624 views
Skip to first unread message

Aavery Mundt

unread,
Mar 30, 2022, 9:59:01 AM3/30/22
to Google Apps Script Community
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. 


Clark Lind

unread,
Mar 31, 2022, 9:02:58 AM3/31/22
to Google Apps Script Community
You are passing the range to the function as "countRange", but you never use it anywhere. Nor do you use the colorRef passed in. It may work some times simply because whatever the current active range happens to be on the sheet has colored cells.
I'm guessing you mean to do something like this??
var activeRange = countRange;
var activeformula = colorRef; 

Clark Lind

unread,
Mar 31, 2022, 9:04:40 AM3/31/22
to Google Apps Script Community
or rather,
var activeRange = countRange;
var activeformula = colorRef.getFormula()  ; 

Aavery Mundt

unread,
Apr 1, 2022, 11:44:30 AM4/1/22
to Google Apps Script Community
Thank you very much I'll test as soon as I can and get back to you with results. 
Reply all
Reply to author
Forward
0 new messages