Home > Enterprise >  Delete Last X Number of Sheets Using Google App Script
Delete Last X Number of Sheets Using Google App Script

Time:10-05

I need to delete the last x number of sheets (tabs) from a spreadsheet (workbook) using Google App Script. All I have been able to scrounge up through Googling is this bit of code, which does not do what I need.

function DeleteSheet() {
  var spreadsheet = SpreadsheetApp.getActive();
  for (i = 0; i < 10; i  ) {
  spreadsheet.deleteActiveSheet();}
};

This obviously deletes the first X number of sheets (tabs) at the beginning of a spreadsheet. What I need is a similar script that will delete the last x number of sheets at the end of a spreadsheet. In other words I need to delete sheets from right to left rather than from left to right as is done in the code above.

Below is the exact code that I need in a vba format, but I don't know how to write it appropriately in Google App Script.

Sub DeleteAll()
    i = Worksheets.Count
    For x = i to 21 Step -1 '# <- please note the change here
        Application.DisplayAlerts = False
        Worksheets(x).Delete
        Application.DisplayAlerts = True
    Next x
End Sub

Thanks in advance!

CodePudding user response:

Try this:

function delete_sheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = spreadsheet.getSheets();
  var len = sheets.length;
  for (var i = len-1; i > len-11; i--) spreadsheet.deleteSheet(sheets[i]);
}

Another variant:

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