Excel VBA:从集合中检索自定义对象

时间:2015-10-08 12:59:39

标签: excel vba excel-vba

我有一个包含姓氏,姓氏和部分的人物对象。这些是存储在excel表中的列中,但我需要提取它们并将它们作为Person对象的集合传递。我可以创建对象并显然将其中的所有39个添加到集合中,但是当我对集合进行预测时,我什么也得不到。 我有debug.print似乎显示正在创建的单个对象,但是当我打印出检索到的对象时,我得到39行空白。

Public Function PeopleList() As Collection

    Set PeopleList = New Collection
    Dim newPerson As Person
    Set newPerson = New Person
    'hide active sheet and go to sheet holding class information
    SwitchSheets
    lastLine = GetFirstFreeLine(SHEETNAME, 1)
    For x = 2 To lastLine
        newPerson.idNumber = Worksheets(SHEETNAME).Cells(x, 1)
        newPerson.Forename = Worksheets(SHEETNAME).Cells(x, 2)
        newPerson.Surname = Worksheets(SHEETNAME).Cells(x, 3)
        newPerson.SectionName = Worksheets(SHEETNAME).Cells(x, 4)

        'Test print the newPerson object
        Debug.Print (newPerson.Forename & " " & newPerson.Surname & " " & newPerson.SectionName)

        PeopleList.Add newPerson
    Next

    For Each newPerson In PeopleList
        Debug.Print ("Person : " & newPerson.Forename & " " & newPerson.Surname & " " & newPerson.SectionName)
    Next
'restore active sheet
    ReturnSheets

End Function

1 个答案:

答案 0 :(得分:1)

你需要在你的循环

中创建New对象

Public Function PeopleList() As Collection

Set PeopleList = New Collection
Dim newPerson As Person

'hide active sheet and go to sheet holding class information
SwitchSheets
lastLine = GetFirstFreeLine(SHEETNAME, 1)
For x = 2 To lastLine
    Set newPerson = New Person
    newPerson.idNumber = Worksheets(SHEETNAME).Cells(x, 1)
    newPerson.Forename = Worksheets(SHEETNAME).Cells(x, 2)
    newPerson.Surname = Worksheets(SHEETNAME).Cells(x, 3)
    newPerson.SectionName = Worksheets(SHEETNAME).Cells(x, 4)

    'Test print the newPerson object
    Debug.Print (newPerson.Forename & " " & newPerson.Surname & " " & newPerson.SectionName)

    PeopleList.Add newPerson
Next

For Each newPerson In PeopleList
    Debug.Print ("Person : " & newPerson.Forename & " " & newPerson.Surname & " " & newPerson.SectionName)
Next
'restore active sheet ReturnSheets

End Function