如何在编辑行时自动将Google Sheets单元格设置为当前日期

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

本文关键字:Sheets Google 单元格 设置 当前日期 编辑      更新时间:2023-09-26

我有一个谷歌电子表格,每当我编辑尚未设置日期的行时,我都想自动设置"日期"单元格的值。据我所知,GoogleSheetsneneneba API和GoogleScript是如何工作的,我认为这应该工作,但它甚至从来没有设置调试单元我做错了什么

/**
 * 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());
  }
}

我想您没有设置触发器。在脚本编辑器中,转到资源->当前项目的触发器选择您的函数名称(在本例中为onEdit),并将Event设置为From Spreadsheet->onEdit

保存它,你就完成了。

已编辑的解决方案

好吧,你的代码也有问题。我早些时候错过了。

CCD_ 5是类CCD_ 6和NOT类sheet的函数。您应该使用getRange。这是一个应该有效的代码。您可以根据自己的要求进行编辑。

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());
  }
}