google-apps-scriptgoogle-sheetsgoogle-sheets-macros

How to copy a range of selected data to after the lastRow of data in the same Sheet using Google Apps Script?


I selected manually a range of data and want to press a button to copy those data to after the last row of data in the same sheet using Google Apps Script but not working at all. How to fix it? The codes are:

var listToCopy = SpreadsheetApp.getActiveSheet().getActiveRange();
  var height = listToCopy.getHeight();
  var destRow = listToCopy.getLastRow()+1;
  listToCopy.copyTo(spreadsheet.getRange(destRow, 0, height));

Solution

  • I believe your goal as follows.

    For this, how about this answer?

    Modification points:

    When above points are reflected to your script, it becomes as follows.

    Modified script:

    In order to use this script, please select the range and run the function of myFunction. By this, the selected range is copied to the last row of the same sheet.

    function myFunction() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var listToCopy = sheet.getActiveRange();
      var destRow = sheet.getLastRow() + 1;
      listToCopy.copyTo(sheet.getRange(destRow, 1));
    }
    

    References: