问题
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
- onChange Event Object
- SpreadsheetApp Class Reference
- JavaScript Array.map reference
- Managing Triggers Manually
- Managing Triggers Programmatically
来源:https://stackoverflow.com/questions/55199621/google-apps-script-how-to-create-an-event-object-script-that-activates-when-you