Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for each loop with user defined class objects in vba

Tags:

class

excel

vba

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
like image 258
Chris Avatar asked Aug 22 '26 06:08

Chris


2 Answers

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
like image 84
Chris Avatar answered Aug 24 '26 19:08

Chris


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
like image 30
InContext Avatar answered Aug 24 '26 19:08

InContext



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!