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

如何将表格最后一行数据复制到另一表格并删除原数据行?

解决方案:复制源表格最后一行到目标表格并删除源行

原代码会复制指定的整个数据区域,无法满足只复制最后一行的需求,以下是修改后的代码,可实现你需要的功能:

function moveLastRow() {
  // 替换为你的源表格ID、源工作表名称
  const sourceID = "1PugO3VL8ZkGzA6stYfUkQK4WoU-FfRUBHUzRDTsEbYE";
  const sourceSheetName = "Sheet2";
  // 替换为你的目标表格ID、目标工作表名称、目标起始列(比如B列对应数字2)
  const destinationID = "1A2buwUnoDYVRILSETTFd_v6XGmrQtsGD-nT4P8Ufl_0";
  const destinationSheetName = "Sheet x";
  const destStartCol = 2; // B列对应数字2

  // 获取源表格及最后一行数据
  const sourceSS = SpreadsheetApp.openById(sourceID);
  const sourceSheet = sourceSS.getSheetByName(sourceSheetName);
  const lastSourceRow = sourceSheet.getLastRow();
  // 若源表格无数据,直接终止
  if (lastSourceRow === 0) return;
  const sourceRowRange = sourceSheet.getRange(lastSourceRow, 1, 1, sourceSheet.getLastColumn());
  const sourceRowValues = sourceRowRange.getValues();

  // 获取目标表格并写入数据到第一个空行
  const destinationSS = SpreadsheetApp.openById(destinationID);
  const destSheet = destinationSS.getSheetByName(destinationSheetName);
  const firstEmptyRow = destSheet.getLastRow() + 1;
  const destRange = destSheet.getRange(firstEmptyRow, destStartCol, 1, sourceRowValues[0].length);
  destRange.setValues(sourceRowValues);

  // 删除源表格中被复制的行
  sourceSheet.deleteRow(lastSourceRow);
}

关键修改说明

  • 精准取最后一行:用getLastRow()定位源表格的最后填充行,再通过getRange获取该行的所有有效列数据,避免复制空列
  • 定位目标空行:目标表格的第一个空行通过getLastRow() + 1获取,确保新数据不会覆盖已有内容
  • 删除源行:数据写入完成后调用deleteRow()删除源表格的目标行
  • 配置直观:直接在函数内定义表格ID和工作表参数,比原代码的拆分调用更易修改维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:01:40