TobiasH
TobiasH

Reputation: 313

Set variable as sheet name

I want the variable "sheetname" to be the name of the active sheet. How do I do this? I tried

    var sheetname = SpreadsheetApp.getActiveSpreadsheet().getSheetByName();

But it did not work. Anyone?

Upvotes: 0

Views: 6715

Answers (1)

Mogsdad
Mogsdad

Reputation: 45710

You're looking for Sheet.getName(), check the documentation here.

var sheetname = SpreadsheetApp.getActiveSheet().getName();

The .getName() method exists in both Spreadsheet and Sheet classes. Spreadsheet.getName() will return the name of the document, while Sheet.getName() will give you the name of the sheet within a spreadsheet (the same name that appears on the "tab"). In Google Apps Script, as with javascript, you need to pay attention to the return types of method or function calls to make sure you're invoking the right method in a chain.

In your example, .getActiveSpreadsheet() returns a Spreadsheet instance. In the re-write, we use .getActiveSheet() instead, yielding a Sheet.

Upvotes: 2

Related Questions