With a Collection class, the application calls the Add method of the class, passing any required information. Contrast the previous code with the Add method of the Files class:
Public Function Add(Path As String) As File
Dim objFile As File
' Create the new File object. Set objFile = New File objFile.Path = Path
' Add it to the Private collection. pcolFiles.Add objFile, objFile.ShortName
' Return a pointer to the new object. Set Add = objFile
' Add a file to the collection. colFiles.Add "C:\AUTOEXEC.BAT" In addition to the Add method, the Collection class should also implement the Item and Remove methods, as well as a Count property:
Public Function Item(Key As Variant) As File ' Return an item in the collection. Set Item = pcolFiles.Item(Key) End Function
Public Sub Remove(Key As Variant) ' Remove an item from the collection. pcolFiles.Remove Key End Sub
Property Get Count() As Long ' Return the number of items. Count = pcolFiles.Count End Property
' Private variable to store path. Private pstrPath As String
Property Get Path() As String ' Return stored path value. Path = pstrPath End Property
Property Let Path(strPath As String)
Dim strFile As String
' Clear the collection. Set pcolFiles = New Collection
' Make sure there's a backslash. If Right(strPath, 1) <> "\" Then strPath = strPath & "\" End If
' Get the first file. strFile = Dir(strPath & "*.*", _ vbReadOnly Or vbHidden Or vbArchive Or vbSystem) Do Until Len(strFile) = 0 ' Add it to the collection. Call Add(strPath & strFile) ' Get the next file. strFile = Dir() Loop
' Fill the list box with info. lstFiles.Clear For lngCount = 1 To mobjFiles.Count With mobjFiles.Item(lngCount) lstFiles.AddItem .ShortName & _ Space(12 - Len(.ShortName)) & _ vbTab & .AttributeString & _ vbTab & .Size End With Next