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

请求Google Sheets App Script代码:下拉框选中指定值时记录起止时间戳

Google Sheets 自动记录状态切换时间戳脚本

以下是完全符合需求的代码,以及针对无编程经验用户的操作步骤:

完整代码

function onEdit(e) {
  // 获取编辑触发的单元格和工作表
  const editedRange = e.range;
  const editedSheet = editedRange.getSheet();

  // 仅处理「Work Sheet」中K3单元格的编辑
  if (editedSheet.getName() !== "Work Sheet" || editedRange.getA1Notation() !== "K3") {
    return;
  }

  const currentValue = editedRange.getValue();
  const dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  const startTimeCell = dataSheet.getRange("P3");
  const endTimeCell = dataSheet.getRange("Q3");

  // 选中「Awaiting Client Documents」时记录开始时间(仅首次选中时写入)
  if (currentValue === "Awaiting Client Documents") {
    if (!startTimeCell.getValue()) {
      startTimeCell.setValue(new Date());
      startTimeCell.setNumberFormat("yyyy-MM-dd HH:mm:ss");
    }
  } 
  // 切换出该状态时记录结束时间(仅当已记录开始时间且未记录结束时间时写入)
  else {
    if (startTimeCell.getValue() && !endTimeCell.getValue()) {
      endTimeCell.setValue(new Date());
      endTimeCell.setNumberFormat("yyyy-MM-dd HH:mm:ss");
    }
  }
}

操作步骤

  • 打开你的Google Sheets文档
  • 点击顶部菜单栏的「扩展程序」→「Apps 脚本」,进入脚本编辑器
  • 删除编辑器内默认的示例代码,将上面的代码粘贴进去
  • 点击编辑器顶部的保存图标,为脚本命名(例如「StatusTimestampTracker」)
  • 关闭脚本编辑器,返回表格进行测试:
    • 在「Work Sheet」的K3下拉菜单选择「Awaiting Client Documents」,检查「Data」工作表的P3单元格是否生成时间戳
    • 将K3切换为其他选项,检查「Data」工作表的Q3单元格是否生成结束时间戳

说明

  • 时间戳格式设置为yyyy-MM-dd HH:mm:ss,如果需要调整格式,修改代码中setNumberFormat的参数即可(例如"MM/dd/yyyy hh:mm AM/PM")
  • 脚本仅在状态首次切换时写入时间,避免重复覆盖;如果需要每次切换都更新时间,可删除代码中判断单元格是否为空的if (!startTimeCell.getValue())和if (startTimeCell.getValue() && !endTimeCell.getValue())条件

内容的提问来源于stack exchange,提问作者Sara Hatamleh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:12:45