1

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 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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 Comment

this is not an ideal solution as it keeps the rows heights and columns widths if they have not default values... can be annoying.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.