在每日脚本运行工作表时预加载自定义函数

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

我正在使用Google电子表格中的“Cryptofinance”自定义功能。我编写了一个自定义脚本,每天使用应用程序脚本的触发器功能运行。

function daily() {
  SpreadsheetApp.flush();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Liquidity");
  var value = sh.getRange("B36").getValue();
  var lastRow = whichRow();
  lastRow += 1;
  ss.getSheetByName("Liquidity over time").getRange("B" + lastRow).setValue(value);
  ss.getSheetByName("Liquidity over time").getRange("A" + lastRow).setValue(new Date());
}

function whichRow() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var Avals = ss.getSheetByName("Liquidity over time").getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length; 
  return Alast;
}

基本上它应该从字段中获取值并添加一行,以便我可以在此列上运行图表。

从脚本编辑器手动运行时的输出可能如下所示;

1337999,52

日常函数运行时的输出如下所示:

#NAME?

它对.flush()函数没有帮助,我无法理解工作表生命周期与自定义函数的结合。

如何确保在脚本运行之前预先加载工作表?

javascript google-apps-script
2个回答
1
投票

您需要打开电子表格,然后将其设置为活动:

var ss = SpreadsheetApp.openById("1234567890");
SpreadsheetApp.setActiveSpreadsheet(ss);

https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#setActiveSpreadsheet(Spreadsheet)


1
投票

Short answer

在时间驱动的触发器上避免使用调用函数,甚至使用getActiveSpreadsheet和其他“get active”方法的自定义函数。而是使用openById或其他类似的方法。

Explanation

SpreadsheetApp.flush()确保应用对脚本所做的挂起更改,因此将它作为函数的第一个操作没有意义。

另一方面,在Google Apps脚本上,打开电子表格的用户确定哪个电子表格处于活动状态,按时间驱动的触发器getActiveSpreadsheet返回null,换句话说,我们可以说“active”表示“此时正在使用”由用户“。

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