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

我有一个Person对象,包括姓,名和部分。 这些商店在Excel表中的列,但我需要提取这些并将它们作为Person对象的集合传递。 我可以创build对象,显然将其中的39个添加到集合中,但是当我对集合进行foreach时,我什么也得不到。 我有debug.print似乎显示单个对象正在创build好,但是当我打印出检索到的对象时,我得到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 

您需要循环中创buildNew对象:

 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