0
votes

I'm working on a script that will copy a certain range of Sheet A and paste it in Sheet B after the last record, I know it should be pretty easy, but somehow the code is not working, could you please advise me on what am I doing wrong here, it will clear the contents of the cell, but copy partially the data from Sheet A to Sheet B

function Export2() {

     var ss = SpreadsheetApp.getActiveSpreadsheet()
      var database = SpreadsheetApp.openById("XXX");
     var source = ss.getSheetByName('Sheet1');
       var dataToCopy = source.getRange('B2:G10');
      var copyToSheet = database.getSheetByName("Sheet2");
      var lastRow = copyToSheet.getLastRow();
      for (var i = 1; i<6 ;i++){
        var Paste = copyToSheet.getRange(lastRow + 1,i).setValues(dataToCopy.getCell(1,i).getValues());
    }

    var Clean = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange('B2:G10');
                Clean.clear({contentsOnly:true});
    }
2

2 Answers

1
votes
function Export2() {
  var svA=SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2,2,9,6).getValues()
  var dsh=SpreadsheetApp.openById('1AqQyqMQNnYvbFoU0HQ4WtjqkKtfxkj15Y6iXG6lCWkI').getSheetByName('Sheet2')
  dsh.getRange(dsh.getLastRow()+1,1,svA.length,svA[0].length).setValues(svA);
}
0
votes
  • You want to copy the values of the range B2:G10 on Sheet1 in the active Spreadsheet to the last row of Sheet2 in the other Spreadsheet using Google Apps Script.
  • After the values were copied, you want to clear the cells of the range B2:G10 on Sheet1 in the active Spreadsheet.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

  • In your current script, only values of "B2:F2" of the source sheet are copied. So in this case, at first, retrieve the source values from the range B2:G10 on Sheet1 in the active Spreadsheet. Then, put the values to the destination range.
  • In order to clear the range B2:G10 on Sheet1 in the active Spreadsheet, you can also use dataToCopy of var dataToCopy = source.getRange('B2:G10').

Modified script:

When your script is modified, it becomes as follows.

function Export2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var database = SpreadsheetApp.openById("XXX");
  var source = ss.getSheetByName('Sheet1');
  var dataToCopy = source.getRange('B2:G10');
  var copyToSheet = database.getSheetByName("Sheet2");

  // I modified below script.
  var sourceValues = dataToCopy.getValues();
  var lastRow = copyToSheet.getLastRow();
  copyToSheet.getRange(lastRow + 1, 1, sourceValues.length, sourceValues[0].length).setValues(sourceValues);
  dataToCopy.clear({contentsOnly:true});
}

If I misunderstood your question and this was not the result you want, I apologize.