Google Sheets 脚本 - 复制行 4:8 并粘贴到 Sheet 的最后一行

Google Sheets Script - Copy Rows 4:8 and Paste to Last Row of the Sheet

我需要创建一个脚本来复制行 4:8 然后无论 sheet 的最后一行是什么,都将这些行粘贴到其中。

注意 - 为了保持文件小,sheet 有意删除了大部分行。最后一行可能不总是相同的数字,因此即使其中没​​有数据,脚本也必须知道最后一行是哪一行。

示例

如果最后一行是 20,在执行脚本(我将分配给一个按钮)时,将添加 5 个额外的行(它们将来自行 4:8),扩展 sheet 到总共 25 行。

这些行中有特定的格式,所以它不像添加 5 行那么简单,它们必须是行的副本 4:8。

谢谢。

function copyrow_4_8(){
        const ss = SpreadsheetApp.getActive().getActiveSheet();
        //replace the columns number with your acutal needed columns 
        const range = ss.getRange(4,1,5,4);
        const range_value = range.getValues();
        const dest_range = ss.getRange(ss.getLastRow()+1,1,range_value.length,range_value[0].length);
        //get grid id for the dest range
        const dest_range_Gid = dest_range.getGridId();
        //copy format to the dest range
        range.copyFormatToRange(dest_range_Gid,1,4,ss.getLastRow()+1,ss.getLastRow()+range_value.length+1);
        //set the values to dest range.
        dest_range.setValues(range_value);
    }
  1. 您需要获取原始范围和值
  2. 然后将格式和值复制到目标范围。

将行复制到底部,包括格式

function copyrows() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const rg = sh.getRange("4:8");//select line 4 through 8
  const drg = sh.getRange(sh.getLastRow() + 2 , 1);//Select destination range. You only have to specify the upper left corner of the range
  rg.copyTo(drg);
}

copyTo

演示:

修改为包括行高

function copyrows() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const rg = sh.getRange("4:8");//select line 4 through 8
  let hA = [...Array.from(new Array(rg.getHeight()).keys(),x => sh.getRowHeight(x + 4))]
  let lr = sh.getLastRow();
  const drg = sh.getRange(lr + 2 , 1);//Select destination range. You only have to specify the upper left corner of the range
  rg.copyTo(drg);
  hA.forEach((h,i) => sh.setRowHeight(lr + 1 + i, h ));
}