Google Apps Script OnEdit触发创建日历事件报授权错误
问题原因
你遇到的授权报错和scope配置无关,是Google Apps Script简单触发器的硬性限制:
- 直接命名为
onEdit的简单触发器运行在受限授权模式下,仅能执行无需用户敏感授权的基础Spreadsheet操作,无法调用Calendar、Gmail、Drive等需要额外授权的服务,哪怕你在应用清单里声明了对应权限也不会生效。 - 手动通过自定义菜单运行脚本时走的是全量授权模式,所以功能正常,这也是两种运行方式表现不一致的核心原因。
修复方案
1. 替换为可安装编辑触发器
不要用默认的简单onEdit触发器,改用可安装编辑触发器,这类触发器运行在全授权上下文,可以正常调用Calendar服务,配置步骤:
- 打开Apps Script编辑器,点击左侧边栏的时钟形状「触发器」按钮
- 点击右下角「添加触发器」
- 触发函数选择
overwright,不要选原生的onEdit - 事件源选择「来自电子表格」,事件类型选择「编辑时」
- 按需配置失败通知规则后点击保存,按弹窗提示完成账号授权即可
- 注意:配置完成后请删除原来的
onEdit函数,避免两个触发器同时触发导致重复创建日程
2. 修复原有代码的逻辑bug
你现有代码里有两处会导致运行异常的问题,修正后的完整代码如下:
// 已删除原生onEdit简单触发器,避免重复触发 function overwright(e) { // 直接用事件对象判断,减少不必要的API调用,仅当编辑Z3且值为TRUE时执行逻辑 if (!e.range || e.range.getA1Notation() !== "Z3" || e.range.getValue() !== true) return; const spreadsheet = SpreadsheetApp.getActive(); Inboeken(); spreadsheet.getRange('Z3').setValue(false); } function Inboeken() { // Calendar info 注意把"email"替换成你实际的日历ID const calendar = CalendarApp.getCalendarById("email"); const sheet = SpreadsheetApp.getActiveSheet(); // 日程基础信息 const titel = "R'DAM - " + sheet.getRange("I3").getValue() + " " + sheet.getRange("M3").getValue(); const startTime = sheet.getRange("B3").getValue(); const endTime = sheet.getRange("C3").getValue(); // 日程描述 注意单个单元格取值用getDisplayValue()单数形式,避免返回二维数组导致格式异常 const naam = sheet.getRange("G3").getValue(); const starttijd = sheet.getRange("E3").getDisplayValue(); const eindtijd = sheet.getRange("F3").getDisplayValue(); const aantal = sheet.getRange("H3").getValue(); const status = sheet.getRange("K3").getValue(); const notitiedatum = Utilities.formatDate(new Date(), "GMT+2", "dd-MM-yyyy") console.log(naam + " " + startTime + " " + endTime + " " + aantal + " " + status + " " + notitiedatum); calendar.createEvent(titel, startTime, endTime, { description: ("Naam: ".bold() + naam + "\n" +"Tijd: ".bold() + starttijd + " - " + eindtijd + "\n" + "Aantal: ".bold() + aantal + "\n" + "\n" + "---"+"\n" + notitiedatum + " M: Als " + status + " ingeboekt" ), location: (naam + " / " + aantal + " pax" ) }) }
额外注意事项
- 可安装触发器默认使用触发器创建者的权限运行,也就是说所有编辑操作触发的日程创建,都会写入你配置的对应日历中,如果你需要根据编辑者身份写入不同日历,需要额外配置权限逻辑。
- 不要给可安装触发器绑定名为
onEdit的函数,否则会同时触发简单触发器和可安装触发器,导致逻辑重复执行。
内容的提问来源于stack exchange,提问作者Evorsa evenementen
相关产品推荐
相关产品推荐

