I’m trying to re run a formula that sums all of the cells with a certain color. When I call the function, it runs correctly. After I add a another cell with the same colour it should re run and increase the number by 1. If I delete the cell and then type in the function again it works. Here is the code for the function
function countColoredCells(countRange, colorRef) {
const ss = SpreadsheetApp.getActive();
const formula = ss.getActiveRange().getFormula();
let searchColor, countRangeA1;
try {
const colorRefA1 = formula.match(/,(.+))/).pop().trim();
searchColor = ss.getActiveSheet().getRange(colorRefA1).getBackground();
countRangeA1 = formula.match(/((.+),/).pop().trim();
} catch (error) {
throw new Error('Bad arguments.');
}
let count = 0;
ss.getSheets().forEach(sheet => {
count += sheet.getRange(countRangeA1).getBackgrounds()
.flat()
.filter(c => c === searchColor)
.length
});
return count;
}
Here is the line calling the function:
=countColoredCells(A:A,’Practice Sheet’!A6)
When I manually run the function again I get an error on line 10. I want the cell to update atomatically on spreadsheet changes.
I tried to add a trigger on spreadsheet changes but it gives me the same error as mentioned above and the code fails.