首页 > 解决方案 > 在编辑时将多个功能应用于单元格的 JS 代码

问题描述

我目前正在尝试在 google sheet 上的脚本编辑器中编写一些 JS,不仅可以生成时间戳以及单击的复选框,还可以设置一个计时器,如果该框检查超过 X 分钟,则单元格将开始变红。

此外,当我取消选中该框以使单元格变为绿色时。这背后的想法是当我单击表示表已满时间戳的框时想到餐厅女主人的范式,给了我复选框被选中的时间并且颜色显示它不可用 - 如果我取消选中复选框,它会给出时间戳,它也没有被选中重置时间计数器并将单元格更改回绿色。目前,我可以让时间戳部分与我编写的代码一起使用,并在第一次编辑时更改颜色,但它不会根据复选框在颜色之间摇摆不定

以下是我目前拥有的代码。是否会使用触发功能或其他编辑功能如果有人有任何提示或想法,将不胜感激

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  if (s.getName() == "Sheet1") { //checks that we're on the correct sheet
    var r = s.getActiveCell();
    if (r.getColumn() == 5) { //checks the column
      var nextCell = r.offset(0, 1);
      //if( nextCell.getValue() !== '' ) //is empty?
      nextCell.setValue(new Date().setFontColor('green');
      }

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


下面的代码应该可以工作:

function onEdit(e) {

  var s = SpreadsheetApp.getActiveSheet(); // the active sheet (no need to check if the sheet == sheet1 as the active sheet will always be the one that's being edited)
  var r = e.range; // the range of the edited cell
  var c = r.getColumn(); // the column of the range
  var timeDelay = 5; // number in seconds
  var checkbox = r.getValue(); // the value of the checkbox after being edited
  var date = new Date(); // the date for the timestamp

  if (c == 5 && checkbox == true) { // if the checkbox has been checked, change the color to red
    var nextCell = r.offset(0,1);
    Utilities.sleep(timeDelay * 1000); // Utilities.sleep takes a number in milliseconds
    nextCell.setValue(date).setBackground("red");
  } else if (c == 5 && checkbox == false) { // if the checkbox has been unchecked, change the color to green
    var nextCell = r.offset(0,1);
    nextCell.setValue(date).setBackground("green");
  }
}

我对您的进行了一些更改,如果您要在代码中添加更多内容(即事先声明日期,在开始时设置所有变量等),我认为从长远来看,我认为更易于阅读的内容只是个人偏好.)。

但是,这绝对是多余的,因为活动表无论如何都会返回正确的内容:

 if (s.getName() == "Sheet1")

我还将 setFontColor() 更改为 setBackground() 因为听起来这是您从描述中想要的,并且认为您可能不知道该功能,尽管您当然可以将其更改回 setFontColor() 没有任何问题。

我还添加了您询问的时间延迟,尽管我不确定您为什么在这种情况下需要它。如果这不是您所说的,请随意删除这两行,其余代码仍然可以正常工作:

var timeDelay = 5; // number in seconds

   Utilities.sleep(timeDelay * 1000);

推荐阅读