问题
I have the below functions that handle recording of changes to a change log when edits are made to a particular spreadsheet
Instead of monitoring changes to a single spreadsheet I would like to monitor changes to multiple spreadsheets (as array). How do I modify my code to create triggers for multiple spreadsheets?
var model1Id = 'xxx';
var changelogId = 'yyy';
//creates onEdit trigger.
function createOnEditTrigger(){
ScriptApp.newTrigger('catchEdits')
.forSpreadsheet(model1Id)
.onEdit()
.create();
}
//gets values from onEdit event and pushes this data to the changelog spreadsheet
function catchEdits(e){
var spreadId = e.source.getId();
var spreadName=e.SpreadsheetApp.getActiveSpreadsheet().getName();
var sheet = e.source.getActiveSheet();
var sheetName = sheet.getName();
var cellAddress = e.range.getA1Notation();
var oldValue = e.oldValue;
var value = e.value;
var user = e.user;
var date = new Date();
SpreadsheetApp.openById(changelogId).appendRow([spreadId,spreadName,sheetName,cellAddress,oldValue,value,user,date]);
}
回答1:
Question:
How do I modify my code to create triggers for multiple spreadsheets?
Answer:
If you have an array with the IDs
of the different spreadsheets to monitor, you could just loop through this array and create a trigger for each corresponding spreadsheet.
Code sample:
function createOnEditTrigger(){
const spreadsheetIds = ["spreadsheetId_1", "spreadsheetId_2", ...];
spreadsheetIds.forEach(spreadsheetId => {
const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
ScriptApp.newTrigger('catchEdits')
.forSpreadsheet(spreadsheet)
.onEdit()
.create();
});
}
Note:
- Please be aware that there is a limit of 20 triggers per user per script, so you cannot track more than 20 spreadsheet with a single script (see Current limitations).
e
doesn't have a propertySpreadsheetApp
, ande.source
refers to the current spreadsheet, so I'd suggest you to changevar spreadName = e.SpreadsheetApp.getActiveSpreadsheet().getName();
tovar spreadName = e.source.getName();
(see onEdit event object).
来源:https://stackoverflow.com/questions/63690673/how-to-detect-edits-from-multiple-spreadsheets