简体   繁体   中英

Google Spreadsheet Script: “Cannot find function getRange in object Sheet” when creating a simple function

Sorry, for the stupid question, but I´ve searched the whole internet and I could not find a good Tutorial to learn how to program in Google SpreadSheet Script.

I want to make a very simple function just for practice.

function simplesum(input) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets();
  var range = sheet.getRange(input);

var x = 0;

for (var i = 1; i <= range.getNumRows(); i++) {
for (var j = 1; j <= range.getNumColumns(); j++) {

var cell = range.getCell(i, j);

x += (cell.getValue());
}
}

return x;
}

I know I could use =sum() to do exactly the same thing. The idea here is to learn how to program.

When I try to use my function in a cell: (ie: =simplesum((A1:A8)) it gives an Error saying: "TypeError: Cannot find function getRange in object Sheet. (line 4)"

What should I do?

And again, sorry for the dumb question....

In this case, you are implementing a Google Apps Script function as a custom function , invoked in a spreadsheet cell.

When you pass a range to a custom function invoked in a spreadsheet cell, you are not passing a range object or a range reference, but rather a 2-D Javascript array of values. So your custom function should just process that array.

function simplesum(input)
{
  var x = 0;
  for (var i = 0; i < input.length; i++)
  {
    for (var j = 0; j < input[0].length; j++)
    {
      x += input[i][j];
    }
  }
  return x;
}
var sheet = ss.getSheets();

returns an Array of sheets, meaning sheets.getRange(input) will throw that error. Try this instead:

var sheet = ss.getSheets()[0];

which selects the first sheet of the array of sheets. Google has some decent documentation for this. For example, here's its documentation on getRange() . Note that it uses ss.getSheets()[0] as well. Hope this helped!

This is working :

function sum(input) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet(); // your mistake : getSheets() 
  var range = sheet.getRange(input);

  var x = 0;

  for (var i = 1; i <= range.getNumRows(); i++) {
    for (var j = 1; j <= range.getNumColumns(); j++) {

     var cell = range.getCell(i, j);

      x += cell.getValue();
   }
 }

  return x;
}

function main () // Yes, I am a former C-programmer ...
{
   var s = sum ("A1:B3"); // Notice the quotes. A string must me entered here.
   Logger.log('s = ' + s);
}

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