Home > Mobile >  Delete Last X Number of Sheets, But Exclude Certain Sheets by Name
Delete Last X Number of Sheets, But Exclude Certain Sheets by Name

Time:01-12

I am trying to delete the sheets greater than X, while also excluding certain sheets by name from being deleted as well as from being part of the total sheet count. I have modified the code below 100 different ways, and cannot seem to get it to work correctly.

For Example:

I have 20 total sheets 1 template sheet I want to delete sheets > 10 while excluding the template sheet based on sheet name This would leave me with 11 sheets total

See code below:

function delete_sheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = spreadsheet.getSheets();
  var x = 10;
  while (x--) spreadsheet.deleteSheet(sheets.pop());
}

CodePudding user response:

Use String.match(), like this:

function deleteSheets() {
  const ss = SpreadsheetApp.getActive();
  const sheets = ss.getSheets();
  let x = 10;
  while (x--) {
    const sheet = sheets.pop();
    if (!sheet.getName().match(/^(Template sheet|Sheet2|Sheet3)$/i)) {
      ss.deleteSheet(sheet);
    }
  }
}
  • Related