对于vba中用户定义的类对象的每个循环

时间:2012-12-18 11:59:55

标签: excel class excel-vba vba

代码在这里,你得到每个语句的第一行所需的运行时错误'424'对象

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

3 个答案:

答案 0 :(得分:2)

你有两个选择:将变量声明为变体:

Dim tmpObj As Variant

For Each tmpObj In dic.Items

  Debug.Print tmpObj.i

Next tmpObj

或遍历集合:

Dim tmpObj As clsTest

For i = 0 To dic.Count - 1

    Set tmpObj = dic.Items(i)

    Debug.Print tmpObj.i

Next i

答案 1 :(得分:2)

三个选项

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

答案 2 :(得分:1)

Dictionary.Items()是变体数组,因此For Each需要tmpObj作为Variant

使用键入的tmpObj的替代方法是:

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