javascript - 按背景颜色计算行数失败

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

大家好,我在 google sheets 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

最佳答案

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

来自

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

您也可以尝试将正则表达式匹配 , 替换为 ;(例如 match(/\((.*)\;/) .)

用法应该是这样的:

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

关于javascript - 按背景颜色计算行数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48880585/

相关文章:

PHP/JQuery - PHP 脚本每 5 秒运行一次,但其中的 jquery 函数仅运行一次

javascript - Owl carousel .destroy() 删除不相关的 div

javascript - 带有 javascript onclick 的多个 DOM 操作函数

MySql Regexp 结果词已知词的一部分

google-apps-script - 反向缩短的 URL 以获取 Google 表格中缩短前的原始 URL

charts - Google 电子表格 sheet.getCharts() 仅在打开电子表格时有效?

javascript - Kendo UI 日期选择器按周捕获

regex - .htaccess 重写 URL 启动/重定向

c# - 提高多个字符串比较的效率(正则表达式?)

google-apps-script - 发布新版 Google 表格插件