getActiveCell() 不适用于 google 脚本

getActiveCell() wont work for me on google scripts

我一直在尝试为某人编写一个快速代码,当他们输入特定短语时,该代码将更改 google sheet 中单元格的背景颜色。代码运行良好,没有错误,但它不会在传播 sheet 上产生任何结果。任何帮助都会很棒。

这是我的代码:

function ChangeCellHighlight() {

  //returning value of active cell
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheet =ss.getSheets()[0];
  var cell = sheet.getActiveCell();  


  //typing "Hay" will trigger cell background color 
  if  (cell == 'Hay') {  color
     cell.setBackgroundRGB(255, 0, 0); //red cell background        
  }
}

我重写了这个可以工作。我没有使用 getSheets()[0],而是将其更改为 getActiveSheet(),这意味着当前使用的活动 sheet 已开启。如果要具体,您可以将其更改为 getSheetByName("SHEETNAME")。最重要的是,在调用 'Cell' 的 IF 语句中,它获取单元格而不是我添加的值,cell.getValue()。我还添加了一个 onEdit() 函数,它是 appscript 中的一个存储函数。当您编辑单元格时,它会调用其中声明的函数。

function ChangeCellHighlight() {

      //Get Current Google Sheet, Get Active Sheet Tab.
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
      //Get Active Cell.
      var cell = ss.getActiveCell();
      //If clause - does cell == "Hay"  
      if(cell.getValue() == "Hay") {
        //If YES change background to red.
        cell.setBackground("red");
      } else {
       //Anything else do nothing.
       //Do nothing or you could have Logger.log("Cell not equal to Hay");
      }
    }
    //This will run every time an edit is made.
    function onEdit(){ 
     ChangeCellHighlight(); 
    }