Modify timestamp in google spreadsheet on the basis of changes in one cell

丶灬走出姿态 提交于 2020-01-25 07:56:26

问题


I have been trying to modify the timestamp when a specific cell is modified in google sheets. My end goal is that if the cell is edited to a value then the modified timestamp reflects and if contents of the cell is entirely deleted, then timestamp also deletes. My current script looks like this:

function onEdit()
{
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Sheet1" ) {
    var r = s.getActiveCell();
    if( r.getColumn() == 4 ) {
      var nextCell = r.offset(0,1);
      if((nextCell.getValue() == "" && r.value != "")  ||  (nextCell.getValue() != "" && r.value != "")) {
        nextCell.setValue(new Date());
      } else if(nextCell.getValue() != "" && r.value == "") { 
        nextCell.setValue("");
      }
    }
  }
}

Now this code is able to change the timestamp to current in case of any modification to cell, but if I entirely delete the content of the cell, timestamp does not delete, it again changes to the current timestamp.


回答1:


Try this:

function onEdit()
{
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Sheet1" ) 
  {
    var r = s.getActiveCell();
    var rvalue=r.getValue();
    if( r.getColumn() == 4 ) 
    {
      var nextCell = r.offset(0,1);
      if(rvalue != "")) 
      {
        nextCell.setValue(new Date());
      } 
      else
      { 
        nextCell.setValue("");
      }
    }
  }
}

You can also do it with something like this:

function onEdit(e)
{
  if(e.source.getActiveSheet().getName()=="Sheet1") 
  {
    if(e.range.getColumn()==4) 
    {
      var nextCell = e.range.offset(0,1);
      if(e.value!="")) 
      {
        nextCell.setValue(new Date());
      } 
      else
      { 
        nextCell.setValue("");
      }
    }
  }
}

Although the latter is a little more difficult to debug.

Note: there can only be one onEdit() in your project code. If you have others then they all need to be combined into one with the appropriate conditional logic to keep them from interacting inappropriately.



来源:https://stackoverflow.com/questions/46991271/modify-timestamp-in-google-spreadsheet-on-the-basis-of-changes-in-one-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!