Episode #125 of the Stack Overflow podcast is here. We talk Tilde Club and mechanical keyboards. Listen now
1 of 4

How can I sort all worksheets in my Google spreadsheet on open?

I have successfully been able to sort the first sheet in my Google spreadsheet onOpen, but I'd like to sort all 4 spreadsheets onOpen and I can't make this work. I've tried quite a few variations in Script Editor, here's my latest:

function onOpen(){

var ss = SpreadsheetApp.getActiveSpreadsheet();

// Sorts the first sheet by the first column, ascending

var sheet = ss.getSheets()[0];

var tableRange = sheet.getRange("A3:L999"); // What to sort.

tableRange.sort({column: 1, ascending: true});

// Sorts the second sheet by the first column, ascending

var sheet1 = ss.getSheets()[1];

var tableRange1 = sheet1.getDataRange("A3:AC999"); // What to sort.

tableRange1.sort({column: 1, ascending: true});

// Sorts the third sheet by the first column, ascending

var sheet2 = ss.getSheets()[2];

var tableRange2 = sheet2.getDataRange("A3:N999"); // What to sort. tableRange2.sort({column: 1, ascending: true});

// Sorts the fourth sheet by the first column, ascending

var sheet3 = ss.getSheets()[3];

var tableRange3 = sheet3.getDataRange("A3:AC999"); // What to sort.

tableRange3.sort({column: 1, ascending: true});

}