Calling a Google App Script library from a Google spreadsheet cell

不问归期 提交于 2020-01-02 06:50:47

问题


Trying out the new library feature in a Google spreadsheet. I have include a library with the identifier of "Test" and the library implements the function "foo()"

entering =Test.foo() into a spreadsheet cell gives the error : "unknown function name TEST.FOO"

If I create a function in my spreadsheet to wrap the library function:

function foo()
{
  return Test.foo();
}

then use =foo() in my speadsheet cell, all is well. Creating wrapper functions for all library functions so they can be used in a spreadsheet cell makes using libraries less than ideal. Is there a way to call a library function from a spreadsheet cell?


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/10759296/calling-a-google-app-script-library-from-a-google-spreadsheet-cell

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