0

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

}
0

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

0

I figured it out! I had another function with the same name it was running the other one instead.

0
  • you could try like this which will prevent deleting the Template sheet:

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();
    for (i = 0; i < sheets.length; i++) {
     switch(sheets[i].getSheetName()) {
     case "Template":
     break;
     default:
     ss.deleteSheet(sheets[i]);}}

  • Thanks! I also figured it I just delete the second half (Ui.Alert), it will prevent the Template from being deleted while not having the popup problem. However, I would like if possible to display the alert if they click delete when on the template. – Luke Jul 4 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.