2012-12-18 30 views
2

用戶定義的類對象中的每個循環中的代碼是在這裏,你會得到一個運行時錯誤「424」爲每個語句與在VBA

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 

回答

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 
+0

是的我一直在使用變體選項,但它失去了智能感知,所以在開發時我必須不斷改變從變體到clsTest的類型,並在運行時返回。 – Chris

+0

更新了我的代碼。 tmpObj可以以這種方式強制輸入到您的自定義類中,並且您具有對值的智能感知。 – InContext

1

一個Dictionary.Items()是一個變量數組使For Each需要有tmpObjVariant。使用一個類型tmpObj

另一種方法是:

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

如果它返回了一個對象的數組,它會更有用。是的,我一直在使用變體。我只是想我會問。 – Chris

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