Search code examples
google-apps-scriptcopy-paste

Copy and Paste to the next Column + Last Row (GOOGLE SCRIPT)


I would like to copy and paste to the next column + last row. I try below but doesn't work and please see sample picture

function CopyPasteFrTo() {
  var ss=SpreadsheetApp.getActive();
  var shfr=ss.getSheetByName('From');
  var shto=ss.getSheetByName('To');
  shfr.getRange('A1:N').copyTo(shto.getRange("A1"), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  shfr.getRange('A2:F').copyTo(shto.getRange(shto.getLastRow()+1,1), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  shfr.getRange('K2:N').copyTo(shto.getRange(shfr.getLastColumn()+1,7), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  shfr.getRange('G2:J').copyTo(shto.getRange(shfr.getLastColumn()+1,11), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

see sample here


Solution

  • I believe your goal as follows.

    • When I saw your sample image, it seems that you want to copy the values in the same sheet. But when I saw your script, you want to copy the values from "From" to "To" sheet. From this situation, I would like to believe your goal as your sample image.
    • In your sample image, for the same sheet,
      • You want to copy the cells "A2:F" (last row of the data range.) to the column "A" of the next row of the last row.

      • You want to copy the cells "K2:N" (last row of the data range.) to the column "G" of the next row of the last row.

      • You want to copy the cells "G2:J" (last row of the data range.) to the column "K" of the next row of the last row.

      • Your sample image is as follows (This is from your question.).

    Sample script:

    function myFunction() {
      const sheetName = "Sheet1";  // Please set the sheetname.
    
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
      const lastRow = sheet.getLastRow();
      sheet.getRange("A2:F" + lastRow).copyTo(sheet.getRange("A" + (lastRow + 1)));
      sheet.getRange("K2:N" + lastRow).copyTo(sheet.getRange("G" + (lastRow + 1)));
      sheet.getRange("G2:J" + lastRow).copyTo(sheet.getRange("K" + (lastRow + 1)));
    }
    

    Reference: