我正在尝试在电子表格更新时触发以下函数(理想情况下,对 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;
}
一个可能的原因是getValues((和getBackgrounds((方法都返回一个二维数组。因此,在您的"for"循环中,当您调用rangeValues[j]时,假设单元格的值为"editorName",它将返回带有括号而不是"editorName"的"[editorName]",背景也是如此。这可能会导致您的"if"条件返回 false。