How to fix null fields in Google Apps Script e-mail lookup

Viewed 61

I'm setting up a spreadsheet rota system. I found some script on-line that seemed to fit the majority of my needs here

Here's the sheet I'm using (with dummy data) - here

However in tweaking it to work with the format & layout I want I've discovered that it doesn't work well with any empty cells.

I've tried using an if statement but it doesn't like it - syntax error (from the "e-mailaddress=" section.

 emailAddress=if(getEmailFromName(row[1])!="") {getEmailFromName(row[1]) + ",";} else{"";}

This is the current code I'm using to send e-mails. Have a separate function that looks up the e-mail addresses.

        // Send an email to the first person

      emailAddress=getEmailFromName(row[1]) + "," +

                      getEmailFromName(row[2]) + "," +

                      getEmailFromName(row[3]) + "," +

                      getEmailFromName(row[4]);


        MailApp.sendEmail(emailAddress, subject, message);



  // to use this function, don’t put anything in the first column (A) or row (1).

  // Put the name (i.e. the key, or what we’re looking for) in column B.

  // Put what we want to return in column C. 



  var columnToSearch = 1; //column B



  // Set the active sheet to our email lookup

  var ss1 = SpreadsheetApp.getActiveSpreadsheet();

  var sh1 = ss1.getSheetByName("EmailContactList")

  ss1.setActiveSheet(sh1);



  var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();



  var line = -1;

  for( var i = 0; i < data.length; i++ ) {

    if( data[i][columnToSearch] == sKey ) {

      line = i;

      break;

    }

  }



  if( line != -1 ) {

    //do what you want with the data on "line"

    return data[line][2]; //value on column C of the matched line

  } else {

  return "";

  // if criteria is not found

  }

}

I'd love my rota to not be necessarily full from the first column & if it's empty to skip that column and only send to e-mail addresses where it finds matches.

1 Answers

Assuming the email addresses are in columns 1 to 4 and some of these could be blanks:

for (var x = 1; x < 5; x++) { // 5 because emails are till col4

    var emailAddress = []; // Start by collecting the non-blank emails in an array

    if (getEmailFromName(row[1]) != "") {

      emailAddress.push(getEmailFromName(row[x]))

    }

  }

  emailAddress = emailAddress.join();  // Join the array to get a comma separated string

  MailApp.sendEmail(emailAddress, subject, message);
Related