获取自定义函数中的单元格对象

Roz*_*lns 3 google-sheets google-apps-script

我有这个功能来获取单元格的字体颜色.测试函数工作正常(因此我得到十六进制代码#ff0000),但是当我get_color()从Google电子表格调用该函数时,它返回#ERROR.这似乎是因为我从函数参数中获取了一个纯字符串值,而不是Range对象.我怎么能实现它?

也许有一种更简单的方法来获取文本的字体颜色?

get_color()返回#ERROR

function test_get_color() {
  var targetId = 'xxx'
  var cell = SpreadsheetApp.openById(targetId).getSheetByName('Sheet1').getRange('B7');

  Logger.log(get_color(cell)); 
}

function get_color(cell){
  return cell.getFontColor();
}
Run Code Online (Sandbox Code Playgroud)

Mog*_*dad 6

通过提供范围作为参数来调用自定义函数时,该函数实际上会从该范围接收.这在Google表格/参数中的自定义函数中有记录.

对于需要实际范围引用的函数的hack,就像你的函数一样,是将范围作为字符串传递.

=get_color( "B7" )
Run Code Online (Sandbox Code Playgroud)

函数将是这样的:

/**
 * Get the color of text in the given cell.
 *
 * @param  {"B32"}  cell  Cell reference, enclosed in quotes.
 * @returns               The text color from the given cell.
 * @customfunction
 */
function get_color( cell ) {
  if (typeof cell !== "string")
    throw new Error( "Cell reference must be enclosed in quotes." );

  var range = SpreadsheetApp.getActiveSheet().getRange( cell );
  return range.getFontColor();
}
Run Code Online (Sandbox Code Playgroud)

注意:评论块会为此功能提供Google表格自动完成帮助.看你知道吗?(有关自定义功能,请参阅Google Apps脚本中的自定义功能).


小智 5

最好的方法是使用填充了ROW()和COLUMN()函数结果的其他参数来调用自定义函数.

当调用= MYFUNCTION(ROW(),COLUMN())时,MyFunction获取工作表中与调用函数的单元格位置相对应的单元格位置.

  • 或者你可以做 `function MYFUNCTION() { return SpreadsheetApp.getActiveSheet().getCurrentCell().getA1Notation(); 然而 getCurrentCell 并不是一个实际的“this”等价物,像这样使用它可能会颠覆其记录的目的:“当前单元格是 Google Sheets UI 中具有焦点的单元格,并由黑色边框突出显示。. .. 当用户选择一个或多个单元格范围时,所选内容中的单元格之一就是当前单元格。” https://developers.google.com/apps-script/reference/spreadsheet/sheet#getcurrentcell 但不知何故它有效......? (2认同)