In Google Sheets, the range of cells that conditional formatting applies to can change when you paste in new values. I'm looking for a script that will copy the conditional formatting present in the sheet and reapply it to new cells as people paste in data.
I don't actually do much scripting, but I steal other people's scripts and Frankenstein them together until they're vaguely functional. Here's what I've stolen so far:
function onEdit(e) {
var range = e.range;
var sheet = range.getSheet();
range.clearFormat();
//clears formatting just on data that is pasted into the sheet
var rules = sheet.getConditionalFormatRules();
var newRules = [];
for(var r = 0; r < rules.length; r++) {
var booleanCondition = rules[r].getBooleanCondition();
if(booleanCondition != null) {
var rule = SpreadsheetApp.newConditionalFormatRule()
.withCriteria(booleanCondition.getCriteriaType(), booleanCondition.getCriteriaValues())
.setBackground(booleanCondition.getBackground())
.setRanges([sheet.getRange("A:A"),sheet.getRange("C:C")])
.build();
newRules.push(rule);
sheet.setConditionalFormatRules(newRules);
}
}
}
The problem, of course, is that I'm getting ALL of the conditional formatting rules for that sheet and applying them all to two columns (A:A and C:C). These rules are applied regardless of what columns they used to apply to.
Can someone suggest a way to copy the pre-existing Conditional Formatting rules and reapply them to the columns I copied them from?