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

Google Sheets脚本故障排查:列修改触发时间戳记录与复制

修复Google Apps Script时间戳记录问题

原代码存在的问题

  • 列索引错误:multi函数监听的是M列(索引13),但需求是监听K列(索引11);single函数中rowStart < 1的判断逻辑错误,应该排除表头行(改为row < 2)。
  • 逻辑判断失效:indexOf返回的是数字索引,和字符串"true"比较永远不成立,导致监听逻辑完全反转。
  • 全局代码无效:最后的copyTo代码不在任何函数内部,永远不会被执行。
  • 缺少不可编辑设置:未处理P列时间戳不可编辑的需求。

修正后的代码

function onEdit(e) {
  const sheet = e.source.getActiveSheet();
  const row = e.range.rowStart;
  const col = e.range.columnStart;

  // 跳过表头行,只处理数据行
  if (row < 2) return;
  // 仅针对"Forms"工作表执行逻辑
  if (sheet.getName() !== 'Forms') return;

  // K列(第11列)修改时:记录N列时间戳并同步到P列(设置不可编辑)
  if (col === 11) {
    const timestamp = new Date();
    // 写入N列(第14列)
    sheet.getRange(row, 14).setValue(timestamp).setNumberFormat("MM/dd/yyyy hh:mm");
    // 写入P列(第16列)并设置不可编辑
    const targetCell = sheet.getRange(row, 16);
    targetCell.setValue(timestamp).setNumberFormat("MM/dd/yyyy hh:mm");
    // 移除其他用户编辑权限,仅所有者可修改
    const protection = targetCell.protect();
    protection.removeEditors(protection.getEditors());
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }
  }

  // L列(第12列)修改时:记录O列时间戳
  if (col === 12) {
    sheet.getRange(row, 15).setValue(new Date()).setNumberFormat("MM/dd/yyyy hh:mm");
  }
}

代码说明

  • 合并所有逻辑到onEdit函数,避免多函数调用的混乱;
  • 明确列索引对应关系:K列=11、L列=12、N列=14、O列=15、P列=16;
  • 通过单元格保护实现P列时间戳不可编辑;
  • 使用getRange(row, col)直接定位目标单元格,比offset更直观,减少出错概率。

内容的提问来源于stack exchange,提问作者Enrique Espinosa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:32:36