首页 > 解决方案 > 如何从最后一行检索值

问题描述

我创建了一个申请新学生 Google 帐户的表格。我想要一个表格脚本通过电子邮件向提交表格的人发​​送新帐户信息,该信息是通过“结果”表上的公式创建的。

function Notification() {
  // Send email notice for accounts
  var lastRow = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getLastRow();
  var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("A" + lastRow);
  if (range.getValue() !== "") {
    return lastRow;
  } else {
    return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
  var AccountName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("H" + lastRow);
  var Password = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("I" + lastRow);
  var PW = Password.getValue();
  var Account = AccountName.getValue(); 
  // Fetch the email address
  var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("G" + lastRow);
  var emailAddress = emailRange.getValues();
// Send Alert Email.
   var message = 'Account Request - Account Name: ' + Account + ' Password: ' + PW; // Second column
   var subject = 'Google Account Request';
MailApp.sendEmail(emailAddress, subject, message);
     }

此脚本在新的表单提交时触发。尝试从查询的最后创建行中提取值到“结果”表,使用 lastRow 从选择列中查找最新条目行。脚本运行没有错误,但没有发送电子邮件,告诉我它没有获取值或返回空值。 这是它从中提取数据的工作表

标签: formsgoogle-apps-scriptgoogle-sheets

解决方案


您只发送第 2 行,因为您只检索一个值(Password.getValue()AccountName.getValue())。考虑与 之间的getValue区别getValues

另一方面,通过声明getRange("H2:H")(“帐户名称”)之类的范围,您将包括电子表格中的每一行,包括有内容和没有内容的行。

我将如何让它从最后创建的行中提取值?

有两种选择:

  • getlastRow()(“Sheet”与“Range”版本)“返回具有内容的最后一行的位置” doc ref here。事实上,该文档项有一个很好的示例,说明如何使用命令声明 Range。
  • StackOverflow 上描述了另一个(非常有用的)实用程序,这是我的最爱。这描述了一列中包含内容的连续行数。

我建议您使用getRange(row, column, numRows, numColumns).
“行”已使用上述方法之一确定,“numRows”=1。然后getValues,该范围将仅包含该行中的值,并且您的电子邮件将仅与该行相关发送。


推荐阅读