How to detect edits from multiple spreadsheets [closed]

柔情痞子 提交于 2021-02-20 05:01:54

问题


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 property SpreadsheetApp, and e.source refers to the current spreadsheet, so I'd suggest you to change var spreadName = e.SpreadsheetApp.getActiveSpreadsheet().getName(); to var spreadName = e.source.getName(); (see onEdit event object).


来源:https://stackoverflow.com/questions/63690673/how-to-detect-edits-from-multiple-spreadsheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!