Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sheet that is not first sheet?

I am new to Google scripting, so I apologize if this is a naive question. I do not know how to get a variable reference to a sheet within a spreadsheet that is not the first sheet.

In my spreadsheet, I have two sheets, Agenda and Info. Agenda is the first sheet(index 0) and Info is the second. I can get a reference to Agenda, but I cannot get a reference to Index. This is the code I have tried:

var info_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Info');

info_sheet.getName() always comes out being Agenda, though. What do I do?

like image 419
Casey Avatar asked Dec 11 '13 07:12

Casey


1 Answers

There are 2 ways to get access to a specific sheet in a spreadsheet : by its name as you were showing in your code or by its index like in the second example below.

Just run this test to see the results on a spreadsheet with at least 2 sheets (I changed the sheet names to the 'standard default values in US locale' to make the test working for anyone, re-set it to your parameters if needed)

function testSheetNames(){
  var info_sheet_example1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2');
  var info_sheet_example2 = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];
  Logger.log('name method result = '+info_sheet_example1.getName());
  Logger.log('index method result = '+info_sheet_example2.getName());          
}

That said, your example should return the correct value, I'm not sure why it didn't in your tests.

like image 70
Serge insas Avatar answered Oct 21 '22 10:10

Serge insas