Sometimes your Google Sheet tabs can get out of hand. They can be mixed up and confusing to users. It’s often necessary to simply sort them in ascending or descending order.
In this tutorial, we will use Google Apps Script to sort tabs in Google Sheets. We’ll also use a handy menu bar to quickly run the sort.
The approach below relies on a natural sort. In a normal sort where you also have numbers say:
"2. Cheese", "10. Pizza", "1. Bananas"
Then you ran your sort, you would not get what your expected but rather:
"1. Bananas", "10. Pizza", "2. Cheese"
With a natural sort, we consider the number numerically, rather than as characters. This means our sort would come out as expected:
"1. Bananas", "2. Cheese", "10. Pizza"
You can learn more about creating the Apps Script by following the video below or you can jump down and grab a copy of your code and run it in your own project.
You can grab the starter Google Sheet Here:
Sort Tabs in Google Sheets – Video
The Code
Step 1: In your Google Sheet, Go to Extensions > Apps Script.
Step 2: copy the code from below and paste it into the edits and save.
Step 3: Next, reload the Google Sheet. You will see a menu item called Extras. Click it and you will see your two sort options.
Step 4: Go ahead and click an option.
You should see your tabs being sorted.
Step 5: You will be prompted to run authorisation of the script the first time the script is run. You can learn more about this here:
Step 6: Select an option again and you will see the tabs being sorted.
If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/** * Creates a menu item for ascending and descending sheet tab sort. */ function onOpen(){ const ui = SpreadsheetApp.getUi() ui .createMenu("Extras") .addItem("Sort tabs Asc","tabSorter.ascending") .addItem("Sort tabs Desc","tabSorter.descending") .addToUi() } /** * Object container to direct tab sorts for either ascending or descening order. */ const tabSorter = { ascending: function(){this.sortTabs(true)}, descending: function(){this.sortTabs(false)}, /** * Naturally sort tabs. This means where there are number, * the sort will order them in numerical order. e,g, 1, 2, 10, "Car", "Goat" * @param {boolean} isAscending - if true will sort ascending, otherwise descending. */ sortTabs: function(isAscending){ const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheets = ss.getSheets(); // Enable language sensitive string comparison. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator const collator = new Intl.Collator(undefined, { numeric: true, // Sets numeric collation so 1 < 2 < 10 sensitivity: 'base' // Ignores accents and other diacritic marks in lettering. }); // Sorts the sheet. let sheetNames = sheets.sort((a,b) => { // Compares first sorted sheet name value against last sorted sheet name value. return collator.compare(a.getName(), b.getName()) }) // If set to descending the sheetNames lists is ignored. sheetNames = (!isAscending)? sheetNames.reverse(): sheetNames; // Iterates through each sheet sets it to activve and updates it order. sheetNames.forEach((sheet, idx) => { ss.setActiveSheet(sheet) ss.moveActiveSheet(idx + 1) // Sheet tab indexes start from one so we must add one. }); } }; |
Need help with Google Workspace development?
Go something to solve bigger than Chat GPT?
I can help you with all of your Google Workspace development needs, from custom app development to integrations and security. I have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
Schedule a free consultation today to discuss your needs and get started or learn more about our services here.
Code Breakdown
onOpen()
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * Creates a menu item for ascending and descending sheet tab sort. */ function onOpen(){ const ui = SpreadsheetApp.getUi() ui .createMenu("Extras") .addItem("Sort tabs Asc","tabSorter.ascending") .addItem("Sort tabs Desc","tabSorter.descending") .addToUi() } |
The onOpen()
function is a Google Apps Script simple trigger that runs automatically when the user opens the Google Sheet.
Line 5: In our example, we call the Spreadsheet App UI class, so that we can build the menu.
Line 8: To create a menu we use the Create Menu method and add the menu label “Extras” as an argument.
Lines 9-10: Next, we can add menus to the main menu header with the Add Item method. These menus take a menu label and then a function or an object method that will run when the menu is selected. Ensure that you don’t include parentheses in these arguments and contain them in a string.
Line 11: Finally, we need to build the menu by adding all the menu items to the UI.
You can learn more about building menus in Google Sheets, Docs and Slides here:
The Sheet Tab Sorter object
The tabSorter object contains 3 properties:
ascending
descending
sortTab
1 2 3 4 5 6 7 8 |
const tabSorter = { ascending: <em>method</em>, descending: <em>method</em>, ... sortTabs: <em>method</em> ... |
Ascending and Descending Property Methods
Both of these property methods run the sortTabs
method providing either true for ascending or false for descending as the argument.
We need to encapsulate these method calls inside their own anonymous functions so that they don’t run automatically when the menu is loaded.
ascending: function(){this.sortTabs(true)},
descending: function(){this.sortTabs(false)},
The sort Google Sheet Tabs machine (sortTabs)
The sortTabs
property does all the heavy lifting in this object.
It takes a boolean as an argument that will determine if the sort is ascending or descending.
Get a list of sheets
1 2 3 |
const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheets = ss.getSheets(); ss.sheet |
Our first task is to get an array containing all the Google Sheets in the currently active sheet. We can do this with the SpreadSheet App Get Sheets method. This will contain an array with all the methods available for each found sheet tab.
Using Intl Collator for natural sorting
We want to sort our sheet tabs naturally just in case we have numbers in the name of the tab (e.g. “1”, “2”, “4. Cake”). We can do this with the JavaScript Intl.Collator
object to sort the sheet tabs in a natural order, meaning that numeric values are sorted in numerical order and text values are sorted alphabetically. You can modify this function to use a different sorting algorithm or change the sorting order.
1 2 3 4 |
const collator = new Intl.Collator(undefined, { numeric: true, // Sets numeric collation so 1 < 2 < 10 sensitivity: 'base' // Ignores accents and other diacritic marks in lettering. }); |
Line 2: Here, we create a new Intl.Collator
constructor. The first optional parameter of the constructor defines the locale or language tab. We don’t need this option, so we set it to ‘undefined’.
The second parameter sets the options for the collator.
Line 3: First, we use the numeric property and set it to true. This will allow us to order the numbers properly so that 1 < 2 <10.
Line 4: Secondly, we set the sensitivity to base. This means that we do not take into account any accents or other markings on letter characters. If you are using this Google Sheets sort tab code in other languages, then you might want to modify this.
Sort Google Sheet tabs Apps Script-side
Now that we have our collator set up we use the JavaScript sort method to sort through the array of sheet names.
1 2 3 4 5 |
// Sorts the sheet. let sheetNames = sheets.sort((a,b) => { // Compares first sorted sheet name value against last sorted sheet name value. return collator.compare(a.getName(), b.getName()) }) |
Line 2: Here, we use an arrow function with a standard a, b parameter set. These parameters refer to the first and second elements of comparison respectively.
Line 3: Use our collator and apply the compare method to compare the sheet names against each other.
Reversing the sort
1 2 |
// If set to descending the sheetNames lists is ignored. sheetNames = (!isAscending)? sheetNames.reverse(): sheetNames; |
If isAscending
parameter of the sortTabs
method is set to false, then we use JavaScript reverse()
to reverse the array order of the sheetNames
.
Updating the Google Sheet tabs to the desired order
Finally, once our array is in the desired order we need to update the Google Sheet with the new tab order.
1 2 3 4 5 6 7 |
// Iterates through each sheet sets it to activve and updates it order. sheetNames.forEach((sheet, idx) => { ss.setActiveSheet(sheet) ss.moveActiveSheet(idx + 1) // Sheet tab indexes start from one so we must add one. }); |
Line 2: First, we loop through the sheet names array with the JavaScript forEach() method.
Line 3: Inside each loop, we need to set the active sheet to the currently iterated sheet.
Line 4: Finally, we move the active sheet to the next position in the sheet tabs. Note that sheet indexes start from one (1) however our array index starts from zero (0). This is why we need to add one to the index.
Starting the sort after a set number of tabs
Perhaps you have an instruction tab or dashboards that you want to leave to the left of your sort. Here you can update the moveActiveSheet() by increasing the value to add to the index by the desired number plus 1.
Let’s say I have an ‘Instructions’ tab and a ‘Dashboard Tab’ that I want to keep to the far left and is not included in my sort list. my moveActievSheet() function would look like this:
1 |
ss.moveActiveSheet(idx + 3) |
Here I add 1 to the zero-based index and another 2 for the two tabs I want to keep in position.
Google Sheet Tabs by Date
Check out my bonus video on sorting tabs by leading date.
The Starter Sheet
That’s all there is to it.
If you want to learn more about how to modify Google sheets tabs with Apps Script, check out these tutorials:
- Get Hidden or Visible Google Sheet Tabs with Google Apps Script
- Duplicate Filter Views in Selected Google Sheet Tabs with Google Apps Script
If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.
Changelog
2024-05-31
- Added table of contents.
- Added video on sorting Google Sheet Tabs by leading date.
- Added chapter on keeping static sheet tabs to the right and sorting after them. Thanks to Cassidy for the question.