I have a really simple script to pull the given tab name:
function sheetName() {return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();}
But this will not update when I change a tab's name. Is there any script that could be written to "re-execute" sheetName(), the function, in all places it is found in a spreadsheet? Would love to just pop in a button that could rerun sheetName() everywhere so that the tab names' references stay current.
I do see some old (~4 years) questions about this, but struggling to find something current. Apologies if this is duplicative!
You can install a trigger to run "On change" I tried editing a sheet tab, and the code did run.
function sheetNameReturn(e) {
Logger.log(e.changeType)
Logger.log('sheetName ran')
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}
Unfortunately, at the time of this post, the triggers are kind of buggy. If you install a trigger, and it doesn't run, you'll need to delete the trigger, close the window, and go through the process again and save it.
I changed the name of the function to sheetNameReturn
I had a lot of trouble getting the trigger to run. I had to delete the trigger and install it again.
Keep Your Sheet Names the Same
If you'd like to keep your sheet names the same here's a script just for you. It utilizes a few scripts that I've been working on lately that allow you to save arrays and associative arrays in files rather than utilizing the PropertiesService. It may not be 100 percent bug free...but what is?
Code.gs
function onOpen()
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('SaveSheetNames', 'SaveSheetNames')
.addToUi();
}
function SaveSheetNames()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shts = ss.getSheets();
var s = 'SheetNames:::DICT|***|';
for(var i = 0; i<shts.length;i++)
{
if(i>0){s += '~~~';}
s += shts[i].getSheetId() + '^^^' + shts[i].getSheetName();
}
saveFile(s);
}
function KeepSheetNames()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shts = ss.getSheets();
var SheetNamesA = getArrayByName('SheetNames');
for(var i = 0; i<shts.length;i++)
{
if(shts[i].getName() !== SheetNamesA[shts[i].getSheetId()])
{
shts[i].setName(SheetNamesA[shts[i].getSheetId()]);
}
}
}
ArrayFileStorage.gs
//A segment is either an Array or an Associative Array obtain by splitting the data string inside the data file with this delimeter |@@@|
//It returns an actual Associative Array
function getAssociativeArray(segment)
{
var segment = (typeof(segment))?segment:null;
var C = [];
var br = '<br />';
if(segment)
{
var A = segment.split('~~~');//Array of key^^^value strings [key^^^value,key^^^value,key^^^value...]
for(var i = 0;i<A.length;i++)
{
B=A[i].split('^^^');//KeyValueArray[key,val]
C[B[0]]=B[1];//Dictionary or Associative Array {key:'value',key:'value',key:'value'...}
}
}
return C;
}
//A segment is either an Array or an Associative Array obtain by splitting the data string inside the data file with this delimeter |@@@|
//It returns an actual Array
function getArray(segment)
{
var segment = (typeof(segment))?segment:null;
var br = '<br />';
if(segment)
{
var A=segment.split('~~~');
}
return A;
}
//The above functions are used within this function so that it can return either type of array object requested
function getArrayByName(name)
{
var name = (typeof(name) !== 'undefined')? name : null;
var br = '<br />';
if(name)
{
var data = loadFile('KeepSheetNames').split('|@@@|');//Array Data String two different forms possible
for(var i=0;i<data.length;i++)
{
var A = data[i].split('|***|');
var B = A[0];
var segment = A[1];
var nametype = B.split(':::');
if(nametype[0]==name)
{
if(nametype[1]=='DICT')
{
var obj = getAssociativeArray(segment)
}
if(nametype[1]=='ARRAY')
{
var obj = getArray(segment);
}
break;
}
}
}
return obj;
}
//This function just displays the data stored within the default data file by splitting it with |@@@|
function displayData()
{
s='';
var data = loadFile('KeepSheetNames').split('|@@@|');
for(var i=0;i<data.length;i++)
{
if(i>0)s+='<br />';
s+=data[i];
}
s += '<br /><input type="button" value="Exit" onClick="google.script.host.close();" />'
dispStatus('Display Data for Default File',s,1000,400);
}
//This function uses the saveFile function in Utility.gs to save data into default file.
//This function will also add a new array to the end
function saveArray(name,type,array)
{
var name = (typeof(name) !== 'undefined')? name : null;
var type = (typeof(type) !== 'undefined')? type : null;
var array = (typeof(array) !== 'undefined')? array : null;
var types = ['DICT','ARRAY'];
var isSaved = false;
var isAValidType = false;
for(var i=0;i<types.length;i++)
{
if(type == types[i])
{
isAValidType=true;
break;
}
}
if(name && isAValidType && array)
{
var data = loadFile('KeepSheetNames').split('|@@@|');
var datstr = '';
var idx = getIndexOf(name);
var str = convertArrayToString(name,type,array);
if(idx>-1)
{
data[idx]=str;
}
else
{
data.push(str);
}
for(var i = 0;i<data.length;i++)
{
if(i>0){datstr += '|@@@|';}
datstr += data[i];
}
isSaved=saveFile(datstr);
}
else
{
SpreadsheetApp.getUi().alert('Invalid Input: Check your parameters in function saveArray().');
}
return isSaved;
}
//This function gets the index of the requested named data array
function getIndexOf(name)
{
var name = (typeof(name) !== 'undefined')? name : null;
var idx = -1;
if(name)
{
var data = loadFile('KeepSheetNames').split('|@@@|');
for(var i=0;i<data.length;i++)
{
var nametype = data[i].split(':::');
if(name==nametype[0])
{
idx = i;
break;
}
}
}
return idx;
}
//Takes the real arrays and converts them to strings so that they can be saved.
function convertArrayToString(name,type,array)
{
var name = (typeof(name) !== 'undefined')? name : null;
var type = (typeof(type) !== 'undefined')? type : null;
var array = (typeof(array) !== 'undefined')? array : null;
var types = ['DICT','ARRAY'];
var ConvertedString='';
var isAValidType = false;
for(var i=0;i<types.length;i++)
{
if(type == types[i])
{
isAValidType=true;
break;
}
}
if(name && array && isAValidType)
{
ConvertedString += name + ':::' + type + '|***|';
switch(type)
{
case 'ARRAY':
for(var i=0;i<array.length;i++)
{
if(i>0){ConvertedString += '~~~';}
ConvertedString += array[i];
}
break;
case 'DICT':
var firstTime = true;
for(var key in array)
{
if(!firstTime){ConvertedString += '~~~';}
ConvertedString += key + '^^^' + array[key];
firstTime=false;
}
break;
}
}
else
{
SpreadsheetApp.getUi().alert('Invalid Input: Check your parameters in function saveArray().');
}
return ConvertedString;
}
//deletes a current data array
function deleteArrayByName(name)
{
var name = (typeof(name) !== 'undefined')? name : null;
var br = '<br />';
var isSaved = false;
if(name)
{
var delidx = getIndexOf(name);
if(delidx > -1)
{
var datstr = '';
var data = loadFile('KeepSheetNames').split('|@@@|');//Array Data String two different forms possible
for(var i=0;i<data.length;i++)
{
if(delidx !== i)
{
if(i>0){datstr += '|@@@|';}
datstr += data[i];
}
}
isSaved=saveFile(datstr);
}
return isSaved;
}
}
function dispFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var file = loadFile();
if(file)
{
dispStatus('Displaying File: ' + filename, file, 800, 500);
}
else
{
SpreadsheetApp.getUi().alert('File "' + filename + '" not found in function dispFile.');
}
}
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
function delFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var fldr = DriveApp.getFolderById(folderID)
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
targetFound = true;
fldr.removeFile(fi);
SpreadsheetApp.getUi().alert('File: ' + filename + ' was removed from: ' + fldr.getName() + '/' + target);
}
}
return targetFound;
}
function saveFile(datstr,filename)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
targetFound = true;
fi.setContent(datstr);
}
return targetFound;
}
}
Utility.gs
// Display a modeless dialog box with custom HtmlService content.
function dispStatus(title,html,width,height,modal)
{
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 400;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var modal = typeof(modal) !== 'undefined' ? modal : false;
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
if(!modal)
{
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
else
{
SpreadsheetApp.getUi().showModalDialog(htmlOutput, title);
}
}
You will have to setup a onEdit trigger to call KeepSheetNames() and that should do it. I played with it a bit and it seems to work okay. If you find anything wrong with feel free to fix it. Also you'll have to add the id of your data folder. I decided that it probably wasn't a good idea to publish that.