使用并行单元格中的电子邮件编辑单元格时发送电子邮件

时间:2019-03-07 09:33:56

标签: google-apps-script google-sheets

我已经阅读了很多onEdit和Triggers脚本,但是仍然无法实现我想要达到的目标,我在excel VBA中编写了很多代码,而Google工作表却大不相同。所以事情是基于我的屏幕截图,我想要的是一旦单元格中包含“已批准”,“被拒绝”,“进行中”,并且该电子邮件地址必须基于所编辑单元格的并行度,就发送一封电子邮件。我渴望完成这项工作。 enter image description here

该代码基于互联网,但我无法根据我的数据/工作表对其进行调整。

3 个答案:

答案 0 :(得分:1)

您可以使用以下脚本在Spreadsheets UI中的下拉菜单中添加自定义函数。这将允许您规避onEdit()限制,该限制不允许一个人使用MailApp类,但这是以让用户手动调用脚本而不是自动运行脚本为代价的。

在此,用户将从下拉菜单中选择“发送电子邮件”,并通过输入提示模式提示他/她输入主键。相应密钥的行将被标识,并且在状态自动更改为“已批准”后发送一封电子邮件。该脚本假定电子表格至少包含四列,标题行的顺序为“主键”,“描述”,“电子邮件”和“状态”。

请注意:此代码已成功测试。请通过替换方括号和其中包含的定义sheetURL和workSheetName变量的文本来更新第20和21行。

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
  .addItem('Send E-Mail', 'sendEmail')
  .addToUi();
}

function sendEmail(){

  // Display a dialog box with a title, message, input field, and "OK" and "Cancel" buttons. The
  // user can also close the dialog by clicking the close button in its title bar.
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Pop-Up Prompt', 'Please enter primary key:', ui.ButtonSet.OK_CANCEL);

  // Process the user's response.
  if (response.getSelectedButton() == ui.Button.OK) {
    Logger.log('The user entered the following primary key:', response.getResponseText());

    // Map the header rows in order that column position is not hard-coded.
    var sheetURL = '[ENTER YOUR SHEET URL HERE]';
    var workSheetName = '[ENTER YOUR WORKSHEET NAME HERE]';
    var sheet = SpreadsheetApp.openByUrl(sheetURL).getSheetByName(workSheetName);
    var lastColumn = sheet.getLastColumn();
    var headerRange = sheet.getRange(1, 1, 1, lastColumn);
    var headers = headerRange.getValues();

    for (var i=1; i<headers[0].length+1; i++) {
      switch (headers[0][i-1]){
        case "Primary Key":
          var primaryKeyIndex = i;
          break;
        case "Description":
          var descriptionIndex = i;
          break;
        case "Email":
          var emailIndex = i;
          break;
        case "Status":
          var statusIndex = i;
          break;
      }
    }
    // Header rows mapped.

    // Search for row corresponding to primary key.
    var primaryKey = response.getResponseText();
    var keyRow = findInColumn(columnToLetter(primaryKeyIndex), primaryKey);
    if (keyRow == -1){
      ui.alert('Primary Key "'+ primaryKey + '" not found.');
    } else {
      ui.alert('Primary Key "'+ primaryKey + '" found at row: ' +keyRow+ '.');
      sheet.getRange(keyRow, statusIndex).setValue("Approved");

      //Prepare Email
      var subject = "test";
      var email = sheet.getRange(keyRow, emailIndex).getValue();
      var body = "Hi, \n\n Your entry with primary key " + primaryKey + " is now approved.";
      MailApp.sendEmail(email, subject, body);

    }

  } else if (response.getSelectedButton() == ui.Button.CANCEL) {
    Logger.log('The user clicked cancel.');
  } else {
    Logger.log('The user clicked the close button in the dialog\'s title bar.');
  }
}

// Helper function to find corresponding row to data in column.
function findInColumn(column, data) {

  var sheet  = SpreadsheetApp.getActiveSpreadsheet();
  var column = sheet.getRange(column + ":" + column);  // like A:A

  var values = column.getValues(); 
  var row = 0;

  while ( String(values[row]) && String(values[row][0]) !== String(data) ) {
    row++;
  }

  if (String(values[row][0]) === String(data))
    return row+1;
  else 
    return -1;

}


// Helper function to convert Column Number to Column Letter
function columnToLetter(column){
  var temp, letter = '';
  while (column > 0)
  {
    temp = (column - 1) % 26;
    letter = String.fromCharCode(temp + 65) + letter;
    column = (column - temp - 1) / 26;
  }
  return letter;
}

答案 1 :(得分:1)

我建议您不要使用onEdit触发器发送电子邮件。我认为许多用户都在使用它。如果是,则必须使用installable triggers。这是昨天来的example email solution,看上去很干净。

答案 2 :(得分:0)

您可以在下面使用大多数此代码。修改电子邮件部分以适合您的需求。  这段代码检查工作表名称是否为“表单响应”,而已编辑的列标题为“状态”,如上图所示。

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var aSheet = ss.getActiveSheet();
  // check sheet name
  if (aSheet.getName() != 'Form Responses') return;

  var range = ss.getActiveRange();
  var row = range.getRow();
  var col = range.getColumn();
//  Logger.log(col);

  var headers = aSheet.getRange(1,1,1,aSheet.getLastColumn()).getValues()[0];
//  Logger.log(headers[col-1]);

  // check column header
  if (headers[col-1] != 'Status') return;

  var value = range.getValue();
  var values = ["approved", "denied", "in progress"]; // values to check for

  // check values
  if (values.indexOf(value.toString().toLowerCase()) == -1) return;

//  Logger.log(row);
  var rowValues = aSheet.getRange(row, 1, 1, aSheet.getLastColumn()).getValues()[0];
  Logger.log(rowValues);

  // change as necessary
  var recipient = rowValues[1]; // email is in 2nd column
  var body = 'Email body'; // create body
  var subject = 'Test'; // set subject

  // send email
  MailApp.sendEmail(recipient, subject, body);
}