如何临时停止Google Apps Script中的onSelectionChange自动执行函数?
临时停止Google Apps Script自动触发函数的实现方案
要实现临时停用onSelectionChange自动执行、且下次打开文件自动恢复的需求,你需要对现有代码做以下调整:
修改自动触发函数
在onSelectionChange开头加入停止标志检查,一旦检测到停止指令就直接退出函数:
function onSelectionChange(e) { const prop = PropertiesService.getScriptProperties(); // 检查停止标志,存在则直接终止函数执行 if (prop.getProperty('STOP')) return; const previousSheet = prop.getProperty("previousSheet"); const range = e.range; const sheetName = range.getSheet().getSheetName(); if (sheetName != previousSheet && sheetName=="Balance Life Today") { BalanceLifeTodayUpdate(); } else if (sheetName != previousSheet && sheetName=="Values Power Success") { ValuesPowerSuccessUpdate(); } else if (sheetName != previousSheet && sheetName=="To-Do List") { ToDoListUpdate(); } prop.setProperty("previousSheet", sheetName); }
保留并优化停止函数
你的stopScript函数只需稍作调整,明确设置标志值:
function stopScript() { PropertiesService.getScriptProperties().setProperty('STOP', 'true'); return '已停止自动执行,下次打开文件将恢复'; }
添加自动恢复函数
新增onOpen函数,在文件打开时自动清除停止标志,实现重启后恢复:
function onOpen() { PropertiesService.getScriptProperties().deleteProperty('STOP'); }
逻辑说明
- 临时停用:执行
stopScript函数后,onSelectionChange会检测到STOP标志,不再执行后续的工作表更新逻辑。 - 自动恢复:关闭并重新打开表格时,
onOpen函数会自动删除STOP标志,onSelectionChange恢复正常触发。
内容的提问来源于stack exchange,提问作者Sohel Ahamed
相关产品推荐
相关产品推荐

