2010-04-20 62 views
3

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

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

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 

这是查询类型类中使用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:

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 

这是我从调试中得到的输出:

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 

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

感谢, 马丁

回答

2

你创建的查询类型:

Dim QType As New QueryType 

应该是:

Dim QType As QueryType 
Set QType = New QueryType 

如果你不这样做,你正在重用的QueryType相同的实例(因为没有Set),因此将相同的参考添加到集合中,使每个项目都引用您的单个实例r类。 (你添加的最后一个)

+1

你比我发布这个答案快了1分钟! – 2010-04-20 11:26:51

+0

这是修复它,谢谢!新的它会很简单。 – Martin 2010-04-20 12:05:07

+0

请参阅此处以获取更长的解释:http://stackoverflow.com/questions/2478097/vba-difference-in-two-ways-of-declaring-a-new-object-trying-to-understand-why/2480559# 2480559 – jtolle 2010-04-20 14:22:08

相关问题