Search code examples
google-apps-scriptgoogle-sheetsslackgoogle-workspace

If, Else, limit range in google script for onEdit trigger


When the value in the cells changes, a message is sent to Slack. I was able to configure sending messages for any change. Here is the script:

var url = 'https://hooks.slack.com/services/';

function sampleName(e){
    
  var newValue = e.value; 
  var oldValue = e.oldValue; 
  var user = e.user; 
  
  var payload = {
      'text' : user + " Изменено с " + oldValue + " на "  + newValue  + " :wink:"
    };

  var params = {
      'method' : 'post',
      'contentType' : 'application/json',
      'payload' : JSON.stringify(payload)
    };
  return UrlFetchApp.fetch(url, params)

}

But I want it only to send a message if the change is in a certain place.


Solution

  • Take a look at the event object

    For example:

    
    function onEdit(e) {
        
        let eventRange = e.range;
        let eventRow = eventRange.getRow()
        let eventCol = eventRange.getColumn()
        
        
        if (eventRow == 1 && eventCol == 1) {
            // DO STUFF
            // ...
            // etc
        }
    }
    
    • The event object, usually called e, has a range attribute.
    • Get the column and the row from this and then use conditionals as you need.
    • You can also call the source attribute to get the Sheet name and use that in your coditionals also.
    • Inspect the documentation linked in the title to see all the different info you can get from the event object, its a lot!