Getting some weird behavior in VB6 and I'm throwing a net out for some answers.
I have a collection in which I use to store a group of custom forms of the same type.
Dim formCollection As New Collection
Public Sub AddForm()
Dim newForm As New frmCustomForm
formCollection.Add(newForm)
End Sub
Then in another routine I iterate through the collection. But as I cast the variant back into the custom form class I get a type casting error ("Run-time error '13': Type mismatch").开发者_JS百科
Public Sub Foo()
Dim someForm As frmCustomForm
Dim iterator As Integer
For iterator = 1 To formCollection.Count
Set someForm = formCollection.Item(iterator) ' The error appears here
someForm.SomeProperty = 3
Next iterator
End Sub
It seems that though initially it was of the custom form class, as it got stored into the collection it lost it's type and can't be casted back. Further, if I put a breakpoint before I try casting the stored form and then I examine the object through Locals, it's lost all the class specific information such as property names, which appear only as 'Item 1', 'Item 2', 'Item 3', etc.
Any ideas?
You can't use parentheses like this in VB6. Try this
formCollection.Add newForm
or this
Call formCollection.Add(newForm)
In your case parentheses force VB6 to evaluate the default property of the object reference and this gets stored in the collection, not the form reference.
Usually you get an extra space in the IDE just before the opening bracket like this
formCollection.Add (newForm)
which should make you extra suspicious.
Try:
Public Sub Foo()
Dim someForm As frmCustomForm
For Each someForm In formCollection
someForm.SomeProperty = 3
Next
End Sub
Scripting.Dictionary may help you better than Collection. It is powerful and faster than Collections. You will need to reference scrrun.dll in your Project.
精彩评论