I'm trying to add a table of contents to Google Sheets: simply want to include a list of all sheets inside the document, as clickable links (got 150+ sheets.)
I got it to work, but it's more complicated than I'd like, and leaves me with questions about custom functions in Google Sheets.
Here's what I have, set of course in Tools › Script editor
:
/**
* Returns all the document's sheet IDs.
*
* @return
* @customfunction
*/
function tocid() {
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=0 ; i<sheets.length ; i++)
out.push( [ sheets[i].getSheetId() ]
)
return out
}
/**
* Returns all the document's sheet names.
*
* @return
* @customfunction
*/
function toctitle() {
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=0 ; i<sheets.length ; i++)
out.push( [ sheets[i].getSheetName() ]
)
return out
}
Using each formula, I get:
| Sheet_ID | Sheet_Title |
|------------|-------------------|
| 349319062 | Table of Contents |
| 1280378086 | many ou much |
| … | … |
And then I can use the HYPERLINK
formula to get links: =hyperlink(concatenate("#gid=",A2), B2)
.
So it works.
However, I tried to do it all in one pass, like so:
/**
* Returns a list of all the document's sheets as hyperlinks.
*
* @return
* @customfunction
*
* …unfortunately, can't use built-in functions inside of it, it seems. So instead of hyperlinks, it shows the formula for the hyperlinks.
*/
function toclink() {
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=0 ; i<sheets.length ; i++)
out.push( [ "=HYPERLINK(\"#gid=" + sheets[i].getSheetId() + "\", \"" + sheets[i].getName() + "\")" ]
)
return out
}
But, as noted in the function's code comments, it does not work.
My questions are:
Is the fact that you cannot use built-in functions inside of Google Sheets' custom functions / Google Apps scripts actually documented anywhere? (I'd have saved a couple of hours of my life had I known.)
Any way to have the a custom function return clickable hyperlinks?
I suspect using Range
might do it, but I'm not comfortable with them (and the fact the above still works makes it less of an incentive to learn). Is there a way to have a custom function just evaluate a formula taken from another column?
NOTE: I don't want to use a macro. I want to use a solution that auto-updates when new sheets get inserted.
I realize there's a similar question here, with a very useful answer. This does not exactly answer my questions, but is a bit easier to use than my current solution.