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

Excel 按指定的不同颜色计算单元格值,excel,vba,macos,Excel,Vba,Macos,请根据指定的不同颜色计算单元格值,需要您的帮助 在一张纸中,一些单元格填充了红色,一些单元格填充了蓝色,一些单元格填充了绿色。输出应分别为红色单元格计数、蓝色单元格计数和绿色单元格计数 这就是我尝试过的: Function CountByColor(InputRange As Range, ColorRange As Range) As Long Dim cl As Range TempCount As Long ColorIndex As Integer C

请根据指定的不同颜色计算单元格值,需要您的帮助

在一张纸中,一些单元格填充了红色,一些单元格填充了蓝色,一些单元格填充了绿色。输出应分别为红色单元格计数、蓝色单元格计数和绿色单元格计数

这就是我尝试过的:

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

您的功能按预期工作:-

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
公式: 这里的
A2单元格
绿色
填充,绿色索引为
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

我试过使用下面的codeFunction CountByColor(InputRange作为范围,ColorRange作为范围)作为范围,TempCount作为长度,COLORRINDEX作为整数ColorRange=ColorRange.Cells(1,1).Interior.ColorIndex TempCount=0,用于输入范围中的每个cl。单元格如果cl.Interior.ColorIndex=ColorIndex,则TempCount=TempCount+1结束如果下一个cl设置cl=Nothing CountByColor=TempCount结束函数,但该函数不起作用……请帮助我您可以编辑问题并发布代码吗有?@arul->这是VBA中的一个解决方案。这是一个自定义构建的函数,可以插入到模块中,并由上面的Siva公式部分使用。如果要从另一个过程内部调用它,请按名称调用它,并传递两个范围进行求值。
=CountByColor(A:A,A2)   // A2 filled with Green
=CountByColor(A:A,A6)   // A6 filled with Red
=CountByColor(A:A,A9)   // A9 filled with Blue