Trigger onEdit() with a programmatic edit

后端 未结 1 510
南旧
南旧 2020-12-12 05:07

I have a script that takes data from one sheet when it is edited and puts that recently added data into ScriptDb.

The onEdit() trigger is fired successf

1条回答
  •  有刺的猬
    2020-12-12 05:27

    The onEdit trigger is intended to work when an actual user edits a spreadsheet, the use case you describe should be easy to implement simply by calling your sheetWasEdited() function from the other function if the latest is part of the same project.

    If the changes are made from another project (another spreadsheet or a web app) then it will become quite harder to put in place. (let us know if it is your use case)


    EDIT following your comments :

    The idea is to monitor the length of the sheet, keep the value somewhere (in script properties for example) and call your function if a row has been added.

    This small code should do the trick, you should set a time trigger to call lookatsheet() once in a while, depending on how fast you need to react... I'd say every hour or 30' shouldn't be too much, you decide.

    function lookatsheet(){
      var ss = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxx');// the ID of the SS you want to look at
      var sh = ss.getSheets()[0];// first sheet
      var lastrow = sh.getLastRow();
      var formertest = ScriptProperties.getProperty('lastTest');// recover the value from the last test (will need to get called once to initiate a valid value)
      if (formertest < lastrow){
        sheetWasEdited(lastrow);// call your function with lastRow as parameter
        ScriptProperties.setProperties({'lastTest': lastrow}, true);   // store for next time
    }
    }
    
    function sheetWasEdited(row) {  // modified to work with the other function
      var sheet = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxx').getSheets()[0]
      var lastRowValues = sheet.getRange(row, 2, 1, 2).getValues()[0];
      CgcEmailDatabase.addEmail(now=lastRowValues[0].toString(), email=lastRowValues[1].toString());
    }
    

    NOTE: may be useful to comment the mail call on the first run to avoid sending a mail ( just to initiate the script properties)

    0 讨论(0)
提交回复
热议问题