如何将查询表行复制到目标表并基于唯一ID修改源表单元格
Google Apps Script 实现复制行并标记源表状态
功能说明
将query表第11行及以后的行复制到Target表,随后根据这些行的G列唯一ID(UID),将Source表对应行的H列设置为"yes"。
修改后的完整代码
function copyRows() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const query_sheet = ss.getSheetByName('query'); const target_sheet = ss.getSheetByName('Target'); const source_sheet = ss.getSheetByName('Source'); const startRow = 11; var outdata = []; var numrows = 0; var lastRownum = query_sheet.getLastRow(); console.log('Last row = ' + lastRownum); if (lastRownum >= startRow) { // 确保存在可复制的行 outdata = query_sheet.getRange(startRow, 1, lastRownum - startRow + 1, 9).getValues(); numrows = outdata.length; pasteMultipleRows(target_sheet, outdata); console.log(numrows + ' Rows Inserted into Target'); // 提取query表中所有有效UID(G列,数组索引为6) const uidsToMark = outdata.map(row => row[6]).filter(uid => uid !== ''); // 获取Source表的UID与行号映射,避免逐行查找 const sourceLastRow = source_sheet.getLastRow(); if (sourceLastRow < 1) return; const sourceUidData = source_sheet.getRange(1, 7, sourceLastRow, 1).getValues(); // 仅获取G列数据 const uidRowMap = {}; sourceUidData.forEach((row, index) => { const uid = row[0]; if (uid) uidRowMap[uid] = index + 1; // 行号从1开始计数 }); // 批量更新Source表H列为"yes" const updateRanges = []; uidsToMark.forEach(uid => { const targetRow = uidRowMap[uid]; if (targetRow) updateRanges.push(`${targetRow}:${targetRow}`); // 构造行范围字符串 }); if (updateRanges.length > 0) { source_sheet.getRangeList(updateRanges).getColumn(8).setValue('yes'); // 选择H列(第8列) console.log(updateRanges.length + ' rows marked as "yes" in Source sheet'); } } else { console.log('No rows to copy from query sheet (starting from row ' + startRow + ')'); } } function pasteMultipleRows(target_sheet, data) { var lastRow = target_sheet.getLastRow(); console.log(data.length + ' rows will be written to ' + target_sheet.getName() + ' from row ' + (lastRow + 1)); target_sheet.getRange(lastRow + 1, 1, data.length, data[0].length).setValues(data); }
关键改进点
- 修复无效调试代码:将原代码中无效的
if ('xxx');替换为console.log(),便于查看执行日志。 - 高效UID匹配:通过一次性读取
Source表的G列数据,构建UID到行号的映射对象,避免逐行遍历查找的低效操作,尤其适合数据量大的场景。 - 批量更新操作:使用
getRangeList()批量处理需要更新的行,比逐行调用setValue()效率提升显著。 - 边界条件处理:增加了对
query表是否有可复制行、Source表是否有数据的判断,避免空数据导致的报错。
内容的提问来源于stack exchange,提问作者Oliver Yu
相关产品推荐
相关产品推荐

