1
votes

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...

1
Have you tried changing it to just for each cc in customers ? Also, make sure that custmers definitley is initalized in the scope of the for each loop.CMaster
if you leave off the type in VB6/sbscript it will be a Variant, not an Object. You could try to change your declaration to " As Object". also, any reason you are using CreateObject? It's better to include the library, and use the Dictionary type directly, because you'll get a bit of intellisense, and errors may get caught sooner.Jeremy

1 Answers

0
votes

It's a bit of a cludge and there may be better ways of doing it, but how about this:

dim loc as variant
dim cc as cCustomer

for each loc in Customers
    set cc = Customers(loc)
    foo(cc)
next loc

It may even be possible to do foo (Customers(loc)), but I suspect you will get the type mismatch error again. I don't think you can pass an object with byval