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

需求:编写Google Sheets脚本将指定区域按D2数值向上粘贴n次

Google Sheets 脚本实现指定次数向上粘贴带格式区域

以下脚本可实现复制A5:G10区域(包含所有格式),并根据D2单元格的数值n,向上粘贴n次:

function pasteUpMultipleTimes() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // 读取D2中的粘贴次数
  const pasteCount = sheet.getRange("D2").getValue();
  
  // 校验输入合法性
  if (pasteCount <= 0 || !Number.isInteger(pasteCount)) {
    SpreadsheetApp.getUi().alert("D2单元格必须输入正整数");
    return;
  }
  
  // 定义要复制的源区域
  const sourceRange = sheet.getRange("A5:G10");
  const rowCount = sourceRange.getHeight();
  const colCount = sourceRange.getWidth();
  
  // 预存源区域的内容和所有格式属性
  const sourceValues = sourceRange.getValues();
  const sourceNumberFormats = sourceRange.getNumberFormats();
  const sourceBackgrounds = sourceRange.getBackgrounds();
  const sourceFontFamilies = sourceRange.getFontFamilies();
  const sourceFontSizes = sourceRange.getFontSizes();
  const sourceFontWeights = sourceRange.getFontWeights();
  const sourceHorizontalAlignments = sourceRange.getHorizontalAlignments();
  const sourceVerticalAlignments = sourceRange.getVerticalAlignments();

  // 循环执行粘贴操作
  for (let i = 0; i < pasteCount; i++) {
    const insertPosition = 5;
    // 在A5行前插入与源区域行数相同的空行
    sheet.insertRowsBefore(insertPosition, rowCount);
    // 获取新插入的目标区域
    const targetRange = sheet.getRange(insertPosition, 1, rowCount, colCount);
    // 给目标区域设置预存的内容和格式
    targetRange.setValues(sourceValues);
    targetRange.setNumberFormats(sourceNumberFormats);
    targetRange.setBackgrounds(sourceBackgrounds);
    targetRange.setFontFamilies(sourceFontFamilies);
    targetRange.setFontSizes(sourceFontSizes);
    targetRange.setFontWeights(sourceFontWeights);
    targetRange.setHorizontalAlignments(sourceHorizontalAlignments);
    targetRange.setVerticalAlignments(sourceVerticalAlignments);
  }
}

关键说明

  • 输入校验:确保D2是正整数,避免无效操作引发错误。
  • 预存格式:提前保存源区域的内容与格式,防止插入行后源区域位置偏移,保证每次粘贴的都是初始的A5:G10内容。
  • 循环逻辑:每次在当前第5行前插入对应行数的空行,再将预存内容和格式应用到新行,实现向上粘贴的效果。

使用方法

  1. 打开目标Google表格,点击「扩展程序」>「Apps脚本」。
  2. 清空编辑器默认代码,粘贴上述脚本。
  3. 点击保存,为项目命名(比如PasteUpMultipleTimes)。
  4. 返回表格页面刷新,点击「扩展程序」中创建的脚本名称,按提示完成授权后即可运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:25:29