【问题标题】:How to count cells with specific text & color如何计算具有特定文本和颜色的单元格
【发布时间】:2019-12-29 22:45:54
【问题描述】:

我需要在 Google 表格中计算具有特定颜色和文本的单元格。 我找到了一个用颜色计算单元格的代码,这里是

function countColor(countRange,colorRef) {
  var activeRg = SpreadsheetApp.getActiveRange();
  var activeSht = SpreadsheetApp.getActiveSheet();
  var activeformula = activeRg.getFormula();
  var countRangeAddress = activeformula.match(/\((.*)\,/).pop().trim();
  var backGrounds = activeSht.getRange(countRangeAddress).getBackgrounds();  
  var colorRefAddress = activeformula.match(/\,(.*)\)/).pop().trim();
  var BackGround = activeSht.getRange(colorRefAddress).getBackground();
  var countCells = 0;
  for (var i = 0; i < backGrounds.length; i++)
    for (var k = 0; k < backGrounds[i].length; k++)
      if ( backGrounds[i][k] == BackGround )
        countCells = countCells + 1;
  return countCells;
};

所以 Google 表格中的公式如下所示:

=countcolor(Sheet1!A:A,C1)

A:A1 是范围,C1 是带有颜色样本的单元格

我的一个朋友帮了我一点忙,做了一个计算文本和颜色的函数,但是文本应该在函数内部输入。 代码如下:

function count_Color_and_text_Cells(countRange,colorRef) { 
var activeRg = SpreadsheetApp.getActiveRange(); 
var activeSht = SpreadsheetApp.getActiveSheet(); 
var activeformula = activeRg.getFormula(); 
var countRangeAddress = activeformula.match(/\((.*)\,/).pop().trim(); 
var backGrounds = activeSht.getRange(countRangeAddress).getBackgrounds(); 
var text = "test" // Text you whant to count
var arrData = activeSht.getRange(countRangeAddress).getDisplayValues() 
var colorRefAddress = activeformula.match(/\,(.*)\)/).pop().trim(); 
var BackGround = activeSht.getRange(colorRefAddress).getBackground(); 
var countCells = 0; 
for (var row = 0; row < backGrounds.length; row++) 
for (var col = 0; col < backGrounds[row].length; col++) 
if ( backGrounds[row][col] == BackGround ) 
if (arrData[row][col].match(text)) 
countCells = countCells + 1; 
return countCells; 

}

我需要的是在函数中创建文本标准,这样我就可以选择一个范围,输入一个特定的文本并获得结果。期待它看起来像这样:

=countcolor(Sheet1!A:A,"TextSample",C1)

因此它可以计算用户在公式中键入的颜色和文本正确的单元格。

谢谢你,祝你有美好的一天!

【问题讨论】:

  • text 添加为该函数的可接受参数?
  • @TheMaster 你能解释一下吗?

标签: javascript google-apps-script google-sheets


【解决方案1】:

您可以像这样提供文本作为参数:

function count_Color_and_text_Cells(countRange,text,colorRef) { 

不要再次声明text,即删除var text=''

阅读和练习:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多