It looks like you want to ensure that the sheet names in the Table of Contents (TOC) are sorted in alphabetical order from A to Z. The previous implementation already sorts the sheet names before adding them to the TOC, but I'll clarify and reinforce that this sorting is being done correctly.
Here's the complete code, which ensures that sheet names are sorted A-Z both when creating the TOC and when updating it:
function createTableOfContents() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheets = spreadsheet.getSheets();
var tocSheet = spreadsheet.getSheetByName("Table of Contents");
// Create a new "Table of Contents" sheet if it doesn't exist
if (!tocSheet) {
tocSheet = spreadsheet.insertSheet("Table of Contents", 0);
} else {
tocSheet.clear(); // Clear old contents if it exists
}
// Set header for the TOC
tocSheet.getRange("A1").setValue("Table of Contents").setFontWeight("bold");
// Collect sheet names and their IDs for sorting
var sheetData = [];
for (var i = 0; i < sheets.length; i++) {
sheetData.push({
name: sheets[i].getName(),
id: sheets[i].getSheetId()
});
}
// Sort sheetData alphabetically by sheet name (A-Z)
sheetData.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
// Loop through sorted sheetData and add links to the TOC
for (var j = 0; j < sheetData.length; j++) {
var sheetName = sheetData[j].name;
tocSheet.getRange(j + 2, 1)
.setValue(sheetName)
.setFormula('=HYPERLINK("#gid=' + sheetData[j].id + '", "' + sheetName + '")'); // Add hyperlink in TOC
}
// Add "Back to Contents" link in each sheet without modifying A1
for (var j = 0; j < sheets.length; j++) {
var currentSheet = sheets[j];
var cell = currentSheet.getRange("A1").setFontColor("Black");
var originalText = cell.getValue(); // Get original text
// Set Hyperlink in the cell with original text
cell.setFormula('=HYPERLINK("#gid=' + tocSheet.getSheetId() + '", "' + originalText + '")');
}
// Store the current sheet names in User Properties
var currentSheetNames = sheets.map(sheet => sheet.getName());
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('sheetNames', JSON.stringify(currentSheetNames));
}
// This function will run whenever a cell is edited
function onEdit(e) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var currentSheetNames = spreadsheet.getSheets().map(sheet => sheet.getName());
var userProperties = PropertiesService.getUserProperties();
var storedSheetNamesJson = userProperties.getProperty('sheetNames');
var previousSheetNames = storedSheetNamesJson ? JSON.parse(storedSheetNamesJson) : [];
// Check if the names of the sheets have changed
var hasChanged = false;
// Check for additions
if (currentSheetNames.length > previousSheetNames.length) {
hasChanged = true;
}
// Check for deletions
if (currentSheetNames.length < previousSheetNames.length) {
hasChanged = true;
}
// Check if there is a difference in names
if (hasChanged || !arraysEqual(currentSheetNames, previousSheetNames)) {
createTableOfContents();
}
}
// Helper function to compare two arrays
function arraysEqual(a1, a2) {
if (a1.length !== a2.length) return false;
return a1.every((value, index) => value === a2[index]);
}
Key Points:
- The sorting of
sheetData is done using localeCompare, which ensures the names are sorted in alphabetical order (A-Z).
- The link creation for the TOC uses the sorted names so that the TOC displays the sheets in the correct order.
- The update logic in the
onEdit function checks for any alterations in the sheet list, including additions and deletions, and it will regenerate the TOC as needed.
Usage
- Open your Google Sheets document.
- Click on
Extensions > Apps Script.
- Replace any existing code with the code provided above.
- Save the script and authorize it if prompted.
- Close the Apps Script Editor.
Now, whenever you add or delete a sheet, the TOC will update automatically, and the sheets will always be sorted alphabetically from A to Z in the TOC.