调试 google 个应用程序脚本

debug a google apps script

我不明白为什么我的函数无法识别 onEdit 函数中的 'e'? 你有好主意吗? 非常感谢你能帮助我 the error when i try to debug

function onEdit(e){
  
  var feuille = e.source;
  if(SpreadsheetApp.getActiveRange().getColumn()==7){  //the 7th column is the "+/-" column
    var i = e.source.getActiveRange().getRow(); //i is the line of the change
    var k = 408+i;   // k is the line where we put the date
    var l = 2;       //l is the column where we put the date and the quantity
    var cellDate = feuille.getRange(k,l);  
    while (isEmpty(cellDate)==false){  //the column of the date is incremented 
      l=l+1;
    }
    feuille.getRange(k,l).setValue(new Date());
    const stockDate = feuille.getRange(i,8).getValue();
      feuille.getRange(k+1,8).setValue(stockDate);
    var spreadsheet = SpreadsheetApp.getActive();   
    spreadsheet.getRange("G2:G403").setValue('0');  ////we reset the "+/-" column to zero

  }    
    
    
}

根据事件对象的文档:

Simple triggers and installable triggers let Apps Script run a function automatically if a certain event occurs. When a trigger fires, Apps Script passes the function an event object as an argument, typically called e. The event object contains information about the context that caused the trigger to fire.

因此,e是传递给onEdit函数的事件对象。

您收到此消息的原因是因为只有在进行编辑时才会传递对象,也就是触发 onEdit 触发器。

如果您 运行 来自编辑器的函数,那么您将收到此错误,因为没有进行任何编辑,因此没有传递任何编辑对象,因此,e 为空。

参考

onEdit(e) 函数是一个 simple trigger,旨在在您手动编辑电子表格时自动 运行。在这种情况下,事件对象 e 已正确填充。

如果您在脚本编辑器中盲目 运行 您的 onEdit(e) 函数,则不会填充事件参数 e,从而导致您提到的错误。

您可以通过编写一个创建对象并在调用 onEdit(e) 时将其用作参数的包装函数来调试 onEdit(e) 函数,如下所示:

function testOnEdit() {
  const e = {
    source: SpreadsheetApp.getActive(),
  };
  onEdit(e);
}

然后调试testOnEdit()函数。

参见 event object