如何正确使用VBA类模块的集合?

我想创build一个机场的集合。

机场有许多参数,但为了简单起见,我们假设在机场等级模块中这样定义一个机场等级:

'Class Airport Public name As String ' Stores name of the airport Public flights As Long ' Stores number of flights in that airport 

然后我的模块是相当大的,但这是我从一个Excel文件中读取列和存储在机场收集值,删除重复的部分:

 Dim airports As Collection Set airports = New Collection 'Putting airports in collection Dim c As Range For Each c In wsToCheck.Range("D:D") On Error Resume Next Dim airport As New Airport airport.name = c.Value airports.Add airport, c.Value On Error GoTo 0 Next 

如果我在中间

Debug.Print airport.name

我得到的名字,但是当我这样做

Debug.Print机场(1).name

没有打印(但也没有错误)。

我之前正在使用一个string集合,它正在工作。 但是现在每个机场我需要一个以上的string。

我的代码有什么问题? 我用collections品吗?

你的代码有两个问题。

首先是可能创build一个具有数百万个项目的Collection ,因为您正在迭代的范围是D列( D:D )的全部。 这需要绑定。

第二个问题是你的variables名称airport是完全相同的名称,你的classAirport 。 这很容易混淆VBA,所以你需要为其中的一个select一个不同的名字。

这里有一个例子:

 Option Explicit Sub test() Dim wsToCheck As Worksheet Set wsToCheck = ThisWorkbook.Sheets("Sheet1") Dim airportNames As Range Set airportNames = wsToCheck.Range("D1:D10") Dim airports As Collection Set airports = New Collection 'Putting airports in collection Dim i As Long Dim c As Range For Each c In airportNames Dim thisAirport As Airport 'Debug.Print c.Address & "=" & c.Value Set thisAirport = New Airport thisAirport.name = c.Value thisAirport.flights = i i = i + 1 airports.Add thisAirport Next 'now print them out For i = 1 To airports.Count Debug.Print airports(i).name & ", " & airports(i).flights Next i End Sub 

除了@PeterT提到的问题,你的代码中最大的问题就是新Airport对象的创build方式。 我应该说Airport对象,因为实际上没有对象,只有一个对象。

这是由机场variables宣布的方式引起的: Dim airport As New Airport 。 在VBA中,我们可以find为什么在这里只创build一个对象的原因:

New关键字可以隐式创build对象。 如果在声明对象variables时使用New,则在首次引用对象时会创build对象的新实例,因此您不必使用Set语句来分配对象引用。

所以Dim New确保在首次使用variablesairport时创build新的实例。 但是,这是它。 没有其他实例创build,只是第一个。 在每个循环中,只有这个实例被更改并添加到集合中。 所以你的集合包含对同一机场对象的引用。

但是你需要所有的机场对象,而不仅仅是一个。 所以New必须和Set一起使用。 该文件说:

当New与Set一起使用时,它将创build一个新的类实例


考虑下面的代码(范围D1:D3包含值AAAA,BBBB,CCCC)

 Dim airports As Collection Set airports = New Collection Dim c As Range For Each c In Worksheets(1).Range("D1:D3") Dim Airport As New Airport Airport.name = c.Value airports.Add Airport Next Dim airports2 As Collection Set airports2 = New Collection Dim airport2 As Airport For Each c In Worksheets(1).Range("D1:D3") Set airport2 = New Airport airport2.name = c.Value airports2.Add airport2 Next Debug.Print "Airports:" For Each airport2 In airports Debug.Print airport2.name Next Debug.Print vbNewLine Debug.Print "Airports2:" For Each airport2 In airports2 Debug.Print airport2.name Next 

产量

 Airports: CCCC CCCC CCCC Airports2: AAAA BBBB CCCC 

这个问题是关于同样的问题。