Option Explicit
Private pCourseCollection As Collection
Private WithEvents pCourse As Course
'it may seem redundant to wrap a collection object, but it is a good practice
'by giving you more control over your objects and providing code
'that is easier to understand and maintain
'this is a readonly property. No Property Set.
'we do not want to allow direct access to create 'stand-alone' course objects.
'Access to the Course object and all child objects will be managed
'by this parent class. You should change this limitation only if you think it is necc.
'
'the index is a variant to allow an integer or string
'this will allow you to refer to a course object by position or Course Title
'same as Sheets("Sheet1") or Sheets(1)
'VBA does not provide overloading so this is the only way we can provide
'this flexibility while using only one argument
'
'this is the default property
'see
'http://www.cpearson.com/excel/DefaultProperty.htm
Public Property Get Courses(Index As Variant) As Course
'you will need to validate the index before using it
Set Courses = pCourseCollection(Index)
Set pCourse = Courses
End Property
'read only count of course objects
Public Property Get CoursesCount() As Integer
CoursesCount = pCourseCollection.Count
End Property
'require the minimum amount of information to actually
'create a valid 'Course' object
Public Function AddCourse(Title As String, Description As String) As Boolean
If Not CourseExists(Title) Then
Dim c As New Course
c.Title = Title
c.Description = Description
pCourseCollection.Add c, Title
Else
Err.Raise 457, , "This key is already associated with an element of this collection" & vbCr & "The course, """ & Title & """, already exists..."
End If
End Function
Public Function RemoveCourse(Title As String) As Boolean
If CourseExists(Title) Then
pCourseCollection.Remove Title
End If
End Function
Public Function CourseExists(Title As String) As Boolean
On Error Resume Next
Dim c As New Course
Set c = pCourseCollection(Title)
If Err.Number <> 0 Then Exit Function
CourseExists = True
End Function
Private Sub Class_Initialize()
'this is where you would load the data for all of your objects
'set up defaults, ect...
Set pCourseCollection = New Collection
End Sub
Private Sub pCourse_UpDate(Instance As Course, OldTitle As String, NewTitle As String)
Dim SaveIndex As Integer
For SaveIndex = 1 To pCourseCollection.Count
If pCourseCollection(SaveIndex).Title = OldTitle Then Exit For
Next
pCourseCollection.Add Instance, NewTitle, SaveIndex
pCourseCollection.Remove SaveIndex
Set pCourse = Nothing
End Sub