Google Apps脚本根据if语句

时间:2019-03-10 23:28:08

标签: javascript google-apps-script google-sheets

当前,我的脚本正在使用“是”更新所选范围内的所有单元格,但我只希望它更新满足if条件的单元格。任何帮助将不胜感激。

//Active spreadsheet var that can be used anywhere in the programme
var ss = SpreadsheetApp.getActiveSpreadsheet();

// Get and check if there is an email address
function checkSendEmailAdd () {

  //Getting the array of values 
  var activeSheet = ss.getActiveSheet();
  var emailCol = activeSheet.getRange(2, 9, activeSheet.getLastRow() - 1, 2).getValues();
//Looping over the array of values
      emailCol.forEach(function(val){
      var email = val[0].toLowerCase();
      var sentEmail = val[1];
      //If the send date column is empty and the email column has a @ within the string an email will be sent           
          if (email.indexOf("@") !== -1 && sentEmail == ""){

              //Email contents
              var subject = "Survey";
              var body = "Hi" + "<br><br>" +
                         "Testing 123";

               GmailApp.sendEmail(email, subject, "", { htmlBody: body } );

                //Update and set a new value in the sent email column
                var newSetValue = "YES";
                var updateSentEmail = activeSheet.getRange(2, 10, activeSheet.getLastRow() - 1, 1).setValue(newSetValue);

          } else {
          }
      });

我面临的问题是,发送列正在更新每个单元格,但我只希望它更新电子邮件列中具有电子邮件的单元格。

Image of what is being executed currently

1 个答案:

答案 0 :(得分:0)

尝试一下:

我试图根据您的问题确定各列。我相信电子邮件是第一列,而sendMail是第二列,但是如果我错了,可以将其更改为所需的任何内容。

function sendEmail() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet0');
  var vA=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
  var sentA=sh.getRange(2,2,sh.getLastRow()-1,1).getValues();
  var html='';
  for(var i=0;i<vA.length;i++) {
    var email=vA[i][0].toString().trim().toLowerCase();
    var sentEmail=vA[i][1];
    if(email && email.indexOf("@")>-1 && !sentEmail){
      var subject = "Survey";
      var body = "Hi<br><br>Testing 123";

      //GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
      html+=Utilities.formatString('<br />%s -<br />Email: %s<br />Subject: %s<br />Body: %s<br /><hr/>', Number(i+1),email,subject,body);
      sentA[i][0]="Yes";
    } 
  }
  sh.getRange(2,2,sh.getLastRow()-1,1).setValues(sentA);
  var userInterface=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Emails Sent');
}

发送前的电子表格:

enter image description here

发送后的电子表格:

enter image description here

我删除了Gmail行,并使用了一个对话框来显示电子邮件:

enter image description here