使用sumbycolor函数时,Excel不会识别内部颜色

时间:2015-02-28 21:13:02

标签: excel vba colors sum excel-formula

嘿,伙计们,我需要帮助。我编写了有条件地格式化包含特定数字的单元格的代码,然后将彩色单元格排序到底部,最后我不想对仅包含内部颜色的单元格求和。问题是当我执行函数sumbycolor excel不识别单元格颜色并且对整个列进行求和(颜色或没有颜色)。我该如何解决?谢谢!

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

Sub MySheet

'Conditional  formatting
   Range("A1").CurrentRegion.Select
   Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$F1=99999"
   Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
   With Selection.FormatConditions(1).Interior
      .PatternColorIndex = xlAutomatic
      .Color = 65535
      .TintAndShade = 0
   End With
   Selection.FormatConditions(1).StopIfTrue = False

 'Sort by color column C
   Dim sht As Worksheet
   Dim rngSort As Range
   Dim rngTable As Range
   Set sht = ActiveSheet

   RowCount = sht.Range("A1").End(xlDown).Row
   Set rngSort = sht.Range("A1:A" & RowCount)
   Set rngTable = Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell))

    sht.Sort.SortFields.Clear
    sht.Sort.SortFields.Add(rngSort, _
       xlSortOnCellColor, xlDescending, , _
       xlSortNormal).SortOnValue.Color = RGB(255, 255, 0)
   With sht.Sort
      .SetRange rngTable
      .Header = xlYes
      .MatchCase = False
      .Orientation = xlTopToBottom
      .SortMethod = xlPinYin
      .Apply
   End With

 'Sum by color
   lr = Cells(Rows.Count, "O").End(xlUp).Row - 1
   sumRange = Range("O2:O" & lr).Address
   lr = Cells(Rows.Count, "P").End(xlUp).Row - 1
   sumRange2 = Range("P2:P" & lr).Address
   lr = Range("B" & Rows.Count).End(xlUp).Row
   CellColor = Range("B" & lr).Address

   Range("C1").Select
   ActiveCell.End(xlDown).Offset(9, 0).Formula = "=(ColorFunction(" & CellColor & "," & sumRange & ",TRUE)+ColorFunction(" & CellColor & "," & sumRange2 & ",TRUE))" 

End Sub

1 个答案:

答案 0 :(得分:0)

Excel的条件格式不会更改单元格本身的各种颜色属性(例如Interior.Color,Interior.ColorIndex,Font.Color等)。为了使用它,您需要使用实际的条件格式公式,并测试单元格以查看哪些(如果有)适用。

编写一个可以控制颜色和条件的简短例程很容易。

对于通用例程,您可以尝试EJ Gundersons MathByColor 例程。