Search code examples
google-apps-scriptgoogle-sheetscopy-paste

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


I have a need to create a script that copies Rows 4:8 and then whatever the last row of the sheet is, paste those rows in.

NOTE - To keep the file small, the sheet has the majority of the rows deleted on purpose. The last row may not always be the same number, so the script must know which the last row is even if there's no data in it.

EXAMPLE

If the last row is 20, upon executing the script (which I'll assign to a button), 5 additional rows will be added (which would have come from rows 4:8), extending the sheet to a total of 25 rows.

There's specific formatting in those rows so it's not as simple as just adding 5 additional rows, they must be copies of rows 4:8.

Thanks.


Solution

  • Copy Lines to Bottom including format

    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

    Demo:

    enter image description here

    Modified to included row heights

    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 ));
    }