【发布时间】:2015-05-29 17:00:49
【问题描述】:
当我尝试从电子表格的单元格中获取值时,出现“未定义”错误。问题是,如果我对不同的单元格执行相同的命令,我会得到该单元格中的值。这两个单元格之间的唯一区别是产生值的方式。
单元格中正确显示的值是直接从与该电子表格关联的 Google 表单中生成的。调用时不显示的值是由我在 Google 表单中创建的脚本生成的。
表单脚本(在表单提交时触发):
// This code will set the edit form url as the value at cell "C2".
function assignEditUrls() {
var form = FormApp.getActiveForm();
var ss = SpreadsheetApp.openById("my-spreadsheet-id")
var sheet = ss.getSheets()[0];
var urlCol = 3; // column number where URL's should be populated; A = 1, B = 2 etc
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var resultUrl = formResponses[i].getEditResponseUrl();
sheet.getRange(2 + i, urlCol).setValue(resultUrl);
}
SpreadsheetApp.flush();
}
表格(已更改为 HTML)
<table>
<tr> <!-- Row 1 -->
<td>Timestamp</td> <!-- A1 -->
<td>Name</td> <!-- B1 -->
<td>Edit form URL</td> <!-- C1 -->
</tr>
<tr> <!-- Row 2 -->
<td>5/26/2015 14:04:09</td> <!-- A2: this value came from the form submittion-->
<td>Jones, Donna</td> <!-- B2: this value came from the form submittion-->
<td>https://docs.google.com/forms/d/1-FeW-mXh_8g/viewform?edit2=2_ABaOh9</td> <!-- C2: this value came from the the script in the form -->
</tr>
</table>
电子表格中的脚本(在表单提交时触发)
function onFormSubmit(e) {
// This script will get the values from different cells in the spreadsheet
// and will send them into an email.
var name = e.range.getValues()[0][1]; // This will get the value from cell "B2".
var editFormURL = e.range.getValues()[0][2]; // This will get the value from cell "C2".
var email = 'my-email@university.edu';
var subject = "Here goes the email subject."
var message = 'This is the body of the email and includes'
+ 'the value from cell "B2" <b>'
+ name + '</b>. This value is retrieved correctly.'
+ '<br>But the value from cell "C2" <b>'+ editFormURL
+ '</b> show as "undefined".';
MailApp.sendEmail(email, subject, message, {htmlBody: message});
}
电子邮件如下所示:
发送者:my-email@university.edu
主题:这里是电子邮件主题。
主体:
这是电子邮件的正文,包括单元格“B2”Jones, Donna 中的值。此值已正确检索。
但单元格“C2”中的值undefined显示为“undefined”。
问题:
我做错了什么?
【问题讨论】:
-
将
Logger.log()语句添加到您的代码以调试您的代码。在onFormSubmit(e)函数的顶部添加Logger.log('range is: ' + e.range.getA1Notation())语句。范围是多少?在“查看”菜单下,选择“日志”菜单项,提交表单后 -
我这样做了,它有助于更好地理解问题。我得到了范围:A285:Q285。我的表有 285 行,列从 A 到 X。因此范围缺少从 R 到 X 的列,编辑表单 url 位于 X 列。因此,有了这些新信息,我如何告诉脚本从 A 获取范围到 X 而不是我现在拥有的。
-
查看新答案。使用
e.range.getRow()获取行。 X 列的列号始终相同。
标签: javascript google-apps-script google-sheets google-spreadsheet-api google-forms