Server error on simple "Delete sheet / insert sheet" script

I'm getting a server error on a very simple script and I'm not sure why. The purpose of the script is to check if the sheet exists. If the sheet exists, it should be deleted and recreated. If it doesn't exist, it must be created.

The script works fine if the sheet doesn't already exist. If it exists, the script will delete the sheet and then throw the next error on the line with .insertSheet ("Test").

"We're sorry, there was a server error. Please wait a moment and try again."

Any help is greatly appreciated!

function newSheet() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = spreadsheet.getSheetByName("Test");
  if(sheet != null){
    spreadsheet.deleteSheet(sheet); 
  }
  spreadsheet.insertSheet("Test");
}
      

Run codeHide result


+3


source to share


3 answers


Try passing the index ...

function newSheet() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(),
    sheet = spreadsheet.getSheetByName("Test");
if (sheet != null) {
    spreadsheet.deleteSheet(sheet);
    }
spreadsheet.insertSheet("Test", spreadsheet.getSheets().length);
}

      



and see if it works?

+4


source


I am getting the same errors. This could be a mistake. You will probably need to use sheet.clear()

.

Perhaps this code looks like this:



function newSheet() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = spreadsheet.getSheetByName("Test");
  if(sheet != null){
    sheet.clear();
  } else { 
    spreadsheet.insertSheet("Test");
  }
}

      

Instead of deleting a sheet and creating another sheet with the same name, just clear everything in the current sheet. I'm not sure what benefit you would like to remove the sheet, cleaning will hopefully give you the result you want. If not, I am curious to know why the sheet needs to be removed?

+1


source


Perhaps the script throws an error if the sheet doesn't exist. You can put it in a try-catch block.

function newSheet() {

  var sheet, spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

  try {
    sheet = spreadsheet.getSheetByName("Test");
    spreadsheet.deleteSheet(sheet);
  } catch (e) {};

  spreadsheet.insertSheet("Test");

}

      

0


source







All Articles