当单元格等于特定值时,在相邻单元格中添加时间戳

时间:2013-01-18 00:23:15

标签: google-apps-script google-drive-api google-apps

我有一个项目跟踪工具。列K具有完成任务时的下拉菜单。下拉菜单可以选择将任务设置为“未交付”或“已交付”。我想对L列进行编程,这样每当有人选择“已交付”的任务时,我都有该行动的时间戳。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用附加到电子表格的脚本执行此操作。如果您是电子表格中的Google Apps-Script新手,请参阅the tutorials

这是一张电子表格的图片,可以执行您所描述的内容:

Screenshot of working spreadsheet

下面的脚本将通过写入或清除列L中的时间戳来对列K中的更改做出反应。因为电子表格中的每个更改都会调用它,所以它首先要做的是检查我们关心的更改是否已经发生,以及如果没有退出。

/**
 * This function is an auto-trigger, because of its name. It will be
 * invoked on every change in the spreadsheet. The only change that
 * we're interested in is in Column K, and we want to put a timestamp
 * into Column L if the value selected for Column K is "Completed".
 */
function onEdit(event){
  var ColK = 11;  // Column Number of "K"

  var changedRange = event.source.getActiveRange();
  if (changedRange.getColumn() == ColK) {
    // An edit has occurred in Column K
    var state = changedRange.getValue();
    var adjacent = event.source.getActiveSheet().getRange(changedRange.getRow(),ColK+1);
    var timestamp = new Date(); // Get the current time
    // We'll do something different, depending on the selected value
    switch (state) {
      case "Completed":
        // Write timestamp into adjacent cell
        adjacent.setValue(timestamp);
        break;
      case "Not Completed":
        // Erase timestamp in adjacent cell
        adjacent.clearContent();
        break;
      default:
        // Something we didn't expect
        adjacent.setValue("*ERROR*");
        break
    }
  }
}

待办事项:此脚本假设您只更改了一个单元格,这意味着无法正确处理将值复制到多个单元格。