I am using the following code to count the background color and font color of a cells. When I change the background color and font color on cells, I can manually force recalculation by pressing CTRL+ALT+SHIFT+F9. How do I force Excel to auto-calculate when a call in a given range changes? I'm a novice with VBA. Any help is appreciated.
It's been requested that I provide context for this question. Here is a brief explanation:
My mom has a tree farm with 1000 trees. I created a spreadsheet (one cell for each tree) to allow her to rate the health of the trees using a green, yellow, red rating system. Some of the trees were planted in 2020 and others in 2021. Black font color = 2020 and red font color = 2021. She asked if I could calculate stats based on these parameters. So, I found the code pasted here to count cells based on their background and font color and it works just fine. The problem is that I have to press CTRL+ALT+SHIFT+F9 to force the spreadsheet to recalculate. I was hoping to find a way to have it recalculate as she shades a cell or changes the font color. I've attached the spreadsheet as well.
Function ColorInteriorFontCount(SearchRange As Range, colorRange As Range) As Long
Dim cell As Range, a As Range, b As Range, n As Integer
' preload for Union method (will Union with itself in first For loop)
Set b = SearchRange(1).MergeArea(1)
For Each cell In SearchRange
Set a = cell.MergeArea(1)
Set b = Union(a, b)
Next
' a becomes the preload for the next Union; n will be used to exclude
' it from the count if it's not the right color
n = a.Interior.Color = colorRange.Interior.Color
For Each cell In b
If cell.Interior.Color = colorRange.Interior.Color And _
cell.Font.Color = colorRange.Font.Color Then
Set a = Union(cell, a)
End If
Next
ColorInteriorFontCount = a.Count - 1 - n
End Function