A. Willis
A. Willis

Reputation: 3

Google Script: Have an onEdit timestamp static

I'm trying to have a timestamp appear in a column whenever data is added to a sheet. I've had some success with the following script:

function onEdit(e) {

var colToWatch = 2, colToStamp = 1;
if (e.range.columnStart !== colToWatch) return;
var writeVal = e.value ? new Date() : '';
e.source.getActiveSheet()
    .getRange(e.range.rowStart, colToStamp)
    .setValue(writeVal);
}

My issue is, every time the text in col 2 is edited, the timestamp changes to the current time.

My hope it to have a timestamp that shows when the text was originally added (so it can be organized by that date in another sheet). Other people will have access to this sheet and may change something by accident and cause changes in the sheet organized by date.

I'm new to scripting, is it possible to have an onEdit only run the first time data is added? It seems like onChange() might be able to help me, but I haven't been able to find anything.

Upvotes: 0

Views: 655

Answers (1)

Robin Gertenbach
Robin Gertenbach

Reputation: 10806

Basically you want to terminate if the timestamp cell is already filled.

if (e.source
     .getActiveSheet()
     .getRange(e.range.rowStart, colToStamp)
     .getValue()) {
  return;
}

Upvotes: 0

Related Questions