[Google App Script][1] 里的函数可以在 Google Sheet 的公式里直接调用,例如可以自定义一个DOUBLE函数,当输入公式=DOUBLE(A1)将 A1 的值乘以二倍后返回,通过自定义函数可以实现默认函数不支持的功能。
![custom-function.jpg][2]

function DOUBLE(input) {
  return input * 2;
}

在公式里使用自定义函数时,系统先会自动处理传入的值然后再作为参数传入。例如=DOUBLE(A1:B1),最终input的值会是一个二维数组[[1,2]],所以需要在函数里添加处理数组的方法。

function DOUBLE(input) {
  if (input.map) {
    return input.map(DOUBLE);
  } else {
    return input * 2;
  }
}

自定义函数也支持自动提示功能,在函数前添加相关注释即可。
![custom-function2.jpg][3]

/**
 * x2
 *
 * @param {number} input 值或范围
 * @return 乘以 2
 * @customfunction
 */
function DOUBLE(input) {
  if (input.map) {
    return input.map(DOUBLE);
  } else {
    return input * 2;
  }
}

注意:

  • 自定义函数名称不能何内置函数冲突,且不能以_结尾
  • 虽然公式里的函数不区分大小写,但是脚本里的函数是区分大小写的
  • 公式里的自定义函数只能使用有限的 Apps Script services,例如可以使用Spreadsheet.get*()方法,而不能使用Spreadsheet.set*()
  • 公式里每使用一次自定义函数都会去请求服务器,如果大量使用返回结果会很慢,所以应该尽量直接传入单元格区域,而不是每一个单元格单独调用函数

参考:https://developers.google.com/apps-script/guides/sheets/functions
[1]: https://0x400.net/post/google-sheets-script.html
[2]: /images/2020/05/4288202635.jpg
[3]: /images/2020/05/2834882370.jpg

标签:,