按指定的不同颜色计算单元格值

时间:2012-05-22 13:42:25

标签: vba excel-vba excel-vba-mac excel

请按照指定的不同颜色计算单元格值来提供帮助。

在一张纸中,一些单元格填充红色,一些单元格填充蓝色,一些单元格填充绿色。输出应该是细胞计数红色,细胞计数蓝色和细胞计数绿色分开。

这是我尝试过的:

Function CountByColor(InputRange As Range, ColorRange As Range) As Long

    Dim cl As Range
    TempCount As Long
    ColorIndex As Integer

    ColorIndex = ColorRange.Cells(1, 1).Interior.ColorIndex TempCount = 0
    For Each cl In InputRange.Cells
        If cl.Interior.ColorIndex = ColorIndex
        Then
        TempCount = TempCount + 1
        End If
    Next cl
    Set cl = Nothing CountByColor = TempCount
End Function

1 个答案:

答案 0 :(得分:2)

您的功能按预期工作: -

Function CountByColor(InputRange As Range, ColorRange As Range) As Long
    Dim cl As Range, TempCount As Long, ColorIndex As Integer
    ColorIndex = ColorRange.Cells(1, 1).Interior.ColorIndex
    TempCount = 0
    For Each cl In InputRange.Cells
        If cl.Interior.ColorIndex = ColorIndex Then
            TempCount = TempCount + 1
        End If
    Next cl
    Set cl = Nothing
    CountByColor = TempCount
End Function

公式:

=CountByColor(A:A,A2)

此处A2 Cell填充Green,绿色索引为14

结果:

对于我的工作表,我得到了结果

3

基本上你需要执行这个公式三次以得到三个结果

=CountByColor(A:A,A2)   // A2 filled with Green
=CountByColor(A:A,A6)   // A6 filled with Red
=CountByColor(A:A,A9)   // A9 filled with Blue