简体   繁体   中英

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

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());
}

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);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM