Google script - Sheets - sort - how to avoid sorting the first row?

Viewed 3348

A stupid thing that got me cracking my head. I'm sure you'll laugh, but how do I sort a sheet without including the first row in the sort?

Here's my code:

 var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test1");
 spreadsheet.sort(4); // or  spreadsheet.sort(4,false); or  spreadsheet.sort(4,true);

This sorts by column D, but it also sorts the first row. Column D contains only text.

Funny thing is that if you sort a column which has just numbers/dates, it works and it indeed avoids sorting the first row.

So, how can I sort a column with text and avoid sorting the first row?

I know that I can set a range start at A2 until the last column but this seems "messy". Something like this

spreadsheet.getRange('A2:AI').sort({column: 4, ascending: true});

Thanks

2 Answers

What about this solution:

Freeze the header row and then perform the sorting operation.

In this way it's easy and readable to select the row that will contain the headers of your spreadsheet and you can apply all the sorting operations with a cleaner syntax:

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test1");
spreadsheet.setFrozenRows(1);
spreadsheet.sort(4);

Reference

.setFrozenRows()

You'll probably find this "messy" too but maybe you could save the first item, sort your column and insert back the first item ?

About the working sort of dates/numbers, maybe the sheet detects that the first cell is the only different one (not a number or a date) and then don't sort it ?

Related