Search code examples
google-sheetsgoogle-apps-scripttriggers

Simpler check if a cell was edited and a certain value inserted


I'm trying to check if the cell I'm interested in has been edited and changed to a certain value. Within function onEdit(event) I'm currently checking if the sheet, column, row and cell content are correct:

function onEdit(event) {

  var range_active = event.source.getActiveRange();

  var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var sheet_template = ss.getSheetByName("Template");

  var cell_test = sheet_template.getRange("B2");

  if(ss.getActiveSheet().getName() == "Template") {

    if(
        range_active.getColumn() == 2
        && range_active.getRow() == 2
        && cell_test.getValue() == "A"
      )
    {
        //  Do something here
    }
  }
}

So there are 4 checks here. Is there a simpler way to checking if my cell (here B2) has been edited and its value changed to "A"?


Solution

  • function cellB2EqualToA(e) {
    
      var sheet = e.source.getActiveSheet();
      var range = e.source.getActiveRange();
      var rangeA1 = range.getA1Notation();
      var value = sheet.getRange(rangeA1).getValue();
    
      if(value != 'A' && rangeA1 != 'B2'){
        return;
      }else{
        //do what you need to do
      };
    }