The first thing you'll need to do is set your spreadsheet as a variable. In the below example, we use the openByUrl() method to do this, but there are other ways.
function getAllSheets() {
const spreadsheet = SpreadsheetApp.openByUrl(`${YOUR_SPREADSHEET_URL}`)
const sheets = spreadsheet.getSheets()
return sheets
}
If you just have the Spreadsheet Id, you can use the openById() method instead. I personally prefer using this one to avoid having long URLs in my code.
function getAllSheets() {
const spreadsheet = SpreadsheetApp.openById(`${YOUR_SPREADSHEET_ID}`)
const sheets = spreadsheet.getSheets()
return sheets
}
Additionally, if your script is referencing the same sheet that it is being called from - you can use the getActiveSpreadsheet() method instead. This method is really helpful when your code isn't meant for a specific spreadsheet and will depend on where it is being run from.
function getAllSheets() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
const sheets = spreadsheet.getSheets()
return sheets
}
IMPORTANT - Keep in mind that this will return an Array object back. So you'll need to loop through them if you plan on doing anything specific with each one.
