Custom Google Sheets function

≯℡__Kan透↙ 提交于 2019-12-13 18:02:24

问题


I'm trying to write a custom function that looks a like this:

function myFunction(arg1, arg2){
   //some calculations on the range described by these two arguments
   return value of the calculation
}

arg1 is a cell from a spreadsheet formatted as A1

arg2 is a second cell reference A2

I need these two arguments to point to a range on another worksheet within the same spreadsheet. Somewhat like this: range A1:A2 on Sheet2

I can get the spreadsheet Sheet2 and get the range when I use the code "A1:A2" as an argument for getRange().

Things go bad when I do this:

var range = arg1 & ":" & arg2;
var sheetRange = sheet2.getRange(range);

I'm sure there is a syntax problem here that makes it impossible for the function to interpret range as a range.

And I am completely stumped... Any help, direction to a good syntax reference site or some good tutorials are also appreciated. As is the answer to my problem ;)


回答1:


Even after you correct your api and syntax errors it will still fail because custom functions must be deterministic. Since you pass the range name and not its value, your function will return a previous calculation if you pass the same range again but the range values changed. Tldr either pass the values not the range names or dont use custom functions for this.




回答2:


When you select a range of values and pass it to a function they'll show up in your code as an array, for more information on arrays view this page: http://javascript.info/tutorial/array




回答3:


I made an example for you. Check it here: example

/**
 * custom function
 * 
 * @customfunction
 */
function myFunc(input){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet2');

if (input.map) {            // Test whether input is an array.
    return input.map(myFunc); // Recurse over array if so.
  } else {
    return sheet.getRange(1, input).getValue();
  }
}

It takes as input the range of values from sheet1, but populates the target cells with entries from sheet 2, using the inputs as column numbers for the 1st row in Sheet2. Hope this helps.



来源:https://stackoverflow.com/questions/21939902/custom-google-sheets-function

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