Home > Software design >  Can a variable be associated to two different names?
Can a variable be associated to two different names?

Time:12-03

Working in Google AppsScript, specifically for an add-on, and I'm defining the SHEET_NAME as a const. Specifically:

const SHEET_NAME="Values"

Since Google Sheets has a default name of "Sheet1" for all worksheets can I also make SHEET_NAME be associated to either "Values" or "Sheet1"?

Basically, if someone doesn't choose to name their file "Values" then the variable will still know to run SHEET_NAME without breaking.

Right now I have a function that is trying to use the SHEET_NAME variable, but again, trying to see if I can have it look for either "Values" or "Sheet1"

Is something like const SHEET_NAME="Values" OR "Sheet1" doable?

CodePudding user response:

You could just check if the SpreadsheetApp.getActiveSpreadsheet().getSheetByName() returns not null. If so you assign value:

const sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
const SHEET_NAME = sheet1 ? "Sheet1" : "Value"

But in my country it is Blad1 instead of Sheet1 so i suggest rethink you're logic.

I would suggest something like this:

const ss = SpreadsheetApp.getActiveSpreadsheet()
let SHEET

const sheetCheck = ss.getSheetByName("TheSheetName")

if(sheetCheck){
  //Assign the founded sheet to the variable SHEET
  SHEET = sheetCheck
} else {
  //Create the sheet and assign to SHEET
  SHEET = ss.insertSheet("TheSheetName")
}

//Do something with SHEET
  • Related