当另一个单元格被清除后,如何清除特定单元格?

时间:2014-06-26 19:23:09

标签: google-apps-script

我有一个Google文档电子表格的脚本,当填充特定列中的任何单元格时,它会自动将时间戳放在该行的不同列中:

function onEdit() {
 var s = SpreadsheetApp.getActiveSheet();
 if( s.getName() == "Sheet1" ) { //checks that we're on the correct sheet
   var r = s.getActiveCell();
   if( r.getColumn() == 9 ) { //checks the column
     var nextCell = r.offset(0, 3);
     if( nextCell.getValue() === '' ) //is empty?
       var time = new Date();
     time = Utilities.formatDate(time, "Canada/Eastern", "M/dd/Y, h:mm:ss");
       nextCell.setValue(time);
   };
 };
}

脚本效果很好。但是,如果所述单元格已被清除,我希望该脚本删除该时间戳。

或许我可以稍微改变一下这个问题:当该行中另一个特定单元格被清除时,如何清除特定单元格?

1 个答案:

答案 0 :(得分:1)

代码几乎相同,我稍微简化了一下,以便更容易理解它正在做什么。

编辑:

更好的代码,以防止在col 9中修改单元格时出现问题。

我使用了onEdit触发器中的参数(在本例中称为e),有关详细信息,请参阅docs

function onEdit(e) {
  var s = SpreadsheetApp.getActiveSheet();
  Logger.log(JSON.stringify(e)+'  ------------------> value = '+e.value);
  var r = e.range;
  var nextCell = r.offset(0, 3);
  if( s.getName() == "Sheet1" && r.getColumn() == 9 ){ //checks that we're on the correct sheet & column
    if( nextCell.getValue() === '' && e.value !=null){ //is empty?
      var time = new Date();
      time = Utilities.formatDate(time, "Canada/Eastern", "M/dd/Y, h:mm:ss");
      nextCell.setValue(time);
    }else{
      if(e.value==null){ nextCell.setValue('')};  
    }
  }
}

enter image description here