如何用Apps Script匹配特定Code并获取对应最新日期行
Google Sheets Apps Script:按Code筛选最新日期行并执行操作
核心逻辑
- 用对象缓存每个
Code的最新记录,遍历数据时实时对比更新日期,保留最新的那一行 - 最后筛选出最新记录里
Take action?为Yes的条目,执行后续操作
参考代码
function processLatestCodeEntries() { // 替换成你的表格ID和目标工作表名称 const spreadsheetId = "你的表格ID"; const sheetName = "目标工作表"; const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName); // 获取全表数据(表头在第一行,数据从第二行开始) const data = sheet.getDataRange().getValues(); const headers = data[0]; // 定位各列索引,根据你的实际表头调整 const codeCol = headers.indexOf("Code"); const dateCol = headers.indexOf("Date"); const actionCol = headers.indexOf("Take action?"); // 存储每个Code对应的最新记录 const latestRecords = {}; // 遍历所有数据行(跳过表头) for (let i = 1; i < data.length; i++) { const row = data[i]; const code = row[codeCol]; const currentDate = new Date(row[dateCol]); const takeAction = row[actionCol]; // 若该Code无记录,或当前行日期更晚,则更新缓存 if (!latestRecords[code] || currentDate > new Date(latestRecords[code].date)) { latestRecords[code] = { rowNum: i + 1, // 表格行号从1开始计数 date: row[dateCol], needAction: takeAction, rowData: row }; } } // 处理符合条件的条目 for (const code in latestRecords) { const record = latestRecords[code]; if (record.needAction === "Yes") { // 这里写你要执行的操作,比如修改单元格、发送提醒等 console.log(`处理Code: ${code},最新日期行号: ${record.rowNum}`); // 示例:标记该行已处理 // sheet.getRange(record.rowNum, actionCol + 1).setValue("已处理"); } } }
注意事项
- 替换
spreadsheetId和sheetName为你的实际表格信息 - 确保表头名称和代码中
indexOf的参数完全一致,比如你的表头是"编码"就改成headers.indexOf("编码") - Date列的内容必须是合法日期格式,否则
new Date()无法正确解析对比日期
内容的提问来源于stack exchange,提问作者Julius Bright Ross
相关产品推荐
相关产品推荐

