You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets按指定列匹配日历创建Calendar事件的脚本报错排查

问题根因

运行报错+功能不生效是多处代码逻辑/语法错误导致的:

  • 直接触发ReferenceError: Title is not defined的原因:createEvent函数中写了new Title(title),Apps Script不存在Title这个内置构造函数,属于无效代码。
  • 时间参数传递错误:创建Date对象时传入的是列序号变量startDtId/endDtId,而非从表格读取到的实际时间值startDt/endDt,生成的时间完全无效。
  • 事件标题未取实际值:传入创建事件方法的title是列序号3,不是对应单元格存储的活动名称内容。
  • 初始写的createCalendarEvent函数存在大量低级错误:变量名前后不匹配(定义spreadsheet后续调用sheet)、方法名拼写错误(creat漏写字母e)、getOwnedCalendarsByName未传入场地名参数,属于无效废代码。
  • 缺少边界校验:未匹配到对应场地时calendarId为空字符串,存在无意义自赋值代码var type = type;,原代码给结束时间强制加1天的逻辑不符合普通时段预约的需求。
修正后可直接运行的代码
// 列号配置:按表格实际结构修改,Apps Script列号从1开始计数,A列为1
const CALENDAR_TYPE_COL = 4;  // D列,存储场地名称
const EVENT_TITLE_COL = 3;    // C列,存储预约活动标题
const START_TIME_COL = 7;     // G列,存储活动开始时间
const END_TIME_COL = 9;       // I列,存储活动结束时间

// 场地与对应日历ID的映射,新增场地直接在对象中添加键值对即可
const CALENDAR_MAP = {
  "Aux Gym": "c_cvla3g52fqbd4l20rvhk7er8tg@group.calendar.google.com",
  "OL 2": "c_cvla3g52fqbd4l20rvhk7er8tg@group.calendar.google.com",
  "Main Soccer Field": "c_7jau68ofbhbeivnomh232dbelg@group.calendar.google.com",
  "BK 2": "c_7jau68ofbhbeivnomh232dbelg@group.calendar.google.com",
  "GT 1": "calId3@group.calendar.google.com",
  "GT 2": "calId3@group.calendar.google.com"
};

function createCalendarEventFromForm() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const lastRow = sheet.getLastRow();
  
  // 读取最新提交行的字段值
  const eventTitle = sheet.getRange(lastRow, EVENT_TITLE_COL).getValue();
  const venueName = sheet.getRange(lastRow, CALENDAR_TYPE_COL).getValue().trim();
  const startTime = new Date(sheet.getRange(lastRow, START_TIME_COL).getValue());
  const endTime = new Date(sheet.getRange(lastRow, END_TIME_COL).getValue());

  // 校验场地匹配状态
  const targetCalendarId = CALENDAR_MAP[venueName];
  if (!targetCalendarId) {
    throw new Error(`场地【${venueName}】未配置对应日历,请更新CALENDAR_MAP配置`);
  }

  // 校验时间格式合法性
  if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
    throw new Error("时间列内容格式非法,无法解析为有效时间");
  }

  // 向对应日历写入事件
  const targetCal = CalendarApp.getCalendarById(targetCalendarId);
  targetCal.createEvent(eventTitle, startTime, endTime);
}
使用注意事项
  • 先核对代码开头的列号配置,和你自己表格的实际列位置保持一致。
  • 把CALENDAR_MAP中的键替换为D列实际会出现的场地名称,值替换为对应场地日历的真实ID,不要保留占位符内容。
  • 原有写废的三个函数(开头拼写错误的createCalendarEvent、selectCalendarID、旧的createEvent)全部删除,避免旧代码冲突。
  • 建议给createCalendarEventFromForm函数绑定表单提交触发器,每次有新预约提交时自动执行,不需要手动运行。
  • 原代码强制给结束时间加1天的逻辑已移除,如果是全天跨天活动再自行添加对应逻辑,普通时段预约直接使用表单填报的结束时间即可,避免日历占用时长错误。

内容的提问来源于stack exchange,提问作者Mechelle Gattis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 10:21:39