Google-sheets – Else statement is executing when TRUE

google sheetsgoogle-apps-script

I am completely new to coding. I am a teacher and trying to design a lesson planner tool using Google Sheets Scripts. The idea is to have a template sheet for the lesson that will copy into a new tab. That part is working fine. However, to delete the lesson I want to make it impossible for someone to accidentally delete the template. It is succeeding in not deleting the template tab if "Delete Lesson" is clicked.

However, it is displaying the alert that you cannot delete the template for the other tabs (but then deleting the tab as it should) This is the document.

Any help is greatly appreciated!

I used this code at first:

function DeleteTab1() {  
  var spreadsheet = SpreadsheetApp.getActive();
    var sheet = spreadsheet.getActiveSheet();
    var sheetname = sheet.getName();


  if(sheetname != "Template")  { 
    spreadsheet.deleteActiveSheet();

  }

  else {
      SpreadsheetApp.getUi().alert('The template cannot be deleted');
     } 
}

Then I tried this and had the same problem:

function DeleteTab1() {

  var spreadsheet = SpreadsheetApp.getActive();
    var sheet = spreadsheet.getActiveSheet();
    var sheetname = sheet.getName();


  if(sheetname != "Template")  { 
    spreadsheet.deleteActiveSheet();

  }

  if(sheetname = "Template") {
      SpreadsheetApp.getUi().alert('The template cannot be deleted');
     }

}

Best Answer

Regarding your second code, bear in mind that on Google Apps Script/JavaScript a single equal sign (=) is used to assign a literal or an objecto to a variable, so the syntax of the comparison on following code line is wrong

if(sheetname = "Template") {

The correct syntax is

if(sheetname === "Template") {

Notes:

On Google Apps Script / JavaScript:

  • === means strict equality comparison
  • == means abstract equality comparison

Regarding the first code you should put the else keyword on the same like as the if closing bracket } because that is the right syntax and because the automatic semi-colon insertion,

Reference