'Google spreadsheet script cell parameters

Hi im having trouble passing 2 cells in my scripts parameters:

function myFunction(c1, c2) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1]; //This is the correct sheet
var valueFirstCell = sheet.getRange(c1).getValue(); 
var valueSecondCell = sheet.getRange(c2).getValue();
return valueSecondCell - valueFirstCell;
}

So i use this in cell A3:

=myFunction(A1, A2)

And lets say A1=10 and A2=15 i would like A3 to show 5 but,

var valueFirstCell = sheet.getRange(c1).getValue(); 

fails "Argument has to be a range" Any ideas?



Solution 1:[1]

In the custom function, c1 and c2 in your script are actually going to be the value of what's in those cells, so you can just use them directly. You can see that by adding Logger.log(c1); and Logger.log(c2); to your script. Try this:

function myFunction(c1, c2) {
  Logger.log(c1);
  Logger.log(c2);
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1]; //This is the correct sheet

  return c2 - c1;
}

There's a tutorial here on building a simple custom function that shows a similar example.

Solution 2:[2]

It's juste saying that argument of getRange function is not in the way it's expected.

link to getRange() documentation

Solution 3:[3]

getRange() function expects row and column.

For e.g. valueFirstCell is in 7th row and 1st column.

var valueFirstCell = sheet.getRange(7,1).getValue(); 

Link to getRange() official documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jan Kleinert
Solution 2 Zelwina
Solution 3 Amarth Gûl