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
相关产品推荐
相关产品推荐

