在Excel中,需要计算从条件格式中着色的单元格,然后创建特定结果的报告

问题描述 投票:1回答:1

我有一个带有名字的电子表格(在A栏中),每个名字都有10个数字(B-K列)。我正在使用条件格式来突出显示包含与其他条件匹配的数字的绿色单元格。

现在,我需要为每个名称计算绿色突出显示的单元格,并创建结果报告。例如,我需要一个报告,列表或图表,显示以绿色突出显示的10个单元格中的8个的人员的所有名称。 (带有8个绿色单元的名字= Joe,Mike,Sue)

我使用以下公式来计算绿色单元格的每一行,但列表将有太多名称,以便为每一行重复此公式。所以我没有根据这个公式的结果创建报告,因为我需要一个更好的公式来进行初始绿细胞计数。然后,我需要有关创建最终报告的最佳方法的帮助。谢谢!

enter image description here

Public Sub CountColorCells()
    'Variable declaration
    Dim rng As Range
    Dim lColorCounter As Long
    Dim rngCell As Range
    'Set the range
    Set rng = Sheet1.Range("B2:K2")
    'loop throught each cell in the range
    For Each rngCell In rng
        'Checking Green color
        If Cells(rngCell.Row, rngCell.Column).DisplayFormat.Interior.Color = _
                                                       RGB(169, 208, 142) Then
            lColorCounter = lColorCounter + 1
        End If
    Next
    'Display the value in cell L2
    Sheet1.Range("L2") = lColorCounter
 End Sub
excel vba
1个回答
0
投票

我相信你真的需要一个UDF(用户定义的功能)。使用UDF,您可以输入一个看起来像这样的公式

在单元格L2:=CountColorCells(B2:K2)中,UDF将返回该范围内突出显示的单元格的数量。

因此,对您的代码进行一些更改。

首先,你想要将它声明为Function,而不是Sub,因为我们需要返回一个值。

接下来,您的代码接近正确。唯一的问题是,当你在范围内迭代(将更改为函数的输入参数)时,你不需要打破RowColumn。那已经融入了rngCell。所以你的UDF现在看起来像这样(并且工作得非常快)

Public Function CountColorCells(ByRef thisRange As Range) As Long
    Dim lColorCounter As Long
    Dim rngCell As Range
    For Each rngCell In thisRange
        If rngCell.Interior.Color = RGB(169, 208, 142) Then
            lColorCounter = lColorCounter + 1
        End If
    Next
    CountColorCells = lColorCounter
End Function

现在(只是因为我无法帮助它;)),这是我将使用的UDF版本。现在有一些可以添加的红色,绿色和蓝色值的可选参数,以防您想要计算不同的颜色。因此,使用此UDF版本,您可以使用公式=CountColorCells(B2:K2,255,0,0)计算RED单元格。这只是您可以做的一个扩展示例:

Public Function CountColorCells(ByRef thisRange As Range, _
                                Optional ByVal r As Long = 169, _
                                Optional ByVal g As Long = 208, _
                                Optional ByVal b As Long = 142) As Long
    Dim checkColor As Long
    checkColor = RGB(r, g, b)

    Dim lColorCounter As Long
    Dim rngCell As Range
    For Each rngCell In thisRange
        If rngCell.Interior.Color = checkColor Then
            lColorCounter = lColorCounter + 1
        End If
    Next
    CountColorCells = lColorCounter
End Function
© www.soinside.com 2019 - 2024. All rights reserved.