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

Google Script:查找当前行首个空白单元格并添加TODAY()公式

定位当前行最左侧空白单元格并插入今日日期宏

以下是Google Apps Script代码,可实现定位当前活动行最左侧空白单元格,并插入=TODAY()公式:

function addTodayToFirstBlankInCurrentRow() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const currentRow = sheet.getActiveRange().getRow();
  let firstBlankCol = null;

  // 从第1列开始遍历当前行的单元格,寻找首个空白单元格
  for (let col = 1; ; col++) {
    const cell = sheet.getRange(currentRow, col);
    const cellValue = cell.getValue();
    
    // 判断单元格是否空白(包括空字符串和null)
    if (cellValue === "" || cellValue === null) {
      firstBlankCol = col;
      break;
    }

    // 防止无限循环:如果遍历到超过当前工作表的最大列数仍未找到,退出循环
    if (col > sheet.getLastColumn()) {
      break;
    }
  }

  // 如果找到空白单元格,插入TODAY公式
  if (firstBlankCol) {
    sheet.getRange(currentRow, firstBlankCol).setFormulaR1C1('=TODAY()');
  } else {
    // 整行无空白单元格时的提示
    SpreadsheetApp.getUi().alert("当前行没有空白单元格");
  }
}

代码说明:

  • getActiveRange().getRow() 获取当前选中单元格所在的行号
  • 从第1列开始逐列检查单元格值,判断是否为空白
  • 找到首个空白单元格后,用setFormulaR1C1插入日期公式
  • 加入边界判断,避免遍历超出工作表最大列数导致的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:15:32