Calling a Google App Script library from a Google spreadsheet cell

纵然是瞬间 提交于 2019-12-05 12:23:52

There's not currently a way to call these library functions directly as a custom function from a cell. Creating a wrapper, as you've done, is the way to do this currently. If you'd like to be able to call library functions directly as custom functions, please raise that as an issue on the Issue Tracker.

Here is a workaround that allows you to call any library function if you paste in this one generic wrapper function. Then you can call this from the spreadsheet.

For example, if I had a library called MyLib with a function add(x, y) (pretend x is in cell A1 and y is in cell A2) I could call it like this: =LIB_FUNC("MyLib", "add", A1, A2).

It's a little ugly but at least allows me to only have to paste this one function and then access any library function. Note that this depends on undocumented structure of the "this" object that is in scope when calling the wrapper function. Small chance this could break over time. Might see if I can publish this as an add on.

function LIB_FUNC(libraryName, functionName) {
  var result;
  var lib = this[libraryName];
  var extraArgs = [];

  if (lib) {
    var func = lib[functionName];

    if (func) {
      if (arguments.length > 2) {
        extraArgs = Array.apply(null, arguments).slice(2);
      }

      result = func.apply(this, extraArgs);
    } else {
      throw "No such function: " + functionName;
    }
  } else {
    throw "No such library: " + libraryName;
  }

  return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!