自定义函数不适用于 ArrayFormula

Wei*_*ies 2 google-sheets google-apps-script

我跟着帖子 https://developers.google.com/apps-script/guides/sheets/functions

function DOUBLE(input) {
    return input * 2;
}
Run Code Online (Sandbox Code Playgroud)

并将非常简单的 DOUBLE 函数复制到我的应用程序脚本中。

=double(A1)
Run Code Online (Sandbox Code Playgroud)

正在工作并在“A1”中加倍我的整数但是当我用值填充 A 列时,例如

A1 = 2
A2 = 3
A3 = 4
....
Run Code Online (Sandbox Code Playgroud)

在 B1 单元格中,我运行

=arrayformula(double(A1:A))
Run Code Online (Sandbox Code Playgroud)

它返回错误“结果不是数字”,#NUM!

我不确定出了什么问题。任何应用程序脚本大师都可以提供帮助吗?

谢谢

Tan*_*ike 6

这个答案怎么样?

  • 例如,当=DOUBLE(A1)使用时,的值inputDOUBLE(input)作为一数字或字符串检索(在你的情况,它是一个数字)。
  • 例如,当=DOUBLE(A1:B1)使用时,的值inputDOUBLE(input)被检索作为2维阵列。

确认是否input为数组后需要进行计算。上面反映的修改如下。

从 :

return input * 2;
Run Code Online (Sandbox Code Playgroud)

到 :

return Array.isArray(input) ? input.map(function(e){return e.map(function(f){return f * 2})}) : input * 2;
Run Code Online (Sandbox Code Playgroud)

笔记 :

当上面修改的示例使用“if”和“for循环”编写时,它变成如下。

if (Array.isArray(input)) {
  var result = [];
  for (var i = 0; i < input.length; i++) {
    var temp = [];
    for (var j = 0; j < input[i].length; j++) {
      temp.push(input[i][j] * 2);
    }
    result.push(temp);
  }
  return result;
} else {
  return input * 2;
}
Run Code Online (Sandbox Code Playgroud)

如果我误解了你的问题,我很抱歉。