我有一个Google电子表格,其中有几十张相同的表格。我必须对所有工作表应用相同的条件格式,因此我想在第一张工作表上手动制作,然后使用Google Apps脚本将条件格式应用于所有其他工作表。我已经完成了下面的编码,但是我得到一个错误,说法语翻译,“条件格式规则不能参考antoher表”。
function myFunction() {
var my_spreadsheet = SpreadsheetApp.getActiveSpreadSheet();
var all_sheets = my_spreadsheet.getAllSheets();
var source_sheet = all_sheets[0];
var source_rules = source_sheet.getConditionalFormatRules();
var destination_sheet;
for (var i=1; i<=all_sheets.length-1; i++){
destination_sheet = all_sheets[i];
destination_sheet.setConditionalFormatRules(source_rules);
}
}
您知道如何使用Google Apps脚本或任何其他方式将条件格式从一张工作表复制到另一张工作表吗?
如果我的理解是正确的,那么如何使用Sheets API?我认为发生此类错误的原因可能是源表的信息包含在条件格式中。通过这种考虑,我使用Sheets API修改了表格信息,以复制条件格式。我认为你的情况有几个答案。所以请把它想象成其中之一。
使用Sheets API时,请在Advanced Google Services和API控制台上启用Sheets API。您可以在here上查看如何启用Sheets API。
function myFunction() {
var my_spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = my_spreadsheet.getId();
var all_sheets = my_spreadsheet.getSheets();
var source_sheet = all_sheets[0].getSheetName();
var srcConditionalFormats = Sheets.Spreadsheets.get(spreadsheetId, {ranges: source_sheet, fields: "sheets/conditionalFormats"});
all_sheets.shift();
var cf = srcConditionalFormats.sheets[0].conditionalFormats;
var reqs = all_sheets.reduce(function(ar, e, i) {
return ar.concat(cf.map(function(f, j) {
var temp = JSON.parse(JSON.stringify(f));
temp.ranges = temp.ranges.map(function(g, k) {
g.sheetId = e.getSheetId();
return g;
});
return {addConditionalFormatRule: {rule: temp}};
}));
}, []);
Sheets.Spreadsheets.batchUpdate({requests: reqs}, spreadsheetId);
}
在此脚本中,运行以下流程。
Spreadsheets.get()
从源表中检索条件格式对象。
从您的脚本中,它假设源表是工作表的第一个索引。Spreadsheets.batchUpdate()
创建请求正文。
此时,纸张信息(sheetId)被修改。Spreadsheets.batchUpdate()
请求创建的请求正文。SpreadsheetApp.getActiveSpreadSheet()
有一个拼写错过,my_spreadsheet.getAllSheets()
没有使用任何方法。但在你的问题中,写的是The conditional formating rule can't refer to antoher sheet
的错误发生。从这种情况来看,我认为这可能是由于您在发布问题时的错误描述。如果我误解了你的问题并且这不是你想要的结果,我道歉。