首页 > 解决方案 > 为什么 Google Apps 脚本不更新电子表格中的工作表数量?

问题描述

我有一个 Google Apps 脚本,它可以制作一个电子表格,制作一堆表格,并将这些表格链接到该电子表格。我想做的下一件事是修改电子表格,重新排列工作表,更改工作表的名称等。我的问题是我的电子表格似乎在整个脚本完成之前不会更新以确认表单中的新工作表。

这是我的代码:

function mwe() {
  var ss = SpreadsheetApp.create("Spreadsheet");
  var form1 = FormApp.create("Form 1");
  var form2 = FormApp.create("Form 2");
  Logger.log(ss.getNumSheets());
  form1.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
  Logger.log(ss.getNumSheets());
  form2.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
  Logger.log(ss.getNumSheets());
}

这是我的输出:

Info    1.0
Info    1.0
Info    1.0

如果我记录电子表格的 id,我可以创建一个新脚本:

function mwe2() {
  var ss = SpreadsheetApp.openById("[redacted]");
  Logger.log(ss.getNumSheets());
}

这具有预期的输出:

Info    3.0

有人知道为什么是这样吗?我已经尝试存储 id,使用该 id 重新打开电子表格,并记录该变量中的工作表数量,但除非我运行新脚本,否则我总是得到相同的结果。

标签: google-apps-scriptgoogle-sheetsgoogle-forms

解决方案


正如库珀建议的那样,SpreadsheetApp.flush()解决了这个问题:

function mwe() {
  var ss = SpreadsheetApp.create("Spreadsheet");
  var form1 = FormApp.create("Form 1");
  var form2 = FormApp.create("Form 2");
  Logger.log(ss.getNumSheets());
  form1.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
  SpreadsheetApp.flush();
  Logger.log(ss.getNumSheets());
  form2.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
  SpreadsheetApp.flush();
  Logger.log(ss.getNumSheets());  
}

推荐阅读