I could imagine something like this. Class CTeam would precalculate sum of ages of team members right at the moment when new player is added to the collection. And then just use this number instead of having to loop through all the items and calculate the number. But you'll have to update the value in case member is removed from collection etc. You have to decide if this work is suitable or if you just calculate all the values at the moment when it is needed (means no caching).
You could add and event to the CTeam class as well and so let the subscribers know that new team member was added to the collection. Like in this example UserForm1 is subscriber and it gets informed when publischer which is class CTeam creates new player. HTH
' CTeam Class:
Public Event PlayerWasAdded(player As CPlayer)
Private m_players As VBA.Collection
Private m_sumTeamAge As Single
Private Sub Class_Initialize()
Set m_players = New VBA.Collection
End Sub
Public Sub Add(player As CPlayer)
m_players.Add player, player.Name
m_sumTeamAge = m_sumTeamAge + player.Age
RaiseEvent PlayerWasAdded(player)
End Sub
Public Property Get AverageAge() As Single
If m_players.Count > 0 Then
AverageAge = m_sumTeamAge / m_players.Count
Else
AverageAge = 0
End If
End Property
' UserForm1 Class:
Private WithEvents m_team As CTeam
Private Sub UserForm_Initialize()
Dim i As Integer
Set m_team = New CTeam
For i = 1 To 5
m_team.Add CreateNewPlayer(i)
Next
End Sub
Private Sub m_team_PlayerWasAdded(player As CPlayer)
MsgBox "New player " & player.Name & " was added. Do something ...", vbInformation
End Sub
Private Sub ShowAverageAge_Click()
MsgBox "Average age of team member is: " & m_team.AverageAge, vbInformation
End Sub
Private Sub AddNewPlayer_Click()
m_team.Add CreateNewPlayer(...)
End Sub
Private Function CreateNewPlayer(platerIndex As Integer) As CPlayer
Dim upperbound As Integer: upperbound = 35
Dim lowerbound As Integer: lowerbound = 18
Dim player As CPlayer
Set player = New CPlayer
player.Name = "Player_" & platerIndex
player.Age = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Set CreateNewPlayer = player
End Function