问题
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