Google Sheets – Insert Date Automatically When Checkbox is Ticked

data validationgoogle sheetsgoogle-apps-scriptgoogle-sheets-timestamp

I have a simple sheet that has two columns with tick boxes in them (columns 5 and 8) The goal is when the box is ticked the date and time are inserted in the column next to it. I have got it working correctly with one column with the following code:

function onEdit(e) {
  var aCell = e.source.getActiveCell(), col = aCell.getColumn(); 
  if(col == 5) {
    var adjacentCell = aCell.offset(0, 1);  
    var newDate = Utilities.formatDate(new Date(), 
      "GMT+1", "dd/MM/yyyy kk:mm:ss");
    adjacentCell.setValue(newDate);
  }
}

For the life of me, I can't work out how to modify that so that it works with column 8 as well. Any help will save me tearing my hair out!

Best Answer

  • you can simply just double it:

function onEdit(e) {
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Sheet1" ) { 
    var r = s.getActiveCell();
    if( r.getColumn() == 5 ) { 
      var nextCell = r.offset(0, 1);
      var newDate = Utilities.formatDate(new Date(), 
      "GMT+1", "dd/MM/yyyy hh:mm:ss");
      nextCell.setValue(newDate);
    }
    if( r.getColumn() == 8 ) { 
      var nextCell = r.offset(0, 1);
      var newDate1 = Utilities.formatDate(new Date(), 
      "GMT+1", "dd/MM/yyyy hh:mm:ss");
      nextCell.setValue(newDate1);
    }
  }
}