问题
I have a Google Spreadsheet that I want to automatically set the value of a "Date" cell whenever I edit a row where the date has not already been set. As far as I know the Google Sheets API and how GoogleScript works, I figure this should work, but it never even sets the debug cell! What am I doing wrong here?
/**
* Automatically puts the current date in the first column of the edited row
*/
function onEdit(event){
var sheet = event.source.getActiveSheet();
var debugCell = sheet.getCell(10,10);
debugCell.setValue("DEBUG CELL"); // if anything works, this should show up... but it doesn't :C
var editedCell = sheet.getActiveCell();
var dateCol = 0;
var dateCell = sheet.getCell(editedCell.getRow(), dateCol);
debugCell.setValue(editedCell.getColumn());
if(!dateCell.getValue() && editedCell.getColumn() != dateCol){
dateCell.setValue(new Date());
}
}
回答1:
I suppose you did not set the triggers. In the Script editor, go to Resources -> Current project's triggers
Select your function name (in this case onEdit) and set the Event as From Spreadsheet -> onEdit
Save it and you are done.
Edited Solution
Okay there is problem in your code too. I missed that earlier.
getCell is a function of class range and NOT class sheet. You should use getRange instead. Here is a code that should work. You can edit it as per your requirements.
function onEdit(event){
var sheet = event.source.getActiveSheet();
var debugCell = sheet.getRange(10,10);
debugCell.setValue("DEBUG CELL"); // if anything works, this should show up... but it doesn't :C
var editedCell = sheet.getActiveCell();
var dateCol = 1;
var dateCell = sheet.getRange(editedCell.getRow(), dateCol);
debugCell.setValue(editedCell.getColumn());
if(!dateCell.getValue() && editedCell.getColumn() != dateCol){
dateCell.setValue(new Date());
}
}
来源:https://stackoverflow.com/questions/23027087/how-do-i-automatically-set-a-google-sheets-cell-to-the-current-date-on-editing-i