Google sheet 脚本问题,根据单元格中的姓名向某人发送电子邮件

Issue with Google sheet script to email a person based on the name in a cell

我有一个 sheet 链接到客户投诉表。我想要它,以便当投诉升级到单元格(H 列)中列出的某个人时,它会通过电子邮件向该人发送电子邮件,告诉他们他们有需要查看的问题。我使用了这里其他人编写的另一个脚本的一部分,并尝试对其进行修改以使其正常工作,但无论单元格的内容是什么,它都只会向脚本中列出的第一个人发送电子邮件。有时单元格可以为空,也不需要发送电子邮件。提前抱歉,我对此很陌生。

function send() {
//Sort entries so most recent is at top of spreadsheet and pause
getSpreadSheet();
Utilities.sleep(500);

//Declare global variables
  var to;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var eaddress = sheet.getRange('H2').getValue().toString();

// Determine who to email
  if (eaddress = "User 1") {
    to = "user1@company.com";
  } else if (eaddress = "User 2") {
    to = "user2@company.com";
  } else if (eaddress = "User 3") {
    to = "user3@company.com";
  } else if (eaddress = "User 4") {
    to = "user4@company.com";
  }

// Email sent

var subject = 'Customer Complaint';
var body = 'A customer complaint form has been submitted and escalated to you'
MailApp.sendEmail(to, subject, body);
}
function send()
{
  //Sort entries so most recent is at top of spreadsheet and pause
  getSpreadSheet();

  var to;
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheet=ss.getActiveSheet();
  var eaddress=sheet.getRange('H2').getValue();
  if(eaddress)
  {
    switch(eaddress)
    {
      case 'User 1':
        to="user1@company.com"
        break;
      case 'User 2':
        to="user2@company.com"
        break;
      case 'User 3':
        to="user3@company.com"
        break;
      case 'User 4':
        to="user4@company.com"
        break;
    }
    var subject = 'Customer Complaint';
    var body = 'A customer complaint form has been submitted and escalated to you'
    MailApp.sendEmail(to, subject, body);
  }
}

您的脚本中存在多个问题,但最明显的问题是使用赋值运算符“=”而不是实际用于比较值的“==”和“===”。如果您想避免 JS 中的类型推断,请使用 'if (x == y)' 或 'if (x === y)'。

在前一种情况下,如果您比较 5(一个数字)和 '5',使用 '==' 实际上 return 为真,因为 JS 引擎会尝试将值转换为同一类型。使用“===”将进行比较,同时也会考虑变量类型。

您的脚本向第一个人发送电子邮件,因为您将该电子邮件分配给脚本中的变量并且不比较任何内容。