I am trying to iterate through dictionary but encounter the error "Object required". The related code is given below.
First, I create a dictionary.
Dim customers
Set customers = CreateObject("Scripting.Dictionary")
I also define class of "cCustomer", then use the dictionary like this.
Set customer = New cCustomer
customer.Init location, first, last
customers.Add location, customer
Then I use "For Each" to iterate.
Dim cc
For Each cc in customers.items
...
Next
This is OK. But I really want to declare "cc" with type.
Dim cc As cCustomer
But if I do this, VB runtime complains "Object required" at the line of "For Each". I think it is somehow related to the missing of type declaration when creating the dictionary? I am still new to VB. Thanks for the help.
MORE: why this is not duplicate...
I have tried the solution suggested by the link, namely, (a) using Dictionary instead of "Scripting.Dictionary", and (b) "Dim cc As Variant". It works as before but if I feed "cc" into a function whose argument has specific type it still fails.
Public Function foo(customer As cCustomer) As String
...
End Function
Dim cc As Variant
For Each cc in customers.items
foo(cc)
Next
The error is "ByRef argument type mismatch".
That's the reason I really need to declare "cc" as "cCustomer", but it has error of "Object required".
Dim cc As cCustomer
For Each cc In customers.items
...
Per comments
- tried "Dim cc As Object", doesn't work ("Object required").
- tried "remove Dim cc", doesn't work either ("ByRef argument type mismatch").
I could do "ByVal" in the function definition or use another variable, but that would involve extra copy. Something like type casting might help...
for each cc in customers
? Also, make sure that custmers definitley is initalized in the scope of thefor each
loop. – CMaster