Search code examples
google-sheetsgoogle-apps-scriptgoogle-sheets-formula

Update custom function in different cells


I have a spreadsheet with a custom function calling a web API like this:

function myFunction(value) {

  var value = value
  ...

}

and I call this function in different cells in B column in this way:

=myFunction(A2)
=myFunction(A3)
=myFunction(A4)
...

so that the values change regarding the content of A column.

Now, I would like to update all these functions with a trigger, which could be every minute, or every hour, or at midnight. I used the built in trigger on Google Apps Script interface, like I did in the past with external scripts, but it doesn't work (I think because the trigger call the function without the "value" variable). I was thinking to add an external triggered script that update the value of another cell (let's suppose "C1"), and then use the onEdit function to update the custom functions. I searched a lot about onEdit, but I really didn't understand how to make it works in my case. Should the onEdit function recall myFunction? In what way?

Any help is appreciated, thank you


Solution

  • Ok, I solved with an external script that updates a cell, and then a dummy argument in my custon function that refers to that cell (as suggested by @RobinGertenbach) This is the external triggered script:

    function update() {
    
      var number = Math.floor(new Date().getTime()/1000);
      ss.getSheetByName("Data").getRange("A1").setValue(number);
    
    }
    

    and my custom function now looks like:

    function myFunction(value, now) {
    
       var value = value 
       var now = now
       ...
    
     }
    

    and then it is called in column B in this way:

    =myFunction(A2, $A$1)
    =myFunction(A3, $A$1)
    =myFunction(A4, $A$1)
    ...
    

    The solution with a function for refreshing formulas posted above was not doing the job, I don't know why. Formulas were refreshing but the values didn't get updated. Thank you very much for your help!