简体   繁体   中英

Custom Google Sheets function

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

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.

当您选择一个值范围并将其传递给函数时,它们将作为数组显示在代码中,有关数组的更多信息,请查看以下页面: http : //javascript.info/tutorial/array

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM