1
votes

I want to create a new sheet called new which should be overwritten if it already exists. But when the sheet already exists I get the error "We're sorry, a server error occurred. Please wait a bit and try again. (line 34, file "Code")", the sheet gets removed - line 34 is the last row here:

  var delSheet = ss.getSheetByName("new");
  if (delSheet != null) {
  ss.deleteSheet(delSheet);
  }
  var sheet = ss.insertSheet("new");

Thanks

3

3 Answers

2
votes

JPVs answer is a good workaround if you want to consider it, but I could reproduce your error.

Funnily enough, if the active sheet is called 'new' and I delete the active sheet, it does not throw me an error:

function test(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  ss.getActiveSheet();
  ss.deleteActiveSheet();
  ss.insertSheet("new");
}

This makes me think this might be a deeper issue, specifically with '.getSheetByName()' so I've listed it here for review by the Google team. Please star it so it gains traction!

1
votes

if you want to 'overwrite' the sheet if it exists, try clearing instead of deleting..

function check() {
var ss = SpreadsheetApp.getActive();
var newSheet = ss.getSheetByName('new');
newSheet ? newSheet.clear() : ss.insertSheet('new');

}

1
votes

Here is a third solution, it seems that specifying a sheet index for the new sheet solves the issue.

function test(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var delSheet = ss.getSheetByName("new");
  if (delSheet) {
    ss.deleteSheet(delSheet);
  }
  var sheet = ss.insertSheet(ss.getNumSheets());// create the new sheet as last sheet, you can change that if you want
  sheet.setName('new');
}

EDIT :

Following HDCerberus answer that pointed the error source I suggest this code that reproduces your initial workflow (his answer does not really do so...), it uses the deleteActiveSheet method as well (which historically was the first available method to delete a sheet, the other method came much later...)

function test2(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var delSheet = ss.getSheetByName("new");
  if (delSheet) {
    ss.setActiveSheet(delSheet);
    ss.deleteActiveSheet();
  }
  ss.insertSheet("new");
}