报错TypeError: Cannot read properties of null (reading 'createAllDayEvent')求排查
问题:脚本功能正常但触发TypeError错误
我的脚本功能正常,但每次运行都会触发错误:TypeError: Cannot read properties of null (reading 'createAllDayEvent'),错误位于脚本Janerio.gs的第12行。我无法找到问题根源,作为新手希望有人能指出错误,相关代码如下:
function month01(){ // get Calendar ID let sheet = SpreadsheetApp.getActiveSheet() let id = SpreadsheetApp.getActive().getRangeByName("CalendarID").getValue() // get Event data...the filter allows us to only get rows that contain data, and to exclude the checkbox in the filter let events = SpreadsheetApp.getActive().getRangeByName("EventList01").getValues().filter(array => array.slice(0, -1).some(value => value !== '')); //single day event with just title and date events.forEach( function(e, index){ if(!e[22]){ CalendarApp.getCalendarById(id).createAllDayEvent( e[2], e[0], {description: e[1]}) let newIndex = index+3; sheet.getRange("AB"+ newIndex).setValue(true) } }) }
解决方案
错误核心是CalendarApp.getCalendarById(id)返回了null,导致调用createAllDayEvent时触发“无法读取null属性”的报错,具体排查和修复方向如下:
校验CalendarID的正确性:
确认表格中命名为CalendarID的单元格里的内容是正确的日历ID,无空格、拼写错误。可以在Google日历的「设置和共享」→「集成日历」中复制官方提供的ID。新增空值判断逻辑:
在调用日历方法前先检查是否成功获取到日历对象,避免错误触发,修改后的代码如下:
function month01(){ // get Calendar ID let sheet = SpreadsheetApp.getActiveSheet() let id = SpreadsheetApp.getActive().getRangeByName("CalendarID").getValue() // 检查ID是否为空 if (!id) { SpreadsheetApp.getUi().alert("请填写有效的CalendarID!"); return; } let calendar = CalendarApp.getCalendarById(id); // 检查是否成功获取日历对象 if (!calendar) { SpreadsheetApp.getUi().alert("无法找到对应ID的日历,请检查ID是否正确!"); return; } // get Event data...the filter allows us to only get rows that contain data, and to exclude the checkbox in the filter let events = SpreadsheetApp.getActive().getRangeByName("EventList01").getValues().filter(array => array.slice(0, -1).some(value => value !== '')); //single day event with just title and date events.forEach( function(e, index){ if(!e[22]){ calendar.createAllDayEvent( e[2], e[0], {description: e[1]}) let newIndex = index+3; sheet.getRange("AB"+ newIndex).setValue(true) } }) }
- 确认日历访问权限:
确保运行脚本的账号拥有目标日历的访问权限(比如日历已共享给该账号,或账号本身是日历所有者)。
内容的提问来源于stack exchange,提问作者Tomás Albuquerque
相关产品推荐
相关产品推荐

