HowED
HowED

Reputation: 13

Get sheets with several

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var numsheets = spreadsheet.getNumSheets();
var sheets = spreadsheet.getSheets()[numsheets];

sheets return undefined.

How pass variable as parameter in the []?

Upvotes: 0

Views: 4299

Answers (2)

Serge insas
Serge insas

Reputation: 46812

Sheets count from 0 while getNumSheets() returns the number of sheets (obviously starting to count "the natural way" from 1...)

In your code simply remove 1 like below :

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var numsheets = spreadsheet.getNumSheets();
var sheets = spreadsheet.getSheets()[numsheets-1];// gets the last sheet

note that getSheets() returns an array of sheet objects, therefor the index between square brackets. Arrays are always 0 indexed, this one is no exception.

spreadsheet.getSheets()[0] is sheet 1, spreadsheet.getSheets()[1] is sheet 2 , etc

Upvotes: 2

KRR
KRR

Reputation: 4947

If you are looking for getting the sheets to a variable and find the number of sheets, you can try this code.

var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
 if (sheets.length > 1) {
  Logger.log(sheets[1].getName());
}

Hope that helps!

Upvotes: 1

Related Questions