google-sheetsgoogle-apps-scripttriggers

Renaming Sheet Tab Based on Cell Value


I am trying to have all tabs in a spreadsheet renamed based on the value of a specific cell within each tab.

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var oldName = sheet.getName();
  var newName = sheet.getRange(1,1).getValue();
  if (newName.toString().length>0 && newName !== oldName) {
    sheet.setName(newName);
  }
}function myFunction() {

}

This works when I edit it, but I would like it to a) just do it automatically based on a trigger setting (it updates every hour based on the cell value) AND for it to happen to ALL sheets (call them '1', '2', and '3') within a spreadsheet based on the value of cell A1 in each sheet. The above code seems to only work on one tab and only on edit.


Solution

  • You can use a time-driven trigger.


    It would be best to learn about triggers in Google Apps Script by reading the official guides:

    You might also need to learn the basics of JavaScript, in this case, more specifically about loops.

    To iterate over all the sheets, you might use the SpreadsheetApp.Spreadsheet.getSheets() method to get an array of sheets. Then you might use Array.prototype.forEach to iterate over them.

    Example:

    function changeSheetsNames(e = {source : SpreadsheetApp.getActiveSpreadsheet() } ){
    
       e.source.getSheets().forEach(sheet => {
         const oldName = sheet.getName();
         const newName = sheet.getRange(1,1).getValue();
         if (newName && newName !== oldName) {
           sheet.setName(newName);
         }
       });
    }
    

    In this case, it's best to create the trigger manually. Please follow the official guide for this.