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

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

在搜索various questions和文档后,我仍然无法编辑自定义函数的调用单元格。据the docs说:

返回当前被视为活动的单元格范围。这通常表示用户在活动工作表中选择的范围,但在自定义函数中,它指的是正在主动重新计算的单元格。

虽然这个描述是针对getActiveRange()函数的,但是假设getActiveCell()函数的方式相同。

我试图从我的自定义函数中调用一个辅助函数,它应该返回'活动单元',据我所知,它应该是自定义函数的调用单元。不工作的代码:

// 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()
google-apps-script google-sheets google-sheets-api
1个回答
1
投票

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

方法1

// 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)
}

方法2

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');
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.