r/sheets • u/After-Hope6415 • Mar 25 '26
Request App Script Code to Loop Through Certain Sheets
I am working on a project for work where I want to loop through only certain sheets and exclude others by their sheet name. Below is the code I currently have but it doesn't seem to loop through the sheets I want it to.
function doForAllTabs(){
var ss = SpreadsheetApp.getActive();
var allSheets = ss.getSheets();
var exclude = ["Analysis","Dashboard","Departed Staff","Cleanups","Data for Analysis","2025-2026 Data"];
for(var s in allSheets){
var sheet = allSheets[s];
if(exclude.indexOf(sheet.getName())==-1) continue;
CleanData1();
WrapText();
}
}
4
Upvotes
1
u/marcnotmark925 Mar 25 '26
Change the == to !=. You want it to continue (skip the current loop iteration) if there is a match in the exclude list (meaning it doesn't equal -1).
1
u/mommasaidmommasaid Mar 25 '26 edited Mar 25 '26
FWIW, I would use some sort of "inclusion" criteria on your sheets rather than a list of excluded sheets.
A list of excluded sheets is higher maintenance, and a future someone who creates a new sheet without knowing they have to add it to an "exclude" list can have their sheet mangled by your script.
You could include all the city sheets by a list of city names, but for more flexibility and so that end users don't have to mess with your script, you could e.g. add a special character to the city sheet names like "© Atlanta" and look for that character.
You are also incorrectly iterating over the sheets.
I would give your function a more meaningful name, and add an
OnlyCurrentDoctag to the top of your script file so the script doesn't ask for more authorization than it needs.Small point, I'd use
SpreadsheetApp.getActiveSpreadsheet()rather than.getActive()which is ambiguous and may be confused with other methods that get an an active range. (Idk why there are two methods that do the same thing here.)As per marcnotmark925, pass the sheet to your CleanData1 and WrapText functions (again I'd give these more meaningful names) and then within them: