Google Apps Script问题:如何仅复制符合条件的新增行
解决Google Apps Script重复复制旧数据的问题
原脚本每次运行都会遍历Source表的所有行,只要匹配"PoinPOin"就复制,没有记录已复制的内容,导致重复复制旧数据。以下是修改后的脚本,仅复制新增的目标行:
function CopyDataGames() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sourceSheet = ss.getSheetByName("Source"); const targetSheet = ss.getSheetByName("Copie"); const props = PropertiesService.getScriptProperties(); // 获取上次处理到的行号,首次运行默认从第1行开始 const lastProcessedRow = parseInt(props.getProperty("lastProcessedRow")) || 1; const sourceLastRow = sourceSheet.getLastRow(); // 无新增行时直接结束 if (sourceLastRow <= lastProcessedRow) return; // 批量获取新增行的所有数据,减少服务调用次数 const dataRange = sourceSheet.getRange(lastProcessedRow + 1, 1, sourceLastRow - lastProcessedRow, 44); const dataValues = dataRange.getValues(); let targetLastRow = targetSheet.getLastRow(); let rowsToCopy = []; // 筛选出名称为PoinPOin的行 dataValues.forEach(row => { const name = row[1]; // 第2列对应名称(数组索引从0开始) if (name === "PoinPOin") { rowsToCopy.push(row); } }); // 批量写入目标表 if (rowsToCopy.length > 0) { targetSheet.getRange(targetLastRow + 1, 1, rowsToCopy.length, 44).setValues(rowsToCopy); // 更新上次处理的行号,避免重复处理 props.setProperty("lastProcessedRow", sourceLastRow.toString()); } }
关键改动说明
- 用
PropertiesService存储上次处理的行号,确保每次只处理新增行 - 批量获取和写入数据,替代原脚本循环内多次调用
getRange,大幅提升运行效率 - 先筛选后批量写入,减少不必要的操作
重置处理记录(可选)
如果需要重新处理所有行,执行以下脚本清除存储的行号:
function resetLastProcessedRow() { const props = PropertiesService.getScriptProperties(); props.deleteProperty("lastProcessedRow"); }
内容的提问来源于stack exchange,提问作者Noz0ru
相关产品推荐
相关产品推荐

