我如何确定是否(谷歌应用程序)脚本正在执行的新表

How do I determine whether a (Google Apps) script is being executed on New Sheets?

本文关键字:脚本 执行 新表 应用程序 何确定 是否 谷歌      更新时间:2023-09-26

我已经为谷歌表格写了一个谷歌应用程序脚本,但它需要运行不同的代码取决于它是在"新"表格上运行,还是在"旧表格"格式中运行。

它是在"旧工作表"上编写的,但我想在Google将所有工作表更新为"新工作表"格式时保持兼容性。(这特别适用于向用户显示一个警告框:https://developers.google.com/apps-script/guides/dialogs#alert_dialogs)

这感觉有点笨拙,最终可能会停止工作,但是您可以尝试调用新表不支持的函数之一。例如,通过newTrigger以编程方式创建一个触发器。

包含在新工作表中的代码:

function onOpen() {
  try {
    var everySixHours = ScriptApp.newTrigger("runCommand")
        .timeBased()
        .everyHours(6)
        .create();
  } catch(e) {
      Logger.log(e);
      Logger.log('You are using a new Google sheet');
  }
  Logger.log(everySixHours);
}
function runCommand() {
  Logger.log('runCommand()');
}

在刷新工作表时将其输出到日志中:

[14-08-10 22:15:07:767 BST] Exception: You do not have permission to call newTrigger
[14-08-10 22:15:07:767 BST] You are using a new Google sheet
[14-08-10 22:15:07:767 BST] undefined

我认为您可以通过检查文档的创建日期来相当可靠地做到这一点。