在Google表格中,将剪切值粘贴到表格中时,可能会破坏条件格式应用于该表格中的单元格范围。我的工作表经常由同事编辑,并且它mangles有条件的格式。我正在尝试创建一个脚本-在编辑时-从工作表的每一列中复制条件格式设置规则,然后将这些规则重新应用于粘贴到每一列中的任何单元格。
我是脚本新手,所以很多都是由有用的用户在previous question I had posed中编译的。
function onEdit(e) {
var range = e.range;
var column = range.getColumn();
var sheet = range.getSheet();
range.clearFormat();
//clears formatting just on data that is pasted into the sheet
//Get all Sheet rules and iterate through them
var rules = sheet.getConditionalFormatRules();
var newRules = [];
newRules = newRules.concat(rules);
for(var r = 0; r < rules.length; r++) {
var rule = rules[r];
//Get condition for each rule
var booleanCondition = rule.getBooleanCondition();
//Get the ranges to which each rule applies and iterate through
var ranges = rule.getRanges();
for (var i = 0; i < ranges.length; i++) {
var ruleColumn = ranges[i].getColumn();
//If condition isn't null and edited column is the same as the one in the range, add rule
if((ruleColumn == column) && (booleanCondition != null)) {
var newRule = SpreadsheetApp.newConditionalFormatRule()
.withCriteria(booleanCondition.getCriteriaType(), booleanCondition.getCriteriaValues())
.setBackground(booleanCondition.getBackground())
.setRanges([range])
.build();
newRules.push(newRule);
}
}
}
sheet.setConditionalFormatRules(newRules);
}
这将采用工作表中存在的条件格式设置规则,并将它们重新应用于任何已编辑的范围,仅将规则仅应用于从其复制的列。唯一的问题是它会在每列中复制every规则,包括同一规则的迭代。每次编辑工作表时,应用于已编辑单元格的规则的数量都会成倍增加,而且我担心我的计算机即将爆炸。
是否有一种方法只能从工作表的第一行提取条件格式设置规则并将它们(按列)应用于已编辑的范围?这将避免我的规则永久扩散的问题,对此我将[[非常表示感谢。
function onEdit(e) {
var range = e.range;
var column = range.getColumn();
var sheet = range.getSheet();
range.clearFormat();
//clears formatting just on data that is pasted into the sheet
//Get all Sheet rules and iterate through them
var rules = sheet.getConditionalFormatRules();
var newRules = [];
newRules = newRules.concat(rules);
for(var r = 0; r < rules.length; r++) {
var rule = rules[r];
//Get condition for each rule
var booleanCondition = rule.getBooleanCondition();
//Get the ranges to which each rule applies and iterate through
var ranges = rule.getRanges();
for (var i = 0; i < ranges.length; i++) {
var ruleColumn = ranges[i].getColumn();
var ruleRow = ranges[i].getRow();
//If condition isn't null and edited column is the same as the one in the range, add rule
if((ruleColumn == column) && (ruleRow == 1) && (booleanCondition != null)) {
var newRule = SpreadsheetApp.newConditionalFormatRule()
.withCriteria(booleanCondition.getCriteriaType(), booleanCondition.getCriteriaValues())
.setBackground(booleanCondition.getBackground())
.setRanges([range])
.build();
newRules.push(newRule);
}
}
}
sheet.setConditionalFormatRules(newRules);
}
[如果规则范围从第一行开始(即:'A1','A1:A4','D1:D10'等),它将复制规则。[1] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getconditionalformatrules