首页 > 解决方案 > 如何计算突出显示的单元格的数量?

问题描述

能否请大家帮我写一段代码,该代码将一些数据范围作为列中的参数,例如;D 列和 D1 到 100。现在我想要的是该函数计算用颜色突出显示的单元格的数量并返回该单元格的数量。

我几乎无法编写任何代码,因为我的知识很少,但是,我尝试过但没有这样的运气。所以,我想问问你们

你可以在这里看到图片.

标签: google-apps-script

解决方案


您必须使用Class Range中的getBackgrounds()方法 来获取包含所有单元格颜色值的数组,然后检查它是否是您想要的颜色。使用此代码,您可以实现您想要的:

/*
   colA1: The column letter for example A,B,C, AA..
   rangeStart: Where to start the range
   rangeEnd: Where to end the range
*/
function numberHighlightedCells(colA1, rangeStart, rangeEnd){
  // Set the color for comparation 
  var color = '#ff0000';
  // Build the range with the parameters values
  var customRange = colA1 + rangeStart.toString() + ":" + colA1 + rangeEnd.toString();
  // Get the range
  var range = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(customRange);
  // Get an array containing all colors 
  range.getBackgrounds().forEach(function(e, index){
    // Verify if the desired color is in the cell 
    if( e[0] === color) Logger.log("Cell number " + (index + 1).toString())
  });
}

推荐阅读