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

如何编写Google Sheets脚本复制单元格值到对应今日日期列的同排行单元格

需求实现代码修改方案

原代码存在的问题

  • 变量命名不规范且大小写不匹配:使用JS内置对象名Date作为自定义变量名,后续判断时又误用了小写date,导致变量取值异常
  • 日期匹配逻辑缺失:直接将日期对象与单元格范围对象对比,没有读取表头的实际值做匹配,也没有统一日期格式
  • 缺少表头遍历逻辑:没有遍历第一行的所有日期标题,无法定位到对应日期的列位置

修改后完整代码

function recordValue() {
  // 格式化日期为澳式格式 日.月.年(如26.8.21)
  function formatAusDate(date) {
    const day = date.getDate();
    const month = date.getMonth() + 1; // 月份从0计数,需要+1
    const year = date.getFullYear().toString().slice(-2); // 取年份后两位
    return `${day}.${month}.${year}`;
  }

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheetoffruit");
  const today = new Date();
  const todayStr = formatAusDate(today);
  
  // 可选:如果需要保留J1写入当前日期的逻辑可以打开下一行注释
  // sheet.getRange("J1").setValue(today);

  // 获取第一行从C列开始的所有表头值
  const headerValues = sheet.getRange("C1:1").getValues()[0];
  let targetCol = null;

  // 遍历表头找匹配的日期列
  for (let i = 0; i < headerValues.length; i++) {
    let cellValue = headerValues[i];
    let cellDateStr;
    if (cellValue instanceof Date) {
      // 如果表头单元格是日期格式,统一转成澳式字符串再对比
      cellDateStr = formatAusDate(cellValue);
    } else {
      // 如果是字符串格式直接转字符串
      cellDateStr = cellValue.toString();
    }
    if (cellDateStr === todayStr) {
      // C列是第3列,索引从0开始,所以列号是 i + 3
      targetCol = i + 3;
      break;
    }
  }

  if (!targetCol) {
    throw new Error(`未找到日期为${todayStr}的表头列`);
  }

  // 读取B55的值写入对应列的55行
  const targetValue = sheet.getRange("B55").getValue();
  sheet.getRange(55, targetCol).setValue(targetValue);
}

注:当前代码默认取值单元格为B55、写入行也为55行,如果需要适配你提到的B3单元格,只需将代码中B55和55对应修改为B3和3即可。

定时运行配置步骤

  • 打开Google Sheets的扩展程序菜单,选择「Apps Script」进入脚本编辑器
  • 点击左侧菜单栏的「触发器」按钮(时钟图标)
  • 点击右下角「添加触发器」
  • 选择要运行的函数为recordValue,事件源选择「时间驱动」,触发器类型选择「日计时器」
  • 时间范围选择你需要的固定时段,比如「晚上10点到11点」,保存即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:45:04