9
votes

I see some people have had similar issues in the past, but they seems to be just different enough for the solution to be different. So here goes:

I'm trying to return a range of known size in Google Apps Scripts for sheets like so:

var myRange = ss.getRange(2,1,14,4);

However, I'm getting an error like this:

Cannot find method getRange(number,number,number,number).

Note that using a1notation, as shown below, works just fine:

var myRange = ss.getRange("A2:D15");

The getRange function has several permutations

  • getRange(int, int)
    • returns a range from the coordinates of the ints
  • getRange(int, int, int)
    • returns a range from the coordinates of the first 2 parameters of as many rows as the last parameter
  • getRange(int, int, int, int)
    • returns a range from the coordinates of the first 2 parameters of as many rows as the 3rd parameter and as many columns as the last parameter
  • getRange(string)
    • returns a range specified by the string in a1notation (i.e. "A2:D15", which is the same as saying everything from row 2 column 1 to row 15 column 4)

I've tried using all the different permutations (using hard-coded numbers), and only the a1notation one works. Any thoughts?

1
hum , I use "getRange(int, int, int, int)" for my script and i don't have a prob... Are you sure you take the good numbers ?Hann
is it possible that it might be because of your location settings? You might try a semi colons as separators instead of commas just for grins.ScampMichael
It would be useful to see how the var ss was defined. Perhaps it's only looking at the active spreadsheet and not a sheet within it.Munkey
Even though using A1 notation doesn't cause an error, it still doesn't work. Your code is not returning a range. The spreadsheet can have multiple sheets in it. The documentation is wrong. It shouldn't be showing methods that get a range on the Spreadsheet class. Getting a range will only work on the Sheet Class.Alan Wells
@SandyGood Agree with Sandy! The Apps script documentation is simply wrong. I faced the same problem today. You have to use getRange() on 'sheet' and not 'spreadsheet'. I don't know why the notation way works though.Sujay Phadke

1 Answers

20
votes

As mentioned in my comment, I'd be interested to see how you've built the ss var in your code.

It could be you're pointing to a spreadsheet, and not a sheet within that spreadsheet.

I've put together a simple example of the getRange. This works and it logs how many columns and rows in the range to the Logger.

As you can see, the ss var is used for the spreadsheet and the sheet var for the sheet within the spreadsheet itself.

function getSomeRange(){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  var myRange = sheet.getRange(2,1,14,4);

  Logger.log("Number of rows in range is "+myRange.getNumRows()+ " Number of columns in range is "+ myRange.getNumColumns());

}