9

So I've found the following answer in regards to auto-sorting by one column, which works great How can I make some data on a Google Spreadsheet auto-sorting?

However, my use case requires the sorting of two columns. One column is whole numbers, while the second column are dates. I would like to sort the whole numbers column first, then within each number sort the date.

Any suggestions?

9

Starting with the following line of code:

var range = sheet.getRange("A1:B10");

The sort can be performed in different ways:

  1. range.sort([1,2]);
  2. range.sort([{column: 1, ascending: true}, {column: 2, ascending: true}]);

Both ways are identical as the sort type is by default ascending, but the second option allows for different sort order when TRUE is changed to FALSE.

See reference: range.sort

  • 1
    Thanks for the quick response. Your answer makes sense to me. I've implemented the knowledge with success. – Viet Apr 16 '13 at 18:27
  • OK, new to this stuff...where exactly do I enter the above code? – user122792 May 4 '16 at 4:31
  • @robb see reference the OP uses, that Will lead to An answer I gave with explanation. – Jacob Jan Tuinstra May 4 '16 at 7:52
2

A bit late to the party but this is what I did.

function onEdit(event){
  var sheet = event.source.getActiveSheet();
  if(sheet.getName()=='Sort by country full'){
    var editedCell = sheet.getActiveCell();
    var columnToSortBy = 16;
    var columnToSortBy2 = 2;
    var tableRange = "A2:AU1451";
    if(editedCell.getColumn() == columnToSortBy){   
      var range = sheet.getRange(tableRange);
      range.sort( [{ column : columnToSortBy },{column: columnToSortBy2,ascending: false }] );
    }
  }
}

Sorts by column 16 first which for me is countries and then by a scoring rating in column 2 descending.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.