how to get current list of sheet names automatically refresh by google app script when making new sheets or changing sheet name or duplicaing sheets or deleting sheets from google spread sheet
:::::: I need list of sheets name ::::::::::::
::::::::::::::::::::::::::::::::::::::::
and the list of sheet name should display on second sheet that code expression is sheet[1]
below code are working well. but it's not refresh by adding sheets or deleting sheets
function sheetnames()
{
return SpreadsheetApp.getActiveSpreadsheet().getSheets().map(function(x) {return x.getName();});
}
I believe your situation and goal as follows.
sheetnames()
as the custom function on Google Spreadsheet.sheetnames()
works.In order to achieve above, I would like to propose the following method.
In this case, the sample script for refreshing the custom function of sheetnames()
in the Spreadsheet is run by the OnChange event trigger. For this, please copy and paste the following sample script to the container-bound script of Spreadsheet, and save the script.
function onChange(e) {
var lock = LockService.getDocumentLock();
if (lock.tryLock(10000)) {
try {
const prop = PropertiesService.getScriptProperties();
if ((e.changeType === "OTHER" || e.changeType === "REMOVE_GRID" || e.changeType === "INSERT_GRID") && !prop.getProperty("run")) {
const formula = "=sheetnames"; // <--- Please set the function name of the custom function.
const ss = e.source;
const tempFormula = "=sampleFormula";
ss.createTextFinder("^\\" + formula).matchFormulaText(true).useRegularExpression(true).replaceAllWith(tempFormula);
ss.createTextFinder("^\\" + tempFormula).matchFormulaText(true).useRegularExpression(true).replaceAllWith(formula);
prop.setProperty("run", "done");
} else {
prop.deleteProperty("run");
}
} catch(e) {
throw new Error(e);
} finally {
lock.releaseLock();
}
}
}
LockService
is used.PropertiesService
is used.In order to execute the function of onChange
, please install the OnChange event trigger to the function onChange
. You can see the method for installing this at this official document.
In order to test above script, after you installed the function onChange
as the installable OnChange event trigger, for example, please insert new sheet. By this, you can confirm the custom function sheetnames()
is refreshed.