当 Google 表单响应添加到 Google 表格时,为什么此 onChange 脚本不运行?

问题描述 投票:0回答:1

我有一个 Google 表单,可将费用记录到 Google 表格中的

expenses
表格中。按照 this 指南,我创建了这个脚本,每次
expenses
工作表发生更改时,该脚本都会向我发送一封电子邮件,其中包含 Google 工作表中另一张工作表中的值。我测试了它的电子邮件部分并且它有效。电子邮件发送,格式看起来不错等等

function onChange(e) {
  var sheetName = "expenses"
  var sheet = e.source.getSheetByName(sheetName)

  if (!sheet) {
    Logger.log("Sheet not found: " + sheetName)
    return
  }

  var currentRowCount = sheet.getLastRow()
  var properties = PropertiesService.getScriptProperties()
  var lastRowCount = properties.getProperty("lastRowCount")

  if (!lastRowCount) {
    properties.setProperty("lastRowCount", currentRowCount)
    return
  }

  lastRowCount = parseInt(lastRowCount)

  if (currentRowCount > lastRowCount) {
    sendSpendingSummary()
    Logger.log("Sent spending summary by email")
  }

    properties.setProperty("lastRowCount", currentRowCount)
}



function sendSpendingSummary() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('summary')
  var range = sheet.getRange("A1")
  var spending = range.getValue().toLocaleString("en-US", { style: "currency", currency: "USD"})
  
  var recipient = "[email protected]"
  var subject = "Month-to-Date Spending Summary"

  var body = "Month-to-Date Spending as of " + Utilities.formatDate(new Date(), "EST", "MMM d, yyyy") + ": " + spending

  MailApp.sendEmail(recipient, subject, body)
}

但是,触发器本身实际上并不运行。它不会失败。它根本不运行,如“触发器”页面所示:

screenshot of the Triggers window showing that the script didn't run

我确信这个脚本还有其他可以改进的地方。不过,目前我只是想弄清楚为什么它根本不运行,即使提交 Google 表单确实成功地将一行添加到

expenses
工作表中。

google-sheets google-apps-script
1个回答
0
投票

Google 表格支持可安装的

onChange
触发器:

当用户修改电子表格本身的结构时(例如,添加新工作表或删除列),可安装的更改触发器就会运行。

因此,如果您的代码实际上并未在电子表格中插入新行,而只是在文档末尾写入数据,则

onChange
将不会触发。

请使用

onEdit
来代替。

© www.soinside.com 2019 - 2024. All rights reserved.