TypeError:无法读取属性" range"来自undefined

时间:2015-03-07 03:38:28

标签: google-apps-script google-sheets

我写了这个谷歌应用程序脚本。 目的:每次编辑“位置更新”脚本时,都应向“经纪人电子邮件”发送电子邮件。 Here is Link to spread sheet

function onEdit(e) {
  var activateSheet = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.setActiveSheet(activateSheet.getSheetByName('Responses'));
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = e.range;
  var row = e.range.getRowIndex();//Gets the row the change was made to.  

  var timestamp = sheet.getRange(row, 1).getValues(); //Gets the email
  var load = sheet.getRange(row, 2).getValues(); //Gets the email
  var email = sheet.getRange(row, 3).getValues(); //Gets the email
  var location = sheet.getRange(row, 4).getValues(); //Gets the email
  var template = HtmlService.createTemplateFromFile("template");
 template.load = load;
 template.location =location;


  MailApp.sendEmail(email,"Hi","this is my email",{htmlBody: template.evaluate().getContent()});
   }
<html>
<h1><b>This is a Check-In call for load number: <?= load ?></b></h1>
<p>
<?= location ?>
</p>
<p>
Please do not reply this email, we don't read these emails. If you have any questions/concers please <a href="google.com">Click Here</a>. We will get back to as soon as we can.
</p>
</html>

2 个答案:

答案 0 :(得分:6)

错误:

  

范围未定义

表示您定义为范围的某个变量未成功获取对该范围的引用。

如果从脚本编辑器中运行代码,则会出现范围错误。对于简单的onEdit()触发器,您只能通过实际编辑单元格来测试代码。 e事件变量除非您实际编辑单元格,否则不会为其分配任何内容。

我运行了您的代码,如果我通过编辑单元格触发它,则不会出现任何范围错误。

我收到一条错误消息,指出我没有权限发送电子邮件。这可能是因为触发器是一个简单的&#34;触发。您可能需要创建一个可安装的触发器才能拥有发送电子邮件的权限。

答案 1 :(得分:2)

试试这个脚本(也发布在谷歌文档帮助论坛上)

function sendMail(e) {

var sheet = e.source.getActiveSheet();
if (sheet.getName() !== 'Responses' || e.range.columnStart !== 6 || e.range.rowStart < 2) return;
var values = e.range.offset(0, -5, 1, 6)
   .getValues()[0];
var htmlBody = '<body>' + 'Hi<br>'
+ '<h1><b>This is a Check-In call for load number:' + values[3] + '</b></h1>'
+ '<p>' + values[5] + '<\p>'
+ '<p>' + 'Please do not reply this email, we don\'t read these emails. If you have any questions/concers please <a href="google.com">Click Here</a>.'
+ 'We will get back to as soon as we can.</p>'
+ '<\body>'
MailApp.sendEmail(values[4], 'subject', "", {
   htmlBody: htmlBody
});
}

设置一个可安装的onEdit触发器,看看它是否有效?