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

如何确保Google Sheets中K列仅在输入付款日期时填充?

解决Google Sheets K列自动全部填充的问题

修改后的代码

function dateplay() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const data = sh.getRange(2, 10, sh.getLastRow() - 1, 1).getValues();
  const output = Array(data.length).fill([null]);

  output.forEach((e, i) => {
    const cellValue = data[i][0];
    // 仅当J列有有效日期时才执行计算
    if (cellValue instanceof Date && !isNaN(cellValue.getTime())) {
      let dt = new Date(cellValue);
      dt.setDate(dt.getDate() + daysInNextMonth(dt));
      e[0] = dt;
    }
  });

  sh.getRange(2, 11, output.length, 1).setValues(output);
}

function daysInNextMonth(date) {
  const nextMonth = date.getMonth() + 1;
  const targetYear = nextMonth === 12 ? date.getFullYear() + 1 : date.getFullYear();
  // 计算目标月份的总天数
  return new Date(targetYear, nextMonth + 1, 0).getDate();
}

核心改动说明

  • 添加有效性判断:遍历J列数据时,先检查单元格是否为有效日期,只有符合条件才计算并填充K列,否则保持K列空白。
  • 修正数据范围:调整getRange的行数参数,避免处理表格末尾的空行,减少不必要的计算操作。
  • 修复跨年计算bug:原函数使用当前年份计算下一个月天数,跨年时会出错,现在基于原日期的年份动态调整,确保结果准确。
  • 初始化空白输出数组:直接创建全空白的数组,避免覆盖K列原有空白单元格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:35:41