Home > other >  Google Apps Script - FUNCTION renaming all sheets with specific cell value
Google Apps Script - FUNCTION renaming all sheets with specific cell value

Time:04-17

I'm using this function to rename the active sheet according to the cell value in B4 - but I want to do this for the whole spreadsheet, each sheet should be renamed to it's own specific cell value in B4. Could anyone tell me how to implement this with a FOR loop e.g. ?!Thanx!

function RenameSheetsM() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet(); // active Sheet = Tab
  var cell = sheet.getRange("B4");// cell B4 = Name  
  var value = cell.getValue();//Added
  sheet.setName(value);//Sheet name changed
}

CodePudding user response:

It can be something like this:

function main() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (let sheet of sheets) {
    RenameSheetsM(sheet);
  }
}

function RenameSheetsM(sheet) {
  var cell = sheet.getRange("B4");// cell B4 = Name  
  var value = cell.getValue();//Added
  sheet.setName(value);//Sheet name changed
}

But I prefer a loop while() mostly, it looks neat:

function main() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  while (sheets.length) {
    var sheet = sheets.shift();
    var cell = sheet.getRange("B4");
    var value = cell.getValue();
    sheet.setName(value);
  }
}

CodePudding user response:

function RenameSheetsM() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (i=0; i<sheets.length; i  ) {
    var value = sheets[i].getRange("B4").getValue();
      if(sheets[i].getName() != value){
        sheets[i].setName(value);
      }    
  }
}
  • Related