计算使用条件格式设置颜色的位置

我使用了条件格式= B2 = MAX(相对范围)来突出显示所有行中包含的最大值。

我试图计算在这个列中出现了多less个X的实例。

即列A2:1000 – 这将有5个高亮实例。

Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean) Dim rCell As Range Dim lCol As Long Dim vResult lCol = rColor.Interior.ColorIndex If SUM = True Then For Each rCell In rRange If rCell.Interior.ColorIndex = lCol Then vResult = WorksheetFunction.SUM(rCell, vResult) End If Next rCell Else For Each rCell In rRange If rCell.Interior.ColorIndex = lCol Then vResult = 1 + vResult End If Next rCell End If ColorFunction = vResult End Function 

这是我从http://www.extendoffice.com/documents/excel/1155-excel-count-sum-cells-by-color.html取得的代码。 由于我的条件格式,计数失败。 它读取单元格为“白色”,因为它不解释条件格式。

以下是一些数据如何排列以供参考。 数据的示例快照

使用公式=B2=MAX(Relative Range)确定基于总和的条件格式设置规则:

 Option Explicit Public Function ColorFunction(rRange As Range, Optional getSum As Boolean = False) Dim cel As Range, r As Long, c As String, ur As Range, lr As Long, v As Long For Each cel In rRange With cel If Len(cel) > 0 And IsNumeric(cel) Then 'IsDate(cel) If .FormatConditions.Count = 1 Then If InStr(1, .FormatConditions.Item(1).Formula1, "#") = 0 Then v = .Value2 c = Split(.Address(True, False), "$")(0) lr = .Parent.UsedRange.Rows.Count Set ur = .Parent.Range(c & "2:" & c & lr) If WorksheetFunction.Max(ur) = v Then r = r + IIf(getSum, v, 1) End If End If End If End With Next ColorFunction = r End Function 

这段代码对你的情况非常具体:

  • 它只适用于一个条件格式规则
  • 该规则是MAX(范围)并且在主逻辑中被硬编码
  • 它不是基于颜色(在某些情况下可能是一个优势)
  • 使用date值而不是数字将IsNumeric(cel)IsDate(cel)

我使用了以下条件格式规则(4列):

  • =A2=MAX(A$2:A$7)
  • =B2=MAX(B$2:B$7)
  • =C2=MAX(C$2:C$7)
  • =D2=MAX(D$2:D$7)

CF经理: CF经理

结果: 在这里输入图像描述

注意:@ Tim的评论有助于确定其他关键要求,如UDF

确定总行数(初始答案):

 Option Explicit Sub countRowsWithConditionalColor() Dim totalRows As Long, rng As Range, lColor As Long, cel As Range, lRow As Long lRow = ActiveSheet.UsedRange.Rows.Count Set rng = ActiveSheet.Range("A1:A" & lRow) lColor = RGB(255, 0, 0) 'change color accordingly Application.ScreenUpdating = False With rng .AutoFilter Field:=1, Criteria1:=lColor, Operator:=xlFilterCellColor For Each cel In rng If cel.RowHeight > 0 Then totalRows = totalRows + 1 If cel.Row > lRow Then Exit For Next .AutoFilter End With Application.ScreenUpdating = True MsgBox "TotalRows: " & totalRows End Sub 

  • closuresScreenUpdating,所以这个过程对用户是不可见的(并且更快)
  • 在列1上应用AoutoFileter,按照颜色过滤,“Operator:= xlFilterCellColor”

    • 遍历列中的所有单元格
    • 如果当前单元格的高度> 0(可见)增加计数器(totalRows)
  • 重新启动ScreenUpdating

  • 显示总行数

笔记:

  • 我的testing颜色(vbRed)是由条件格式规则生成的
  • Tim的build议rColor.DisplayFormat.Interior.ColorIndex可能更适合您的代码,如果它的工作

保罗的答案很好,很容易理解。 只要确保通过在“Field:=”之后更改值来select右栏。 1代表col。 A,B等。另外,确保在运行macros之前打开自动filter。 并且在End With后使用ActiveSheet.ShowAllData代替.AutoFilter位。 这样它不会禁用你的自动filter。