访问项目集合中的属性

时间:2014-02-19 03:20:37

标签: excel vba excel-vba excel-2010

我有一组课程。我似乎无法访问我班级的属性。这是我可以做的事情吗?

这是我的班级clsProj:

Option Explicit
Private pValue As String


Public Property Get Value() As String
    Value = pValue
End Property

Public Property Let Value(tempv As String)
    pValue = tempv
End Property

我的分:

Sub testtt()

Set cp = New Collection

cp.Add clsProj, "AAA"
cp.Add clsProj, "BBB"

cp("AAA").Value = "OK"

MsgBox (cp("AAA").Value)

End Sub

总之,我有一个类clsProj的集合,我用字符串索引(这只是一个测试子),我想访问给定集合项ex:AAA的clsProj的属性。这有什么不对的地方?我似乎无法得到它。

1 个答案:

答案 0 :(得分:2)

课程有点难以理解,但是当你这样做时,它们确实非常有用。也许这会有所帮助:

Sub testtt()

    Dim cp As Collection
    Set cp = New Collection

    Dim blabla As clsProj
    Set blabla = New clsProj

    Dim blabli As clsProj
    Set blabli = New clsProj

    blabla.Value = "OK"
    blabli.Value = "KO"

    cp.Add blabla, "AAA"
    cp.Add blabli, "BBB"

    MsgBox (cp("AAA").Value)
    MsgBox (cp("BBB").Value)

    Set blabla = Nothing
    Set blabli = Nothing

End Sub


编辑:混合CollectionClassFor...Next循环:

Sub testtt()

    Dim cp As Collection
    Set cp = New Collection

    Dim blabla As clsProj
    Dim i As Integer
    For i = 1 To 10
        Set blabla = New clsProj

        '"OK" value + a special character from ASCII table
        blabla.Value = "OK " & Chr(32 + i)

        cp.Add blabla, CStr("AAA" & i)

        Set blabla = Nothing
    Next i

    'Test calling collection by key
    MsgBox cp("AAA5").Value

    'Test calling collection by item number and print it in
    '"Immediate" window (ctrl+g to show that window from VBA editor)
    For i = 1 To cp.Count
        Debug.Print cp(i).Value
    Next i

End Sub