Search code examples
google-apps-scriptgoogle-sheetscustom-function

Update custom function automatically


I have a custom function as a Google Spreadsheet script, which depends on some other cells' values. It runs ok the first time I put it in a cell, but then when I change the data in the other cells it stays the same. How can I make the first cell update its value automatically when I change the other cells?


Solution

  • I found an answer which doesn't fully make me happy but it's good enough I guess. If you add a function called onEdit to the script of a spreadsheet, it will be called every time stuff is edited. So, this is the code that worked for me: (it has some details that could be useful so I left them unedited)

    function onEdit(event) {
      if (SpreadsheetApp.getActiveSheet().getName().substr(0,5) == "thing")
        SpreadsheetApp.getActiveSheet().getRange("I1").setValue(myCustomFunction());
    }
    

    This makes sheets whose name begins with thing, get the result of myCustomFunction into cell I1.