使用动态行数计算列中的彩色单元格数



在每列的底部,我试图显示该列中有多少单元格具有特定的背景颜色。这就是我希望它做到的:预期结果图片

问题是这是一个甘特图,我会不断地插入行。我可以使用对固定数量的行进行操作

=countCellsWithBackgroundColor("#cfe2f3", "B1:B22")

它使用了我发现的这个功能:

function countCellsWithBackgroundColor(color, rangeSpecification) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(rangeSpecification);
  var x = 0;
  for (var i = 1; i <= range.getNumRows(); i++) {
    for (var j = 1; j <= range.getNumColumns(); j++) {
      var cell = range.getCell(i, j);
      if(cell.getBackgroundColor() == color)
        x++;
    }
  }
  return x;
}

我只是不知道如何给列中的每个单元格赋予这个函数。我会遇到类似"必须是一个范围"的错误。

您可以使用一种更有效的方法来实现相同的结果,方法是在函数中使用数组,如下面的

function countCellsWithBackgroundColor(color, rangeSpecification) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var backGroundColors = sheet.getRange(rangeSpecification).getBackgrounds();
  var x = 0;
  for (var i = 0; i < backGroundColors.length; i++) {
    for (var j = 0; j < backGroundColors[0].length; j++) {
      if(backGroundColors[i][j] == color){ x++ }
    }
  }
  return x;
}

自动更新的工作示例

function countCellsWithBackgroundColor(color, rangeSpecification) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var backGroundColors = sheet.getRange(rangeSpecification).getBackgrounds();
var x = 0;
for (var i = 0; i < backGroundColors.length; i++) {
for (var j = 0; j < backGroundColors[0].length; j++) {
  if(backGroundColors[i][j] == color){ x++ }
   }
 }
 return x;
}
function onEdit(e)
{
 SpreadsheetApp.getActiveSheet().getRange('H26').setValue(Math.random());
}

现在将虚拟单元格插入电子表格功能中以自动更新

=countCellsWithBackgroundColor("#0f9d58","A5:A26",H26)

最新更新