简体   繁体   中英

Copy range to another sheet with Google Appscript

I have written a script that aims at copying a range of data from one sheet to two other separate sheets, one after the other. The data I want to copy is in a sheet called "New entries for the Database". The destination sheets are "BackEndDatabase" and "New Stores for the week".

The script is working fine for the first sheet but doesn't do the same fot eh second one. So, it runs and copies the correct data into the "BackEndDatabase" sheet but does nothing in the "New Stores for the week" sheet. I am not sure what I might be doing wrong. The correct SHEET IDs are being used in both instances.

The script is as follows:

  function addnewentries() {

  var sh = SpreadsheetApp.openById('SHEET_ID').getSheetByName('New Entries for Database')
    var range = sh.getDataRange().offset(0, 0);
    var data = range.getValues();
    var ts = SpreadsheetApp.openById('SHEET_ID').getSheetByName('BackEndDatabase')
    ts.getRange(ts.getLastRow() + 1, 1, data.length, data[0].length).setValues(data);
    var ts1 = SpreadsheetApp.openById('SHEET_ID').getSheetByName('New Stores for the week')
    ts1.getRange(ts1.getLastRow() + 1, 1, data.length, data[0].length).setValues(data);

Thank you.

try this:

function addnewentries() {

  var sh = SpreadsheetApp.openById('SHEET_ID').getSheetByName('New Entries for Database')
  var range = sh.getDataRange();//offset not needed
  var data = range.getValues();
  var ts = SpreadsheetApp.openById('SHEET_ID').getSheetByName('BackEndDatabase');//missing semicolon

  ts.getRange(ts.getLastRow() + 1, 1, range.getHeight(), range.getWidth()).setValues(data);//use Height and Width of the range in case first row has fewer columns
  var ts1 = SpreadsheetApp.openById('SHEET_ID').getSheetByName('New Stores for the week');//missing semicolon
  ts1.getRange(ts1.getLastRow() + 1, 1,range.getHeight(), range.getWidth()).setValues(data);//again use Height and Width of the range in case first row has fewer columns
}

Take a look at the comments for each line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM