Search code examples
google-apps-scriptgoogle-sheets

CopyData and sort descending without first row


I wish to copy/paste data and sort the whole sheet without row 1 (I can simply lock it) by column A descending.

I can achive ascending sorting with:

function CopyData() {
      var ss = SpreadsheetApp.getActive();
      var sh1 = ss.getSheetByName("Auto");
      var sh2 = ss.getSheetByName("Test");
      var rg1 = sh1.getRange("A2:M10000");
      var vA = rg1.getValues().filter(r => r[5]);
      sh2.getRange(sh2.getLastRow() + 1, 1, vA.length, vA[0].length).setValues(vA);
      ss.getSheetByName("Test").sort(1);
    }

The question is, how can I make it sort descending by column A and is there a way to not include row 1 without locking it?


Solution

  • You can use replacing the last line. I divided it in more lines to be more clear:

     var testSh = ss.getSheetByName("Test")
     var sortRa = testSh.getRange("2:"+testSh.getLastRow())
     sortRa.sort([{column: 1, ascending: false}])
    

    You can use more sorting columns if needed:

    sortRa.sort([{column: 1, ascending: false},{column: 3, ascending: true}])