【问题标题】:Trigger Google DocumentApp Script Upon Edit of SpreadsheetApp编辑 SpreadsheetApp 时触发 Google DocumentApp 脚本
【发布时间】:2020-01-20 22:00:17
【问题描述】:

使用 Google Apps 脚本,是否可以在编辑 Google 表格文件时自动更新 Google 文档文件?

我有一个 Google DocumentApp 文件,其中包含一个从 Google SpreadsheetApp 文件中获取数据的脚本。我希望创建一个脚本,以便在编辑 SpreadsheetApp 文件时自动更新 DocumentApp 文件。

这是我目前正在使用的代码:

function updateDocumentOnEditTrigger() {
  var ss = SpreadsheetApp.openById(SheetID);
  ScriptApp.newTrigger('UpdateDocument')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}

运行updateDocumentOnEditTrigger 函数似乎不会触发UpdateDocument 函数,它在手动运行时会正常工作。

【问题讨论】:

  • 我想了解您的目标。但我无法理解I want to trigger that DocumentApp script to run whenever the SpreadsheetApp is edited in any way.。我可以问你吗?顺便说一句,我认为openById 不能与使用onEdit() 的简单触发器一起使用。如果您想通过 OnEdit 事件触发器使用openById,请使用可安装的 OnEdit 事件触发器。这个怎么样?
  • @Tanaike 我想为 DocumentApp 文件创建一个触发脚本,以便在编辑 SpreadsheetApp 文件时,更新 DocumentApp 文件。我已将脚本更改如下:function updateDocumentOnEditTrigger() { var ss = SpreadsheetApp.openById(SheetID); ScriptApp.newTrigger('UpdateDocument') .forSpreadsheet(ss) .onEdit() .create(); } 我将另一个函数包装在此函数中并将其放在外面,似乎都没有更新 DocumentApp 文件。
  • 听起来您想在 SpreadsheetApp 上创建一个 onEdit 触发器,然后更新 DocumentApp。因此,无论何时编辑 SpreadsheetApp,代码都会运行,然后编辑/更新 DocumentApp。对吗?
  • @IMTheNachoMan 没错。我是谷歌脚本的新手。我已经按照我的“UpdateDocument”DocumentApp 脚本中的建议插入了上面安装的触发器。这是正确的还是我需要一个单独的 SpreadsheetApp 文件脚本?

标签: google-apps-script google-sheets google-docs


【解决方案1】:

答案:

为了在编辑电子表格时运行DocumentApp 脚本,必须使用附加到电子表格的On edit 可安装触发器。

更多信息:

根据简单触发器文档,需要考虑一些限制。特别是:

他们可以修改他们绑定的文件,但不能访问其他文件,因为这需要授权。

因此无法使用onEdit(e) 触发功能。然而,有一个可以创建的可安装触发器,其设置设置为可以在编辑时触发。

代码:

将脚本中的以下函数绑定到电子表格文件:

function updateDocument() {
  var doc = DocumentApp.openById('DOCUMENT_ID');
  // here you can put your code that edits the document in the way you want.
}

您可以创建在电子表格编辑时运行的可安装触发器。但是,您需要在设置触发器之前至少运行一次代码 - 这是因为 DocumentApp 需要授权并且您需要授予它!

###设置可安装触发器: 设置好代码后,您可以通过完成以下步骤来创建可安装触发器:

在绑定的电子表格脚本的 Apps 脚本编辑器视图中,遵循路径 Edit > Current project's triggers。这将在新选项卡或窗口中打开项目的触发器。

在左下角,单击+ Add Trigger 按钮,调出Add Trigger 模态。从这里,使用以下属性设置触发器:

  • 选择要运行的函数:updateDocument
  • 选择应该运行的部署:Head
  • 选择事件源:From spreadsheet
  • 选择事件类型:On edit

然后点击Save。这将设置触发器,以便您的文档编辑功能将在每次编辑电子表格时运行。

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多