Use onEdit only in one column

Jelle Poelmans picture Jelle Poelmans · Jan 12, 2016 · Viewed 7.3k times · Source

I'm currently using this script:

function onEdit(e)

  // Set a comment on the edited cell to indicate when it was changed.
  var range = e.range;
  range.setNote('Laatst veranderd: ' + new Date());

What do I need to add so this will only work in column 'C'?

Answer

Alan Wells picture Alan Wells · Jan 12, 2016

Restrict the code from running in a Google Sheet if a certain column is edited. This uses Apps Script onEdit() reserved function name, which is triggered to run on the Edit Event.

Get the column number of the range:

function onEdit(e) {//"e" receives the event object
  var range = e.range;//The range of cells edited

  var columnOfCellEdited = range.getColumn();//Get column number
  //Logger.log(columnOfCellEdited)

  if (columnOfCellEdited === 3) {// Column 3 is Column C
    //Set a comment on the edited cell to indicate when it was changed.
    range.setNote('Laatst veranderd: ' + new Date());
  };
};

Another version:

function onEdit(e) {//"e" receives the event object
  var range = e.range;//The range of cells edited

  var columnOfCellEdited = range.getColumn();//Get column number
  //Logger.log(columnOfCellEdited)


  if (columnOfCellEdited !== 3) {return;}// Halt the code if the column 
    //edited is not column C
    //Set a comment on the edited cell to indicate when it was changed.

  range.setNote('Laatst veranderd: ' + new Date());

};