Google-sheets – Change function from running only on Active Sheet to run on All Sheets (tabs)

google sheetsgoogle-apps-script

I have a script (from here) that changes tab name based on cell value. This works great on the active sheet but I would like it to check and change all tabs based on cell B2 of 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);
  }

I've researched and cannot quite figure out how to make a script run across all tabs.

Best Answer

Spreadsheet, the class representing the workbook, has a function that returns an array of all tabs:

   function onEdit() {
      var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
      for(var i = 0; i <sheets.length; i++){
        var oldName = sheets[i].getName();
        var newName = sheets[i].getRange("b2").getValue();
        if (newName.toString().length>0 && newName != oldName) {
          sheets[i].setName(newName);
        }
      }
    }