Home > Back-end >  How to delete a cell when another cell becomes empty?
How to delete a cell when another cell becomes empty?

Time:09-21

So I have two columns. I am already running a script on this sheet so that whenever I add something to a cell, the cell one column over will give me a date when it was last edited. Now I want to run something that, when I make that cell empty, it will delete that last edited time stamp. A script that basically empties the cell one column to the right when I delete whatever was in that first cell. Here is what I have tried so far:

function onDelete(e) {
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cell = e.getActiveCell().getValue();
  var columnN = 14;
  var columnO = 15;

  if (col == columnN){
    if (cell == ''){
      e.source.getActiveSheet().getRange(row,columnO).setValue(null);
    }
  }
}

I have tried to simplify this as much as possible, but I am not getting any result when I make the active cell empty.

CodePudding user response:

function onDelete(e) {
  const sh = e.range.getSheet();
  if(sh.getName() == "Your Sheet Name" && e.range.columnStart == 14 && e.value == '') {
    e.range.offset(0,1).setValue('');
  }
}

CodePudding user response:

You need to use onEDit() (I don't think onDelete() exists, or at least I don't know about it), and apparently you also need to check on the absence of a new value:

function onEdit(e) {
  const sh = e.range.getSheet();
  if(sh.getName() == "Your sheet name" && e.range.columnStart == 14 && (!e.value || e.value == '')) {
    e.range.offset(0,1).setValue('');
  }
}
  • Related