Hi all
I have been trying for a while to come up with a UDF that counts cells by their color and that
Updates automatically as soon as the color changes !
I searched the Board for a solution but couldn't find one.
I have achieved this by using a combination of UDF code, Worksheet event code and a Class module to trap the
ccrpTimer events.
This object belongs to the ccrpTimer.dll Library.
If you don't have it on your System you can Download it from the following link :
http://hem.passagen.se/fylke/?noframe
You will need to establish a reference to this Library via Tools>Reference.
This may sound like too much work for a small result ,however I personally found it a bit challenging.
Ok let's start:
Step1
Defining the UDF. Place this code in a
Standard Module
Code:
' / / Function Purpose :
' ===============
' / / Count Cells By Interior Color.
' / / Uses ccrpTimer Object Via
' / / A Class Module ' TimerClass'
Public Tmr As TimerClass
Function CountColorCells(Rng As Range, RngColor As Range) As Integer
Dim Cll As Range
Dim Clr As Integer
Clr = RngColor.Range("A1").Interior.ColorIndex
For Each Cll In Rng
If Cll.Interior.ColorIndex = Clr Then
CountColorCells = CountColorCells + 1
End If
Next Cll
End Function
Step2
Insert a
Class Module in your Project and name it
TimerClass Via the Properties Window then assign it this Code:
Code:
' / / Code Defines Timer Event
' ====================
Public WithEvents T As ccrpTimer
Private Sub t_Timer(ByVal Milliseconds As Long)
On Error Resume Next
Application.CalculateFull
End Sub
Step3
Place this code in the
Worksheet Module ( The worksheet that contain the Formula/Cells )
Code:
' / / Event Purpose :
' ============
' / / Event To Set The Timer If Target Whithin
' / / Range Of Which Colored Cells Are Counted.
' / / Timer Disabled If Target Outside Range.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim TrgtDpndnts, Rng As Range
Dim T As ccrpTimer
Application.EnableEvents = False
On Error Resume Next
Set TrgtDpndnts = Target.Dependents
If Err.Number = 0 Then
For Each Rng In Target.Dependents
If Left(Rng.Formula, 16) = "=CountColorCells" Then
Set Tmr = New TimerClass
With Tmr
Set .T = New ccrpTimer
.T.Enabled = True
.T.Interval = 80 ' Adjust Interval to suit your System
End With
Exit For
End If
Next
Else
Tmr.T.Enabled = False
End If
Application.EnableEvents = True
End Sub
That's all.
Drawbaks of this technic :
If when you select the Colored cells in order to change their color,the screen starts flickering a little bit .Try increasing the Timer Interval.
Also,these codes could slow down the WorkBook if is large and contains many Formulas.
See you!