如何使用自定义函数中的 google apps 脚本编辑自定义函数的调用单元格?

How do I edit the calling cell of a custom function with google apps script from within the custom function?

通过 various questions and the documentation I still cannot edit the calling cell of a custom function. According to the docs 搜索后:

Returns the range of cells that is currently considered active. This generally means the range that a user has selected in the active sheet, but in a custom function it refers to the cell being actively recalculated.

尽管此描述是针对 getActiveRange() 函数的,但我们假定 getActiveCell() 函数以相同的方式运行。

我正在尝试从我的自定义函数中调用辅助函数,据我所知,应该 return 'active cell' 应该是自定义函数的调用单元。无效代码:

// returns the current active (calling) cell for use within custom functions
function callingCell() {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getActiveRange()
}

// change background colour of calling cell
function getInfoFromPublicApi(type) {
      ... // get prices using UrlFetchApp
      callingCell().setBackground('green')
      return averagePrice(prices, type)
}

我也尝试过直接在自定义函数中使用 SpreadsheetApp,以及使用:

SpreadsheetApp.getActiveSpreadsheet().getActiveCell()
SpreadsheetApp.getActiveSpeadsheet().getActiveRange()

您可以通过两种方式进行处理。首先,将调用单元格设置为变量。您不能像尝试在更大的函数中那样将方法链接在一起。或者,您可以删除 callingCell() 函数,因为信息是在 onEdit()event 对象中处理的。

方法一

// returns the current active (calling) cell for use within custom functions
function callingCell() {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getActiveRange();
}

// change background colour of calling cell
function getInfoFromPublicApi(type) {
  var active = callingCell();

  ... // get prices using UrlFetchApp
  active.setBackground('green')
  return averagePrice(prices, type)
}

方法二

function onEdit(e) {
  // Not sure what your `type` param is, so you'd need to test for that somehow.
  ... // get prices using UrlFetchApp
  e.getRange().setBackground('green');
  ...
}