3

The code is here and you get a Run-time error '424' Object required on the first line of the for each statement

Public Sub test()

Dim a As clsTest
Dim dic As Dictionary
Dim tmpObj As clsTest
Set dic = New Dictionary
Set a = New clsTest
dic.Add "1", a
dic.Add "2", New clsTest
dic.Add "3", New clsTest

For Each tmpObj In dic.Items '--<< error: Run-time error '424' Object required
  Debug.Print tmpObj.i
Next tmpObj

Stop
End Sub
0

3 Answers 3

2

Three options

1)

Dim tmpObj As Variant

For Each tmpObj In dic.Items

  Debug.Print tmpObj.i

Next tmpObj

2)

for i = 0 to dic.Count - 1
    set tmpObj = dic.Items(i)
   ...

3)

Public Sub test()

Dim a As clsTest
Dim dic As Dictionary
Dim vTmpObj As Variant
Dim tmpObj As clsTest
Set dic = New Dictionary
Set a = New clsTest
dic.Add "1", a
dic.Add "2", New clsTest
dic.Add "3", New clsTest

For Each vTmpObj In dic.Items
  Set tmpObj = vTmpObj
  Debug.Print tmpObj.i
Next vTmpObj
Sign up to request clarification or add additional context in comments.

Comments

2

you have two choices:. Declare the variable as a variant:

Dim tmpObj As Variant

For Each tmpObj In dic.Items

  Debug.Print tmpObj.i

Next tmpObj

Or iterate over the collection:

Dim tmpObj As clsTest

For i = 0 To dic.Count - 1

    Set tmpObj = dic.Items(i)

    Debug.Print tmpObj.i

Next i

2 Comments

Yes I've been using the variant option, but it loses intellisense, so I have to keep on changing the type from variant to clsTest when developing and back when running.
updated my code. tmpObj can be strongly typed to your custom class in this way and you have intellisense on values.
1

A Dictionary.Items() is a variant array so For Each needs to have tmpObj as a Variant.

An alternative using a typed tmpObj is:

for i = 0 to dic.Count - 1
    set tmpObj = dic.Items(i)
    ...

1 Comment

It would be more usable if it returned an array of the object. Yes I had been using variant. I just thought I'd ask.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.