Skip to content

Instantly share code, notes, and snippets.

@bytrangle
Last active October 14, 2020 13:01
Show Gist options
  • Save bytrangle/52e13faada8eb429fac734e2a61c0adf to your computer and use it in GitHub Desktop.
Save bytrangle/52e13faada8eb429fac734e2a61c0adf to your computer and use it in GitHub Desktop.
Sort Google Sheets worksheets by name. Useful when you have more than 8 worksheets inside a spreadsheet.
/* INSTRUCTION
- On your spreadsheet, go to Tools > Script Editor to open the Script Editor in a new tab.
- Paste the code below, starting from the double slash to the end into any file that ends with .gs extension.
- Save the .gs file and reload your spreadsheet to see the new menu.
*/
// This creates a menu which contains menu item that when clicked will trigger the function to sort worksheets by name.
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Utils')
.addItem('Sort Worksheets By Name', 'sortWorksheetsByName')
.addToUi();
}
function sortWorksheetsByName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetArr = [];
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
sheetArr.push(sheets[i].getName());
};
sheetArr.sort();
Logger.log(sheetArr);
for (var j = 0; j < sheets.length; j++) {
ss.setActiveSheet(ss.getSheetByName(sheetArr[j]));
ss.moveActiveSheet(j + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment