Google apps script, how to create an event object script that activates when you change the name of a sheet?

↘锁芯ラ 提交于 2019-12-24 23:24:34

问题


I am attempting to create an onEdit type script that connects two sheets so that if the name of one of the sheets gets changed the other also gets changed. My idea so far was to maybe use the "oldValue" compared to the "value" in an if else operation but I cant figure out a way to get it to work.

If it can't be done then that's fine but if it can then I would be very grateful.

Thanks in advance.

:)


回答1:


Here's a simple onChange function that will get the old sheet name and the new sheet name when a sheets name is changed by the user.

The first function just set's up the PropertiesService. It should be run just to create the 'oshts' property.

function setupPropertyoshts() {
  PropertiesService.getDocumentProperties().setProperty('oshts', SpreadsheetApp.getActive().getSheets().map(function(sheet){return sheet.getName()}).join(','));
  Logger.log(PropertiesService.getDocumentProperties().getProperty('oshts'));
}

This is the function that you attach to the onChange installable trigger. I left all of the Logger.logs and the toast that I used for debugging it in the script.

function sheetNameChange(e) {
  var cshts=e.source.getSheets().map(function(sheet){return sheet.getName()});
  var oshts=PropertiesService.getDocumentProperties().getProperty('oshts').split(',');
  Logger.log('cshts: %s oshts: %s',cshts,oshts);
  var oldName=oshts[cshts.indexOf(e.source.getActiveSheet().getName())];
  Logger.log('oldName; %s newName: %s',oldName,e.source.getActiveSheet().getName());
  e.source.toast(Utilities.formatString('The old name was %s. The new name is %s.',oldName,e.source.getActiveSheet().getName()));
  PropertiesService.getDocumentProperties().setProperty('oshts',cshts.join(','));
}

Other References

  1. onChange Event Object
  2. SpreadsheetApp Class Reference
  3. JavaScript Array.map reference
  4. Managing Triggers Manually
  5. Managing Triggers Programmatically


来源:https://stackoverflow.com/questions/55199621/google-apps-script-how-to-create-an-event-object-script-that-activates-when-you

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