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

Google Apps Script跨表复制时报lastrow.setValues is not a function错误

问题解决方案

错误根因

  • 你定义的lastrow是数字类型的行索引值,只有Range类实例才支持setValues、setBackgrounds这类格式/内容写入方法,直接对数字调用API方法自然会抛出类型错误。
  • 原有遍历判断最后一行的逻辑冗余,Google Apps Script内置Sheet.getLastRow()方法可直接获取工作表最后一个有内容的行号,无需自行遍历实现。

修正后可运行代码

function myfunction() {
  // 识别源表、目标表
  const sourcesheet = SpreadsheetApp.getActiveSpreadsheet();
  // 替换下方的page_url为你实际的目标表格链接
  const destination = SpreadsheetApp.openByUrl("page_url");

  // 定义源表待复制、待清空的区域
  const ws  = sourcesheet.getSheetByName("Récap");
  const source_range_to_delete = ws.getRange("D11:N22");
  const source_range_to_copy = ws.getRange("A43:N54");
  // 获取待复制区域的行列数,用于匹配目标写入区域大小
  const copyRowCount = source_range_to_copy.getNumRows();
  const copyColCount = source_range_to_copy.getNumColumns();

  // 定位目标表待写入区域
  const destpage = destination.getSheetByName("Feuille 1");
  const lastFilledRow = destpage.getLastRow();
  const destWriteRange = destpage.getRange(lastFilledRow + 1, 1, copyRowCount, copyColCount);

  // 读取源区域内容和格式
  const values = source_range_to_copy.getValues();
  const bgColors = source_range_to_copy.getBackgrounds();
  const fontColors = source_range_to_copy.getFontColors();
  const fontSizes = source_range_to_copy.getFontSizes();

  // 写入到目标区域
  destWriteRange.setValues(values);
  destWriteRange.setBackgrounds(bgColors);
  destWriteRange.setFontColors(fontColors);
  destWriteRange.setFontSizes(fontSizes);

  // 清空源表指定区域内容
  source_range_to_delete.clearContent();
}

补充说明

  • 若目标表Feuille 1完全为空,getLastRow()会返回0,内容会从第一行开始写入,符合使用逻辑。
  • clearContent()方法本身仅清空单元格内容保留格式,无需额外传参;如果需要同时清空格式可替换为clear()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:39:01