Skip to content

Instantly share code, notes, and snippets.

@redbar0n
Last active July 26, 2020 04:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redbar0n/738f586ed875ae0f9da3212c0fa563a0 to your computer and use it in GitHub Desktop.
Save redbar0n/738f586ed875ae0f9da3212c0fa563a0 to your computer and use it in GitHub Desktop.
Google Sheets - How to format cells through code in Google Sheets - Option 3: Using `SpreadsheetApp.newConditionalFormatRule().withCriteria` instead of using `.whenFormulaSatisfied()`
// Alternatively: Using withCriteria. Requires more boilerplate than using whenFormulaSatisfied.
// This code shows the same case above as a specific instance of the general case of using withCriteria,
// which has a bit more boilerplate setup.
function setRangeToRedBackground(cellsInA1Notation) {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(cellsInA1Notation);
var customFormulaString = "=A1=1";
var criteria = SpreadsheetApp.BooleanCriteria.CUSTOM_FORMULA; // booleanConditionCriteriaType is an alternative name for this
var argsArray = [customFormulaString]; // booleanConditionCriteriaValues is an alternative name for this
// Could have used the convenience method whenFormulaSatisfied instead of withCriteria (withCriteria is probably what it uses internally).
// withCriteria allows using any of the BooleanCriteria Enum types, like CUSTOM_FORMULA here, or CELL_EMPTY (then argsArray would need to be [])
var rule = SpreadsheetApp.newConditionalFormatRule()
.withCriteria(criteria, argsArray)
.setBackground("red")
.setRanges([range])
.build();
addConditionalFormatRule(sheet, rule); // simple custom convenience function I made, shown previously.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment