Modifications
Since the introduction of the V8 runtime, one can take advantage of modern ES6 features such as arrow functions, and destructuring. Additionally, the script can be optimized to avoid it becoming slow on larger collections.
First of all, it is important to follow the best practices. I/O (input/output) operations such as getRange
, setBackground
, setValue
are slow. Do not use them inside loops, use batch operations like getBackgrounds
, setBackgrounds
, setValues
, setFontColors
, etc.
Secondly, it is much faster to work on a grid of values than offsetting the range each time you need to go to another row. Chain getDataRange
and getValues
to get all values from the sheet and work directly on the resulting array (if you have a lot of data in the sheet, use the getRange
to your liking, just follow the same principle).
Finally, hardcoding sheet name makes the script inflexible, it should either be a parameter of the function, or at least a declared constant in a context accessible to the function.
Snippet
Given the modifications mentioned above, the snippet (of the other answer) can be modified as follows:
const myColorFunction = ({
sheetName = "Form Responses 1",
targetValue = "Open"
} = {}) => {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const rng = sheet.getDataRange();
const numHeaders = 1;
const backgrounds = rng.getBackgrounds();
const fontColors = rng.getFontColors();
const newBckgs = backgrounds.map((row) => {
const [firstCell] = row;
if (firstCell === targetValue) {
row[5] = "red";
}
return row;
});
const newColors = fontColors.map((row) => {
const [firstCell] = row;
if (firstCell === targetValue) {
row[5] = "white";
}
return row;
});
rng.setBackgrounds(newBckgs);
rng.setFontColors(newColors);
}
Notes
- To save time, you can make the two
map
calls at the same time, but
I split them for clearer flow and to avoid mutating either the
backgrounds
or the fontColors
array.
- You should also remove both
"red"
and "white"
from being hardcoded, as well as the index of the column to set the color on.