TDLR
Explanation:
Get all the sheet names,
replace:
var sheetNames = ["School Form 1 (SF1)", "SEPT-School Form 2 (SF2)", "OCT-School Form 2 (SF2)", "School Form 5 (SF5)"];
with:
var sheetNames = ss.getSheets().map(sh=>sh.getSheetName());
Then, if you only want to get the sheets that contain SF2
:
replace:
if (sheetNames.includes(sheetName))
with:
if (sheetNames.includes('SF2'))
If you want to have multiple filters, try this logic:
if (sheetNames.includes('SF2') || sheetNames.includes('SF5'))
The latter will evaluate to true
for all the sheets that contain SF2
or SF5
.
Solution 1:
var startRow = 11;
var colToCheck = 2;
// This script is the same with your "HideRows".
function script_HideRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetNames = ss.getSheets().map(sh=>sh.getSheetName());
sheetNames.forEach(sheetName => {
var sheet = ss.getSheetByName(sheetName);
if (sheetName.includes('SF2')) {
var numRows = sheet.getLastRow();
var elements = sheet.getRange(startRow, colToCheck, numRows).getValues();
for (var i=0; i < elements.length; i++) {
if (shouldHideRow(sheet, i, elements[i][0])) {
sheet.hideRows(startRow + i);
}
}
// Hide the rest of the rows
var totalNumRows = sheet.getMaxRows();
if (totalNumRows > numRows)
sheet.hideRows(numRows+1, totalNumRows - numRows);
}
});
}
Solution 2:
Another approach would be to filter on SF2
at the point you define the sheetNames
array. Using this approach you don’t need to iterate over all sheets, but only the relevant ones (that contain SF2
). Therefore, you don’t need an if
condition in the forEach
loop.
var startRow = 11;
var colToCheck = 2;
// This script is the same with your "HideRows".
function script_HideRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetNames = ss.getSheets().map(sh=>sh.getSheetName())
.filter(sheetName=>sheetName.includes('SF2'))
sheetNames.forEach(sheetName => {
var sheet = ss.getSheetByName(sheetName);
var numRows = sheet.getLastRow();
var elements = sheet.getRange(startRow, colToCheck, numRows).getValues();
for (var i=0; i < elements.length; i++) {
if (shouldHideRow(sheet, i, elements[i][0])) {
sheet.hideRows(startRow + i);
}
}
// Hide the rest of the rows
var totalNumRows = sheet.getMaxRows();
if (totalNumRows > numRows)
sheet.hideRows(numRows+1, totalNumRows - numRows);
});
}
Using the same logic as before, if you want multiple filters, do that:
var sheetNames = ss.getSheets().map(sh=>sh.getSheetName())
.filter(sheetName=>sheetName.includes('SF2') || sheetName.includes('SF5'))
CLICK HERE to find out more related problems solutions.