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

Google Sheets脚本求助:按用户输入复制最后一行功能失效

问题排查与修复

核心问题

你代码里的小于号(<)被转成了HTML转义字符&lt;,这会导致脚本出现语法错误,duplicateRows函数无法正常执行,自然不会复制行。

修复后的完整代码

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Custom Menu')
    .addItem('Duplicate Rows', 'showDialog')
    .addToUi();
}

function showDialog() {
  const ui = SpreadsheetApp.getUi();
  const response = ui.prompt('Duplicate Rows', 'How many rows would you like to duplicate?', ui.ButtonSet.OK_CANCEL);

  if (response.getSelectedButton() === ui.Button.OK) {
    const numRows = parseInt(response.getResponseText());
    if (isNaN(numRows) || numRows < 1) {
      ui.alert('Invalid input. Please enter a valid number greater than 0.');
      return;
    }
    duplicateRows(numRows);
  }
}

function duplicateRows(numRows) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const lastRow = sheet.getLastRow();
  const sourceRange = sheet.getRange(lastRow, 1, 1, sheet.getLastColumn());
  
  // 一次性插入多行再复制,比循环逐行操作更高效
  sheet.insertRowsAfter(lastRow, numRows);
  const destinationRange = sheet.getRange(lastRow + 1, 1, numRows, sheet.getLastColumn());
  sourceRange.copyTo(destinationRange, SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}

额外优化说明

  • 把循环逐行复制改成一次性插入多行+批量复制,减少对Google服务的调用次数,提升执行效率(Google Apps Script对服务调用次数有配额限制)。
  • 使用copyTo方法可以直接复制格式、公式等内容,比setValues更完整还原原行的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:52:19