Excel VBA:将一个集合从一个类传递给一个模块问题

我一直试图从一个类中的属性返回一个集合到一个正常模块中的例程。 我遇到的问题是,集合在类中的属性(FetchAll)中正确填充,但是当我将集合传递回模块(Test)时,所有条目都填充了列表中的最后一项。

这是标准模块中的testing子例程:

Sub Test() Dim QueryType As New QueryType Dim Item Dim QueryTypes As Collection Set QueryTypes = QueryType.FetchAll For Each Item In QueryTypes Debug.Print Item.QueryTypeID, _ Left(Item.Description, 4) Next Item End Sub 

这是QueryType类中的FetchAll属性:

 Public Property Get FetchAll() As Collection Dim RS As Variant Dim Row As Long Dim QTypeList As Collection Set QTypeList = New Collection RS = .Run ' populates RS with a record set from a database (as an array), ' some code removed ' goes through the array and sets up objects for each entry For Row = LBound(RS, 2) To UBound(RS, 2) Dim QType As New QueryType With QType .QueryTypeID = RS(0, Row) .Description = RS(1, Row) .Priority = RS(2, Row) .QueryGroupID = RS(3, Row) .ActiveIND = RS(4, Row) End With ' adds new QType to collection QTypeList.Add Item:=QType, Key:=CStr(RS(0, Row)) Debug.Print QTypeList.Item(QTypeList.Count).QueryTypeID, _ Left(QTypeList.Item(QTypeList.Count).Description, 4) Next Row Set FetchAll = QTypeList End Property 

这是我从FetchAll中debugging得到的输出:

 1 Numb 2 PBM 3 BPM 4 Bran 5 Claw 6 FA C 7 HNW 8 HNW 9 IFA 10 Manu 11 New 12 Non 13 Numb 14 Repo 15 Sell 16 Sms 17 SMS 18 SWPM 

这是我在Test中debugging的输出:

 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 18 SWPM 

任何人有任何想法? 我可能完全忽略了一些东西!

谢谢,马丁

您创buildQueryType:

 Dim QType As New QueryType 

应该:

 Dim QType As QueryType Set QType = New QueryType 

如果你不这样做,你正在重复使用QueryType的同一个实例(因为没有Set ),所以相同的引用被添加到集合中,使得每个项目引用一个类的单个实例。 (你添加的最后一个)