0

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

问题是它是一个甘特图,我会不断地插入行。我可以使用固定数量的行来做到这一点:

=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;
}

我只是不知道如何为列中的每个单元格赋予该函数。我收到诸如“必须是一个范围”之类的错误。

4

2 回答 2

0

您可以使用更有效的方法通过在函数中使用数组来实现相同的结果,如下所示

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;
}
于 2013-07-26T10:35:48.147 回答
-1

自动更新的工作示例

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)
于 2015-10-23T10:38:15.260 回答