How to trigger an email notification when cell value is modified by function

后端 未结 1 1546
醉酒成梦
醉酒成梦 2021-01-21 11:41

I would like to create a Google Sheets with event triggers. I\'m using Google Apps Script.

I succeeded, thanks to Stack Overflow, to create a Google Sheets with an autom

相关标签:
1条回答
  • 2021-01-21 12:06

    You can use a simple script that runs on a timer trigger and checks for any modification in a specific column in your sheet.

    I use script like that for a lot of tasks, including calendar and sheets monitoring.

    Below is a test code that works on column F, you have to run it once manually to create the scriptProperties value that I use to detect changes.

    Then create a time trigger to run it every hour or any other timer value you find useful.

    The only issue would be if you have a very long sheet, you could reach the length limit of the properties... (right now I don't remember the max length, will have to check ;-)

    Code :

    function checkColumnF() {
      var sh = SpreadsheetApp.getActiveSheet();
      var values = sh.getRange('F1:F').getValues().join('-');
      if(PropertiesService.getScriptProperties().getKeys().length==0){ // first time you run the script
        PropertiesService.getScriptProperties().setProperty('oldValues', values);
        return;
      }
      var oldValues = PropertiesService.getScriptProperties().getProperty('oldValues').split('-');
      var valuesArray = values.split('-');
      while (valuesArray.length>oldValues.length){
        oldValues.push('x'); // if you append some rows since last exec
      }
      Logger.log('oldValues = '+oldValues)
      Logger.log('current values = '+valuesArray)
      for(var n=0;n<valuesArray.length;n++){
        if(oldValues[n] != valuesArray[n]){ // check for any difference
          sendMail(n+1,valuesArray[n]);
        }
      }  
      PropertiesService.getScriptProperties().setProperty('oldValues', values);
    }
    
    function sendMail(row,val){
      Logger.log('value changed on row '+row+' value = '+val+' ,  mail sent');
      // uncomment below when you are sure everything runs fine to avoid sending dozens of emails while you test !
      //MailApp.sendEmail(Session.getActiveUser().getEmail(),'value changed in your sheet','Row '+row+' is now '+val);
    }
    
    0 讨论(0)
提交回复
热议问题