Search code examples
javascriptgoogle-apps-scriptgoogle-sheetssyntax-error

How to fix Else if function in google script?


I am trying to write a code where an email will be sent to different people when single a row has been edited at different columns on google sheets.

For example, if column 8 has been edited it should send an email to ABC. Then ABC writes "APPROVE" in column 13 and an email sends to XYZ.

I am trying to use the else if function to separate the two trigger events but when I click save on Google Script, it says the

Syntax error: SyntaxError: Unexpected token 'else' line.

   function sendMailEdit(e){
   var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REVIEW");
   const rData = e.source.getActiveSheet().getRange(e.range.rowStart,1,1,20).getValues();

   ...
   
   if (e.range.columnStart == 8);{
   MailApp.sendEmail({
     to: "ABC@gmail.com",
     subject: "New Account Access Request",
     htmlBody: msg,
     noReply: true
   });
   }
     
   else if (e.range.columnStart == 13 || e.value == "APPROVED");{
   MailApp.sendEmail({
     to: "XYZ@gmail.com",
     subject: "New Account Access Request",
     htmlBody: msg2,
     noReply: true
   });
   }
}

Solution

  • I did not test the code, but after reviewing your code in the editor I noticed that you had extra ";" after if parentheses. After removing the parentheses the code saved was successfully.

    Change your code from:

    function sendMailEdit(e){
       var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REVIEW");
       const rData = e.source.getActiveSheet().getRange(e.range.rowStart,1,1,20).getValues();
    
       ...
       
       if (e.range.columnStart == 8);{
       MailApp.sendEmail({
         to: "ABC@gmail.com",
         subject: "New Account Access Request",
         htmlBody: msg,
         noReply: true
       });
       }
         
       else if (e.range.columnStart == 13 || e.value == "APPROVED");{
       MailApp.sendEmail({
         to: "XYZ@gmail.com",
         subject: "New Account Access Request",
         htmlBody: msg2,
         noReply: true
       });
       }
    }
    

    to:

    function sendMailEdit(e){
       var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("REVIEW");
       const rData = e.source.getActiveSheet().getRange(e.range.rowStart,1,1,20).getValues();
    
       ...
        
       if (e.range.columnStart == 8){
        MailApp.sendEmail({
          to: "ABC@gmail.com",
          subject: "New Account Access Request",
          htmlBody: msg,
          noReply: true});
       } else if (e.range.columnStart == 13 || e.value == "APPROVED"){
          MailApp.sendEmail({
            to: "XYZ@gmail.com",
            subject: "New Account Access Request",
            htmlBody: msg2,
            noReply: true});
       }
    }