Getting 'Object Required' error when I used a collection

  • Thread starter Thread starter joyo
  • Start date Start date
J

joyo

I copied the code from Getz book to create a my own
collection. I just keep getting the error message.
"Compile error"
"Object required"

What is the reason? Below is my code.

Thank you for your help.

joyo

'Creted a class module, "StringCollection"
Option Explicit
Private MyCollection As Collection
Private Sub Class_Initialize()
Set MyCollection = New Collection
End Sub
Public Sub MyAdd(MyString As String)
MyCollection.add MyString
End Sub
Public Sub Remove(ByVal varID As Variant)
'Call remove method of private collection object
MyCollection.Remove (varID)
End Sub
Public Function MyItem(ByVal varID As Variant) As String
Set MyItem = MyCollection(varID)
End Function
Property Get Count() As Long
'Return Count property of private collection
Count = MyCollection.Count
End Property


'Here is my code in the form
Dim str As String
Dim TestCollection As StringCollection
Set TestCollection = New StringCollection
With TestCollection
.MyAdd ("Message1")
.MyAdd ("Message2")
.MyAdd ("Message3")
End With
MsgBox TestCollection.Count 'print 3
Dim i As Integer
For i = 1 To TestCollection.Count
str = TestCollection.MyItem(1)
MsgBox str
Next i
 
where does the compiler tell you the error occurs?

compiling by eye, I guess that
Public Function MyItem(ByVal varID As Variant) As String
Set MyItem = MyCollection(varID)
End Function

should probably not have the 'Set', like this:
 
Back
Top