miodf
miodf

Reputation: 543

How to delete only some sheets?

Here is what I am doing (I copied and tried to adapt it from old messages) :

1) inside a spreadsheet that have many sheets create a sheet and renamed it "TOC"

2) in "TOC", add this formula inside A1: =SheetNames( GoogleClock() )

3) Once copied in Google Apps Script, run function "SheetNames" below

function SheetNames() { // this will create a list of all the sheets ;)
try {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
  var out = new Array( sheets.length+1 ) ;
  out[0] = [ "Name" , "gid" ];
  for (var i = 1 ; i < sheets.length+1 ; i++ ) out[i] = [sheets[i-1].getName() , sheets[i-1].getSheetId() ];
  return out
}
catch( err ) {
  return "#ERROR!" 
}
}

4) run function "delete_only_some_sheets"

function delete_only_some_sheets() {
// CAUTION !! It will delete some sheets ! 
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheetByName("TOC");
for (var i = 3; i<=5; i++){ // !!! HERE adapt the "5" number to your needs here
var tet = source.getRange(["B"]+[(i)]).getValues();

//ss.setActiveSheet(ss.getSheetId()[tet]); ///ERROR here ! ;(
   ss.deleteActiveSheet();
   //ss.deleteSheetId()[tet]; //possible ??

}
}

I keep getting the error "Cannot find method "setActiveSheet(."" And I am blocked. ;(

Many thanks in advance ;)

EDIT :

Hello, Thanks to "Srik", I have found the solution ! ;) Part 1) to 3) are the same. Part 4) becomes :

4) run function "delete_only_some_sheets"

function delete_only_some_sheets() {
// CAUTION !! IT will delete some sheets ! 
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheetByName("TOC");
for (var i = 3; i<=5; i++){ // !!! HERE adapt the "5" number to your needs here
var tet = source.getRange(["A"]+[(i)]).getValues();

ss.setActiveSheet(ss.getSheetByName(tet));
ss.deleteActiveSheet();

}

}

Upvotes: 2

Views: 5555

Answers (1)

Srik
Srik

Reputation: 7965

First, there is no getSheetId() method. I assume you are referring to the getSheets() method here which returns an array of Sheet objects.

Second, setActiveSheet() takes a Sheet object as an argument. Using getSheets() method, you can simply do it as follows

ss.setActiveSheet(ss.getSheets()[i]);

There is no need to read the TOC sheet, fetch the id etc.

Upvotes: 4

Related Questions