Google Sheets – Loop Through All Sheets Except Specific Names

google sheetsgoogle-apps-scriptjavascript

I found the following code and want to use it to loop through all the sheets expect a few (that I don't want it to go through).

My question is how can I edit this code in such a way that It does not loop through to the sheets example "Setting" "Help" "FAQ"

function myFunction() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]

//your  code here ...

}//end of  sheets loop.
}// end of function...

Best Answer

If you are using for loop you could use continue to terminate the execution of the current iteration.

A way to implement the above by using an if statement and || (logical OR)

function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();
  for(var s in allsheets){
    var sheet = allsheets[s];

    // Stop iteration execution if the condition is meet.
    if(
       (sheet.getName() == "Setting") || 
       (sheet.getName() == "Help") || 
       (sheet.getName() == "FAQ") 
      ) continue;

    //your code here

  } // end of loop

} // end of function

A more elegant way to do the same is:

function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude = ["Setting","Help","FAQ"];

  for(var s in allsheets){
    var sheet = allsheets[s];

    // Stop iteration execution if the condition is meet.
    if(exclude.indexOf(sheet.getName())==-1) continue;

    //your code here

  } // end of loop

} // end of function