Home > Net >  Apps Script: Move SELECTED rows from one sheet to the last available rows of another sheet
Apps Script: Move SELECTED rows from one sheet to the last available rows of another sheet

Time:11-26

The code below is from here and was originally written by user @Cooper. All it does is that it copies the values of the columns specified in the array colA = [1,3,2,4] from SHEET 1 and add them to SHEET 2. I want to re-write the 2 last lines of the code, so that the values coming from SHEET 1 are added to the last available rows in SHEET 2. By "2 last lines", I mean these last lines of the code:
drng = des.getRange(1,1,drngA.length,drngA[0].length);//destination array controls size of destination range.drng.setValues(drngA);

Any idea how to get this done?

Thank you so much in advance for your help!

function Copy_data() 
{
  var src = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SHEET 1");
  var des = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SHEET 2");
  var srng = src.getDataRange(); 
  var srngA = srng.getValues(); 
  var drngA = [];
  var colA = [1,3,2,4];//indirect data column selection
  for (var i = 0; i < srngA.length;i   )
  {
    var k = 0;
    drngA[i]=[];
    for(var j=0;j<srngA[i].length;j  )
    {
        drngA[i][k  ] = srngA[i][colA[j]-1];
    }
    drng = des.getRange(1,1,drngA.length,drngA[0].length);//destination array controls size of destination range.
    drng.setValues(drngA);
  }
}

CodePudding user response:

You can get the last row of the destination Sheet and after, add it to your getRange() function. The method proposed by @soMario will not work because it makes requests inside the loop while you update the Sheet, and this causes it to get different values every time you call des.getLastRow().

The simplest solution is to take the getLastRow() request outside of the loop and then include it in getRange. Note that one is added to it so that it does not overwrite the last row with the setValue() request.

Code.gs
function Copy_data() {
    ...
    var lastRow = des.getLastRow()   1
    for (var i = 0; i < srngA.length;i   ){
    ...
    drng = des.getRange(lastRow,1,drngA.length,drngA[0].length)
    ...
}
Documentation
  • Related