google-apps-scriptgoogle-sheetsgoogle-sheets-custom-function

Clear a cell and fetch the Google sheet name


I want to make a script to clear a fixed cell on all sheets but the first four and fill the very same cell with the sheet name.

So far I have a script to blank out the cell and the fill it with a new function the fetches the sheet name. The first script is triggered on opening the spreadsheet. However, it just says loading… and does not fetch the sheet names.

My current (non-working script):

function sheetName() {
  return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}


function clearRange() {
SpreadsheetApp.getActive().getSheets()
    .map(function (s, i) {
        if (i > 3) s.getRange('B3').clearContent().setFormula('=sheetName()');
    })
}

Any great ideas? Thanks


Solution

  • Instead of writing a custom function to the cell, why don't you write the sheet name itself ? Like so...

    function clearRange() {
    SpreadsheetApp.getActive().getSheets()
    .map(function (s, i) {
        if (i > 3) s.getRange('B3').clearContent().setValue(s.getName());
        })
    }
    

    If needed you can trigger this function to run onOpen..

    NOTE: I think you can even leave out the .clearContent() part as the content will be overwritten any how.