Page 341 - Microsoft Office Excel 2003 Programming Inside Out
P. 341

Developing Class Modules

                             An item is removed from the collection by calling the Remove method and specifying either
                             the relative position of the object or the value of the Name property. In either case, the
                             Remove method from the Collection object is used to remove the item from the underlying
                             collection.

                             Public Sub Remove(key As Variant)

                             MyPlants.Remove key
                             End Sub
                                                                                                             Chapter 14
                             In the same fashion, the Count method returns the number of items in the collection by call­
                             ing the underlying Count method associated with the Collection object.

                             Public Function Count() As Long
                             Count = MyPlants.Count

                             End Function
                             The Clear method is useful if you want to delete all the objects in the collection. This routine
                             just destroys the underlying Collection object and then creates a new instance of the Collection
                             object.

                             Public Sub Clear()

                             Set MyPlants = Nothing
                             Set MyPlants = New Collection
                             End Sub

                             The Item method returns a single item from the collection. Like the Remove and Count meth­
                             ods, this item simply calls the Collection object’s Item method.

                             Public Function Item(key As Variant) As Plant

                             Set Item = MyPlants.Item(key)
                             End Function

                             The following routine is a macro that iterates through the collection class that was just cre­
                             ated. The macro begins by creating a new Plants object named MyPlants, which contains a
                             collection of Plant objects. Then the code calls the SampleData method, which simply adds
                             some sample objects to the collection.










                                                                                                       315
                                                                                                Part 4:  Advanced VBA
   336   337   338   339   340   341   342   343   344   345   346