保存脚本与onEdit触发器-为什么不同?

时间:2019-04-16 18:41:22

标签: google-apps-script google-sheets

我正在尝试在电子表格更新中触发以下功能(理想情况下,对A列进行任何更改)。基本上,脚本会传递名称和活动单元的bgcolor。如果单元格行中的名称与传递的名称匹配,并且行颜色与该活动单元格颜色匹配,则将其添加到redCount并返回此计数。

当在脚本编辑器中单击“保存”按钮(值已更新)时,我的代码有效,但不适用于Google的触发器(时间驱动,“来自电子表格”),即使使用onEvent进行了硬编码( e)。为什么在脚本编辑器中单击“保存”按钮处理与触发器不同的功能执行,该如何解决?

/**
 * The number of times an Editor's Name appears on a red background.
 * @param {string} bgColour - A cell with the background colour we wish to track.
 * @param {string} editorName - The Editor's Name in quotation marks: "James".
 * @return The number of times an Editor's Name appears on a red background.
 * @customfunction
 */

function countSpreads(editorName) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var rangeData = sheet.getDataRange();
  var lastRow = rangeData.getLastRow();
  var searchRange = sheet.getRange(1,2, lastRow-1);
  var actCell = sheet.getActiveCell();
  var activeBg = actCell.getBackground();
  var redCount = 0;
  var bgColors = searchRange.getBackgrounds();

  //Get array of values in the search Range
  var rangeValues = searchRange.getValues();
  // Loop through array and if condition met +1 to redCount
  for (j = 0 ;j < lastRow - 1; j++){
    if(rangeValues[j] == editorName && bgColors[j] == activeBg){
      redCount++;
    }
  };
  return redCount;  
}

1 个答案:

答案 0 :(得分:0)

一个可能的原因可能是getValues()和getBackgrounds()方法都返回一个二维数组。因此,在“ for”循环中,当您调用rangeValues [j]时,假设单元格具有值“ editorName”,它将返回“ [editorName]”并带有方括号,而不是“ editorName”,对于背景也是如此。这可能会导致您的“ if”条件返回false。

相关问题