You need to obtain the spreadsheet object of a Google Sheets when using google sheets and Google app scripts to perform operations on the sheets programmatically.
You can get sheet by name in Google App Script using SpreadsheetApp.getActive().getSheetByName('<Your_Sheet_Name>')
.
Basic Example
function getSheetByName(sheetName) {
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
return sheet;
}
It returns the spreadsheet object. A sheet object has various methods like appendRow()
, GetActiveCell()
and so on.
In this tutorial, you’ll learn how to get a Sheet from a Google Sheet using the sheet name in Google Apps Script.
Get Sheet By Name
In this section, you’ll learn how to get Get Sheet by name.
- Get the active spreadsheet by using the SpreadsheetApp.getActive() method.
- Use the getSheetByName() method to get the spreadsheet object.
The getSheetByName()
method accepts one parameter.
SheetName
– Name of the sheet you need to get.
If there is no sheet available, a null
value will be returned.
Code
function getSheetByName(sheetName) {
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
return sheet;
}
Using this method, you’ll get the active sheet of the Google Sheets application.
This is how you can get the Google sheet by name using Google Apps Script.
Hello,
What about this const destinationSheet = ss.getSheetByName(“SPREADSHEET_NAME”);
I want to use value from… C3 cell for SPREADSHEET_NAME. I want to my script save data in spreadsheet choosen by user from C3 cell.
How to change this script?
Hello,
Please use the script below to get the name of the sheet from a Cell.
var sheetName = SpreadsheetApp.getActive().getRange("C3").getValue();
console.log(sheetName);
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
Let us know if this is what you want.
Regards,
Vikram