首页 > 解决方案 > 如何在谷歌表格中运行两个单独的函数

问题描述

我想要发生的事情的表格示例:

在此处输入图像描述

这个想法是,在第一列中,可以写下物品到达时的名称,这会自动将它到达的日期放在第二列中。然后,当该项目售出时,将记录在第三列中,这会自动将销售日期添加到第四列中。但是,只有第三列有效,而第一列不再输入日期

这是我的代码:

function DateColumnOne() {
  var s = SpreadsheetApp.getActiveSheet();
  if (s.getName() == "Sheet1") { //checks that we're on Sheet1 or not
    var r = s.getActiveCell();
    if (r.getColumn() == 1) { //checks that the cell being edited is in column A
      var nextCell = r.offset(0, 1);
      if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
        nextCell.setValue(new Date());
    }
  }
}

function DateColumnTwo() {
  var s = SpreadsheetApp.getActiveSheet();
  if (s.getName() == "Sheet1") { //checks that we're on Sheet1 or not
    var r = s.getActiveCell();
    if (r.getColumn() == 3) { //checks that the cell being edited is in column C
      var nextCell = r.offset(0, 1);
      if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
        nextCell.setValue(new Date());
    }
  }
}

如果这个问题已经回答了,请告诉我我应该搜索什么关键字,因为我过去两天尝试自己解决这个问题,但无济于事

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


我认为你需要这样的东西:

function onEdit(e) {
  var s = e.source.getActiveSheet();
  if (s.getName() != "Sheet1") return;
  DateColumnOne(s);
  DateColumnTwo(s);
}

function DateColumnOne(s) {
  var r = s.getActiveCell();
  if (r.getColumn() == 1) { //checks that the cell being edited is in column A
    var nextCell = r.offset(0, 1);
    if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
      nextCell.setValue(new Date());
  }
}

function DateColumnTwo(s) {
  var r = s.getActiveCell();
  if (r.getColumn() == 3) { //checks that the cell being edited is in column C
    var nextCell = r.offset(0, 1);
    if (nextCell.getValue() === '') //checks if the adjacent cell is empty or not?
        nextCell.setValue(new Date());
  }
}

第一个函数onEdit()是一个特殊的内部函数,每次手动编辑电子表格时都会触发。

它获取对象e(名称可以是任何东西)。该对象e包含有关编辑发生位置的信息。您可以检查此信息(工作表名称等)并运行其他功能。

实际上你可以做的更短。只有一个功能:

function onEdit(e) {
  var s = e.source.getActiveSheet();    // get the sheet
  if (s.getName() != "Sheet1") return;  // check a name of the sheet

  var col = e.range.columnStart;    // get current column
  if (col != 1 && col != 3) return; // check if it's col 1 or 3

  var next_cell = s.getActiveCell().offset(0,1); // get next cell
  if (next_cell.getValue() != '') return;        // check is the cell is empty

  next_cell.setValue(new Date());  // fill the cell with current date
}

推荐阅读