Skip to content

Instantly share code, notes, and snippets.

@gludion
Last active May 12, 2021 16:24
Show Gist options
  • Save gludion/7c3b89df13fc1f1f25064adad1d7facd to your computer and use it in GitHub Desktop.
Save gludion/7c3b89df13fc1f1f25064adad1d7facd to your computer and use it in GitHub Desktop.
Fixes broken (*) formatting rules in Google Sheets. (*) Broken = range has been messed up by cut&paste. Paste this code in Tools/Script Editor.
function onEdit(e) {
checkAndFix();
}
/*
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Custom Tools')
.addItem('Check formatting rules', 'checkAndFix')
.addToUi();
}
*/
function checkAndFix() {
let sheet = SpreadsheetApp.getActiveSheet();
if (sheet && hasBrokenRules(sheet)) fixBrokenRules(sheet);
}
function hasBrokenRules(sheet) {
for(let rule of sheet.getConditionalFormatRules()) {
if (rule.getRanges().length > 1) return true
}
}
function fixBrokenRules(sheet) {
// fix broken rules
let newRules = [];
let rule;
let colMin, colMax, rowMin, rowMax;
let ranges;
for(let r1 of sheet.getConditionalFormatRules()) {
rule = r1.copy();
ranges = rule.getRanges();
if (ranges.length > 1) {
rowMin = colMin = Number.MAX_VALUE;
rowMax = colMax = -1;
for (let range of ranges) {
if (range.getColumn() < colMin) colMin = range.getColumn();
if (range.getLastColumn() > colMax) colMax = range.getLastColumn();
if (range.getRow() < rowMin) rowMin = range.getRow();
if (range.getLastRow() > rowMax) rowMax = range.getLastRow();
}
rule.setRanges([sheet.getRange(rowMin,colMin, rowMax-rowMin+1, colMax-colMin+1)]);
} else {
// rule with unique range: OK
let range = rule.getRanges()[0];
// BUT: a rule with 1x1 range should not be pushed (happens sometimes during cut&paste)
if (range.getWidth() ==1 && range.getHeight() == 1) rule = null;
}
if (rule) newRules.push(rule);
}
sheet.setConditionalFormatRules(newRules);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment