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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13932512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:52:43  来源:igfitidea点击:

for each loop with user defined class objects in vba

excelclassexcel-vbavba

提问by Chris

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

代码在这里,您会在 for each 语句的第一行收到运行时错误 '424' Object required

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

回答by InContext

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

回答by Chris

Three options

三个选项

1)

1)

Dim tmpObj As Variant

For Each tmpObj In dic.Items

  Debug.Print tmpObj.i

Next tmpObj

2)

2)

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

3)

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

回答by Alex K.

A Dictionary.Items()is a variant array so For Eachneeds to have tmpObjas a Variant.

ADictionary.Items()是一个变体数组,因此For Each需要将其tmpObj作为Variant.

An alternative using a typed tmpObjis:

使用 typed 的替代方法tmpObj是:

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