I've been trying to update this code to change the custom menu's name to the current Sheet name.
function onOpen() {
const prop = PropertiesService.getScriptProperties();
const sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
SpreadsheetApp.getUi().createMenu(`${sheetName}`).addItem('Run Script', 'main').addToUi();
prop.setProperty("previousSheet", sheetName);
}
function onSelectionChange(e) {
const prop = PropertiesService.getScriptProperties();
const previousSheet = prop.getProperty("previousSheet");
const range = e.range;
const randomValue = Math.floor(Math.random() * 100);
const sheetName = range.getSheet().getSheetName();
if (sheetName != previousSheet) {
range.setValue(`Changed tab from ${previousSheet} to ${sheetName}. ${randomValue}`);
SpreadsheetApp.getActiveSpreadsheet().removeMenu(`${previousSheet}`);
onOpen();
} else return;
prop.setProperty("previousSheet", sheetName);
}
I could never get .removeMenu to work when I use it in onSelectionChange, neither onOpen to add the updated menu again. Not sure if this is even possible to do, maybe someone can help. Thanks.
