Google Sheet 不更新自定义函数返回值

Atr*_*eyu 5 google-apps google-sheets google-apps-script custom-function

我对 Google Apps 脚本(以及 JavaScript)非常陌生,但我一直在尝试修补它以获取乐趣。

我尝试编写一个脚本来获取 Google Sheets 中的 API 价格数据,但发现在同一单元格中重新评估脚本时返回的值没有更新。

下面是一个从 Coinbase 的 API 获取比特币价格数据的脚本。该脚本解析请求的 JSON 响应,如此处所述

function getBTCPrice() {
  var url = "https://api.coinbase.com/v2/prices/BTC-USD/spot";
  var response = UrlFetchApp.fetch(url);

  var jsonSpotPrice = response.getContentText();
  var parseSpotPrice = JSON.parse(jsonSpotPrice);
  var price = "$" + parseSpotPrice.data.amount;

  return price
}  
Run Code Online (Sandbox Code Playgroud)

现在,如果我输入=getBTCPrice()某个单元格,然后稍后重新评估,我会得到相同的价格;但是,如果我在不同的单元格中评估脚本,我会得到不同的结果。

我读过一些关于 Google 在单元格中缓存值的内容,因此可能不会评估脚本,因为单元格的值没有更改。这里是这样吗?如果是这样,有解决方法吗?

任何帮助是极大的赞赏!

Atr*_*eyu 5

我终于弄明白了!技巧是在脚本中调用函数,而不是尝试从实际的工作表单元格(显然存储缓存的值)调用自定义函数。

使用我上面的脚本:

function getBTCPrice(url) {
  var response = UrlFetchApp.fetch(url);

  var jsonSpotPrice = response.getContentText();
  var parseSpotPrice = JSON.parse(jsonSpotPrice);
  var price = "$" + parseSpotPrice.data.amount;

  return price; 
}
Run Code Online (Sandbox Code Playgroud)

然后您可以从另一个脚本调用此函数。具体来说,我希望将更新的价格分配给单元格。下面是一个示例,它将价格分配给活动电子表格的单元格A1

function updatePrice(){
    var a = getBTCPrice("https://api.coinbase.com/v2/prices/BTC-USD/spot");
    SpreadsheetApp.getActiveSpreadsheet().getRange('A1').setValue(a);
}
Run Code Online (Sandbox Code Playgroud)

然后您可以继续设置适当的时间触发器。这就是全部!