How do I automatically set a Google Sheets cell to the current date on editing its row?

谁都会走 提交于 2020-01-06 20:04:36

问题


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

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