按背景颜色计算行数失败

时间:2018-02-20 08:19:15

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

嘿伙计们,我在google sheet excel,我想计算有多少行以背景颜色为基础。

我有下一个代码:

function countColoredCells(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;
};

function onOpen() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Contar",
    functionName : "countColoredCells"
  }];
  spreadsheet.addMenu("Contar numero de casillas por color", entries);
}

Code

但是当我把下一个代码放在哪里时?显示错误。发生了什么?

=countcoloredcells(B1:B9,A1)

Error here

Error log here

Error with change of code suggested by Chris W

Error with change of code suggested by Chris W PART 2

3 个答案:

答案 0 :(得分:1)

当您运行activeformula.match(/\((.*)\,/)时,我认为有.match()returning null的情况,因此您无法调用.pop()。 你必须做这样的事......

var match = activeformula.match(/\((.*)\,/);
if(match) var countRangeAddress = match.pop().trim(); //if match is not null...

但当然要处理在脚本的其余部分没有该变量。

答案 1 :(得分:1)

您发布的脚本使用了一种获取范围参数的不寻常方法。它在正则表达式失败,因为在您的位置,表格使用;作为分隔符而不是,使匹配为空。无论如何,直接采取论点应该有效。因此,请尝试更改原始代码

来自

var countRangeAddress = activeformula.match(/\((.*)\,/).pop().trim();
  var backGrounds = activeSht.getRange(countRangeAddress).getBackgrounds();
  var colorRefAddress = activeformula.match(/\,(.*)\)/).pop().trim();

var countRangeAddress = countRange
  var backGrounds = activeSht.getRange(countRangeAddress).getBackgrounds();
  var colorRefAddress = colorRef

您还可以尝试将{regex匹配,替换为;(例如match(/\((.*)\;/)。)

用法应该是:

=countcoloredcells("B1:B9";"A1")

答案 2 :(得分:0)

改为使用此代码。 参数需要作为字符串传递。

/**
* Usage countColoredCells("A1:B3";"C5")
* @param {range} countRange Range to be evaluated
* @param {colorRef} colorRef Cell with background color to be searched for in countRange
* @return {number}
* @customfunction
*/

function countColoredCells(countRange,colorRef) {
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();

  var backgrounds = activeSheet.getRange(countRange).getBackgrounds();
  var colorRefBackground = activeSheet.getRange(colorRef).getBackground();

  var count = 0;

  for(var i=0;i<backgrounds.length;i++)
    for(var j=0;j<backgrounds[0].length;j++)
      if( backgrounds[i][j] == colorRefBackground )
        count=count+1;
  return count;
};