Google Apps Script时间触发器报错:ReferenceError: e未定义
解决Google Apps Script时间触发器运行锁定脚本时的ReferenceError错误
错误原因
基于时间的触发器运行脚本时,不会传递事件对象e,但你的myFunction中直接使用了e.source来获取表格实例,这就导致了e is not defined的报错。
解决方案
修改锁定脚本,直接通过SpreadsheetApp.getActiveSpreadsheet()获取当前绑定的表格,替代依赖事件对象的e.source,这样脚本既能手动运行,也能兼容时间触发器的自动执行。
修改后的锁定脚本
function myFunction() { const editors = ["abc@abc.com", "xyz@xyz.com"]; const sheetNames = ["Sheet1"]; // 替换e.source,直接获取当前绑定的Google表格 const spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); const sheets = spreadsheet.getSheets().filter(s => sheetNames.includes(s.getSheetName())); if (sheets.length == 0) return; sheets.forEach(s => { const p = s.getProtections(SpreadsheetApp.ProtectionType.RANGE); if (p.length > 0) { p.forEach(pp => pp.remove()); } // 获取第1到16列直到最后一行的所有值 var range = s.getRange(1, 1, s.getLastRow(), 16).getValues(); var lastRow = range.length - 1; /* 从下往上检查行,遇到非空行就停止 模拟getLastRow()的行为,但限制在第1-16列 */ for (lastRow; lastRow > 0; lastRow--) { if (range[lastRow].join('').length > 0) break; } if (lastRow != 0) { const startRow = 6; const numRows = lastRow - 4; const newProtect = s.getRange(startRow, 1, numRows, 16).protect(); newProtect.removeEditors(newProtect.getEditors()); newProtect.addEditors(editors); if (newProtect.canDomainEdit()) newProtect.setDomainEdit(false); } }); }
修改说明
- 核心修改:用
SpreadsheetApp.getActiveSpreadsheet()替代e.source,确保无论触发方式如何,都能正确获取表格实例。 - 其余逻辑保持不变,锁定功能的执行逻辑不受影响。
时间触发器脚本无需修改
原有的触发器创建脚本可以直接使用,它会生成每日2点01分自动运行锁定脚本的触发器:
function setTrigger() { ScriptApp.newTrigger("myFunction") .timeBased() .everyDays(1) .atHour(2) .nearMinute(01) .create(); }
内容的提问来源于stack exchange,提问作者Essem
相关产品推荐
相关产品推荐

