32

I'm a mildly experienced programmer ... I have an OK understanding of OOP concepts, I've been using PHP and MySQL lately. I've started to dabble with Google API Scripts. I'm trying to write a very simple program to read cell 1,1 in a google spreadsheet. The API is NOT embedded in the google spreadsheet, I need it to run outside of the SS.

Here is the code in question:

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();

Read cell 1,1 * Line below doesn't work *

var data = Range.getCell(0, 0);

I understand that getCell() is a method within the Range class. From what I can see in the resources, it looks like Range is the top / parent / super class. Looking at the bold code above, I believe I have created a Range object and trying to call a method from that object. What am I doing wrong here??

Thanks for looking!

AndroidLearner
  • 4,500
  • 4
  • 31
  • 62
Makonnen
  • 495
  • 2
  • 6
  • 8

1 Answers1

61

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Srik
  • 7,907
  • 2
  • 20
  • 29
  • Thanks, that makes sense now. But from the standpoint of a complete newbie, how would I know that structure? Looking at the docs (https://developers.google.com/apps-script/) Default Services > Spreadsheet. It appears that Range, Sheet, Spreadsheet and SpreadsheetApp are same-level / equal subclasses of Spreadsheet. Is there another resource where I can view the proper hierarchy of the Google API Script framework (ie: like how Java has it laid out?) – Makonnen Jan 01 '13 at 21:36
  • 3
    Well, the hierarchy I listed out is not in the sense that they are subclasses of one another. Instead, what I meant is using the Spreadsheet class, you can get a Sheet object. From the Sheet object, you get a Range object and so on. – Srik Jan 02 '13 at 02:36
  • Ahhh that makes sense, I'm not used to working with something like that but now that you explain it that way, it makes sense. Thank you for your assistance! – Makonnen Jan 02 '13 at 08:35
  • Range contains a bunch of cells. Which cell's value is returned when you call range.getValue() ? – Akh May 06 '16 at 00:34
  • @AKh Returns the value of the top-left cell in the range. – Smart Manoj Jan 24 '18 at 13:42