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
答案 0 :(得分:0)
Excel的条件格式不会更改单元格本身的各种颜色属性(例如Interior.Color,Interior.ColorIndex,Font.Color等)。为了使用它,您需要使用实际的条件格式公式,并测试单元格以查看哪些(如果有)适用。
编写一个可以控制颜色和条件的简短例程很容易。
对于通用例程,您可以尝试EJ Gundersons MathByColor 例程。