首页 / 知识

关于excel:计算具有相同背景色的单元格列表

2023-04-14 13:52:00

Count a list of cells with the same background color

每个单元格包含一些文本和背景色。 所以我有一些蓝色的单元格和一些红色的单元格。 我用什么功能来计算红细胞的数量?

我尝试=COUNTIF(D3:D9,CELL("color",D3))没有成功(D3为红色)。


Excel无法使用其内置函数来收集该属性。如果您愿意使用某些VB,请在此处回答所有与颜色有关的问题:

http://www.cpearson.com/excel/colors.aspx

站点示例:

The SumColor function is a color-based
analog of both the SUM and SUMIF
function. It allows you to specify
separate ranges for the range whose
color indexes are to be examined and
the range of cells whose values are to
be summed. If these two ranges are the
same, the function sums the cells
whose color matches the specified
value. For example, the following
formula sums the values in B11:B17
whose fill color is red.

=SUMCOLOR(B11:B17,B11:B17,3,FALSE)


如果单元格的颜色设置为负值,则工作表公式=CELL("color",D3)返回1(否则返回0)。

您可以使用一些VBA解决此问题。将此插入到VBA代码模块中:

1
2
3
Function CellColor(xlRange As Excel.Range)
    CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function

然后使用功能=CellColor(D3)显示D3.ColorIndex


我刚刚创建了它,它看起来更简单。您将获得以下两个功能:

1
=GetColorIndex(E5)  <- returns color number for the cell

来自(单元格)

1
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14

来自(单元格范围,要计算的色号)

示例显示颜色为14的单元格的百分比

1
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )

在一个模块中创建这2个VBA函数(按Alt-F11)

打开+文件夹。双击Module1

只需在下面粘贴此文本,然后关闭模块窗口(然后必须将其保存):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Function GetColorIndex(Cell As Range)
  GetColorIndex = Cell.Interior.ColorIndex
End Function

Function CountColorIndexInRange(Rng As Range, TestColor As Long)
  Dim cnt
  Dim cl As Range
  cnt = 0

  For Each cl In Rng
    If GetColorIndex(cl) = TestColor Then
      Rem Debug.Print">" & TestColor &"<"
      cnt = cnt + 1
    End If
  Next

  CountColorIndexInRange = cnt

End Function

我需要解决绝对相同的任务。我用不同的背景颜色对表格进行了视觉划分。搜寻Internet,我已经找到此页面https://support.microsoft.com/kb/2815384。不幸的是,它不能解决问题,因为ColorIndex引用了一些不可预测的值,因此,如果某些单元格具有一种颜色的细微差别(例如,颜色亮度的不同值),则建议的功能会对它们进行计数。下面的解决方案是我的解决办法:

1
2
3
4
5
6
7
8
9
10
Function CountBgColor(range As range, criteria As range) As Long
    Dim cell As range
    Dim color As Long
    color = criteria.Interior.color
    For Each cell In range
        If cell.Interior.color = color Then
            CountBgColor = CountBgColor + 1
        End If
    Next cell
End Function

是的,VBA是必经之路。

但是,如果您不需要具有自动计算/更新具有特定颜色的单元格数量的公式的单元格,则可以选择使用"查找和替换"功能并格式化该单元格以使其具有适当的颜色颜色填充。

点击"查找全部"将为您提供在对话框左下方找到的单元格总数。

enter image description here

如果您的搜索范围很大,这将特别有用。 VBA脚本将非常慢,但是"查找和替换"功能仍将非常快。


背景色计算列表红色

最新内容

相关内容

猜你喜欢