Carla Irrazabal
Carla Irrazabal

Reputation: 23

How can I access an element from an array?

var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1Ow_rhF3sibKL3OAQRXpK6LLZDjMOhW-5DKyWWiN5iZg/edit#gid=638513192');
var data = SpreadsheetApp.setActiveSheet(ss.getSheetByName('Graficos'));
Logger.log(SpreadsheetApp.getActiveSpreadsheet());

var ergo = data.getRange(3,2,4,1);//B3:B6 '

My guess to access the elements was to call var i = ergo[0]; but it didn't work. Do I have to declare ergo using a different syntax?

Upvotes: 1

Views: 63

Answers (1)

Diego
Diego

Reputation: 9571

You need to use getValues() on the range, which will return a 2-dimensional array.

var ergo = data.getRange(3,2,4,1).getValues();

Also, you're not coding efficiently as you're essentially duplicating actions in your first two lines. Take a look at this refactoring:

function test() {
  var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1Ow_rhF3sibKL3OAQRXpK6LLZDjMOhW-5DKyWWiN5iZg/edit#gid=638513192');
  var data = ss.getSheetByName('Graficos');
  ss.setActiveSheet(data); // There doesn't seem to be a need to do this, so maybe delete this line
  var ergo = data.getRange(3,2,4,1).getValues(); //B3:B6
}

Upvotes: 3

Related Questions