Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Google Apps script. For loop is not working

I tried to write an Apps script for sending emails for those who forgot to update status report using google form. It's my 1st script and I tried to fix it for almost 5 hours unsuccessfully.

Here is code:

function sendEmails() {
  
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("summary");
  var lastRow = sheet.getLastRow();

    for ( var i=2; i<=lastRow; i++){

      var currentEmail = sheet.getRange(i,11).getValue();
      var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("emailbody").getRange(1,1).getValue();
      var emailRecipient = sheet.getRange(i,2).getValue();
      var messageBody = templateText.replace("{name}",emailRecipient);

      var oldCheck = sheet.getRange(i,12).getValue();

      if (oldCheck = "Old"){
      MailApp.sendEmail(currentEmail,"Reminder: Fill the weekly status update form",messageBody); 
      } 
      else {
        continue;
      }

    }
  
}

It sends only 1 email for the first "old" check.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Explanation:

Issue:

You want to compare the value of oldCheck with "Old" and not assign "Old" to oldCheck. You need to use == instead of =.

Improvements:

It is computationally expensive to use getValue inside a for loop. Instead use getValues before the for loop and work with the arrays. In this way, you eliminate reduntant API calls that make your script heavy especially when i increases.

Solution:

function sendEmails() {
    var spreadsheet = SpreadsheetApp.getActive();
    var sheet = spreadsheet.getSheetByName("summary");
    var data = sheet.getDataRange().getValues();
    var templateText = spreadsheet.getSheetByName("emailbody").getRange(1,1).getValue();
    for (var i=1; i<data.length; i++){    
      var currentEmail = data[i][12];
      var emailRecipient = data[i][3];
      var messageBody = templateText.replace("{name}",emailRecipient);
      var oldCheck = data[i][13];  
      // be careful! == instead of =
      if (oldCheck == "Old"){
        MailApp.sendEmail(currentEmail,"Reminder: Fill the weekly status update form",messageBody); 
        } 
        else {
          continue;
        }
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!