Hey guys I need help please. I wrote code that conditionally formats cells that contain a specific number then it sorts the colored cells to the bottom and finally I wan't to sum the cells that only contain the interior color. The problem is when I execute the function sumbycolor excel doesn't recognize the cells colors and sums the entire column (color or no color). How do I fix This? Thank you!
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
Excel's Conditional Format does not change the various color properties of the cell itself (eg Interior.Color, Interior.ColorIndex, Font.Color, etc). In order to work with this, you need to work with the actual Conditional Format formula(s), and test the cell to see which, if any, is applicable.
It's easy to write a short routine where you have control over the colors and conditions.
For a general purpose routine, you can try EJ Gundersons MathByColor routines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.