Running onEdit trigger when sheet is updated by Zapier

2.1k views Asked by At

I have a Google spreadsheet where I would like to automatically update one field every time a new row is added by a Zapier automation.

Every time I test the script manually by adding a row or making edits on existing rows, the script fires as expected. However, when Zapier adds a new row to the spreadsheet absolutely nothing happens.

Any idea why and how I can remedy this problem?

This the script which I am trying to use:

function onEdit(e) {
    var row = e.range.getRow();
    SpreadsheetApp.getActiveSheet().
        getRange(row, 10).setValue('My_New_Value');
}
2

There are 2 answers

1
terrywb On

I was able to replicate the behavior you are seeing in your script. I believe that when you add a row outside of the active data range, it does not trigger an edit event. In order to catch those events, you will also need to catch chagne events.

https://developers.google.com/apps-script/reference/script/spreadsheet-trigger-builder#onchange

function onOpen ()
{ 
  var sheet = SpreadsheetApp.getActive();
  ScriptApp.newTrigger("myFunctionx")
   .forSpreadsheet(sheet)
   .onChange()
   .create();
 }

Looking at the documentation for a change event, you can detect that a row was inserted, but the row number is not returned.

https://developers.google.com/apps-script/guides/triggers/events#change

function myFunctionx(e) {
    Logger.log("Change3");
    Logger.log(e.changeType);
}

You might be able to find the row that was inserted by looking at the last row in the active range.

function myFunctionx(e) {
    Logger.log("Change3");
    Logger.log(e.changeType);
    Logger.log(SpreadsheetApp.getActiveRange().getLastRow());
}

It is possible for a change to affect more than one row if you copy and paste into multiple cells. You should loop through all of the rows in your range.

function onEdit(e) {
    for(var i=e.range.getRow(); i<= e.range.getLastRow(); i++) {
        SpreadsheetApp.getActiveSheet().
            getRange(i, 10).setValue(e.range.getA1Notation());
    }
}
0
TheMaster On

onChange does trigger every time a new row is added(through sheets API).

function zapOnChange(e){
  if(e.changeType !== 'INSERT_ROW') return;//exit if the type of change is not a row insertion
  const insertedRow = SpreadsheetApp.getActive().getActiveRange();
  //do something with inserted row
}

Important notes:

  • Sheets API runs asynchronously. onChange is triggered randomly and NOT in the order of insertion.
  • For eg, Two simultaneous inserts may occur at A2:F2 and A3:F3, But the insertRow at A2:F2 may trigger onChange after insertion of A3:F3. So, at the time zapOnChange() is run, the last row might already be A3:F3. So, you cannot use .getLastRow() to determine the inserted row, but use .getActiveRange()
  • Sometimes multiple rows are inserted: .getActiveRange().getNumRows() provides number of inserted rows.