google-apps-scriptgoogle-sheetsevent-triggers

Trigger onEdit Trigger through programmatic edit


I've built a spreadsheet that tracks form responses using the onSubmit trigger. This works well. I then want to display part of the spreadsheet on another spreadsheet, and have built a script that does this.

In order to ensure the second spreadsheet is dynamically updated and synchronised with the first, I have tried to use the onEdit installable trigger; however, it does not work when it is programmatically edited, only if I manually edit spreadsheet 1. Any solutions?


Solution

  • Triggers do not fire on the spreadsheet changes made by scripts. I think the idea is that the script making changes can also follow through on any consequences of those changes. In your case, I see three solutions:

    1. If you just want to "display part of the spreadsheet on another spreadsheet", then importrange command suffices, you don't need a script to do that.

    2. The function triggered by form submission can modify the target spreadsheet itself. To do this, you need an installable trigger running on form submission, since simple triggers cannot access other spreadsheets.

    3. If you really want to trigger a function in a script attached to another spreadsheet, you can run a time-based trigger that will check the last-updated time of the spreadsheet.

    Example of #3: a function that can be set to run every 5 minutes, to detect changes of any kind.

    function checkForUpdates() {
      var updated = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getLastUpdated(); 
      if (new Date() - updated < 300000) {
        // updated in the last 5 minutes, do something
      }
    }