google-apps-scriptgoogle-sheetscopy-paste

How to copy a range of data to another google sheet using google apps script?


Source: enter image description here

Destination: enter image description here

Hi everyone,

I have 2 google sheets, Source & Destination. I want to copy a range of data from Source sheet to Destination sheet by using google apps script. So the data should appear at the last row of the Destination sheet. This is my code:

function copyInfo() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var copySheet = ss.getSheetByName("Source");
  var pasteSheet = ss.getSheetByName("Destination");

  // get source range
  var source = copySheet.getRange(3,1,1,10);
  // get destination range
  var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,1,10);

  // copy values to destination range
  source.copyTo(destination);

}

Seems like the script only allow me to do the copying within one google sheet (different tab) instead of 2 different google sheet. May I know how should I modified it so that the script able to find my destination google sheet and paste the data at the last row? Any help will be greatly appreciated!

Edit enter image description here

I tried to use onEdit to triggered the script, however it seems like not working. Below is my script:

function onEdit(e) {

  if (e.range.columnStart == 11 && e.range.rowStart == 3){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    const id ='1r5Hygl5ysahMi6DQ3duDR5L8c4aGX_0CJba7lXxnejw';
    var copySheet = ss.getSheetByName("Sheet1");
    var pasteSheet = SpreadsheetApp.openById(id).getSheetByName("Sheet1");
    
    if (e.value == 'Submit'){
      var source = copySheet.getRange(3,1,1,10);
      const values = source.getValues();
      var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,1,10);
      destination.setValues(values);
    }
  }
}

Source: https://docs.google.com/spreadsheets/d/1jnOvE-Dc7y9o7GsgN9fjOXZWlUCwiJayugX5q4Y3CA0/edit#gid=0

Destination: https://docs.google.com/spreadsheets/d/1r5Hygl5ysahMi6DQ3duDR5L8c4aGX_0CJba7lXxnejw/edit#gid=0


Solution

  • Use methods Range.getValues() and Range.setValues()

    const id ='ID of paste Spreadsheet here';
    var pasteSheet = SpreadsheetApp.openById(id).getSheetByName("Destination");
    var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,1,10);
    const values = source.getValues();
    destination.setValues(values);