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

标签 excel vba class collections

我想创建机场集合。

机场有很多参数,但为了简单起见,我们假设机场类在机场类模块中定义如下:

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

然后我的模块相当大,但这是我从 Excel 文件读取列并将值存储在 airports 集合中的部分,删除重复的值:

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 airports(1).name

没有打印任何内容(但也没有错误)。

我之前使用过字符串集合并且它可以工作。但我现在每个机场都需要多个字符串。

我的代码有什么问题?我使用集合对吗?

最佳答案

您的代码有两个问题。

第一个可能是创建一个包含数百万个项目的 Collection,因为您要迭代的范围是 D 列的全部 (D:D)。这个需要绑定(bind)。

第二个问题是您的变量名称 airport 与您的类 Airport 的名称完全相同。这很容易混淆 VBA,因此您需要为其中之一选择不同的名称。

这是一个有效的示例:

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

关于excel - 如何正确使用 VBA 类模块集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44701868/

相关文章:

Excel公式翻译(多语言系统)

java - 如何使用java apache POI :showing java. io.IOException在Excel中写入:流关闭错误

vba - 在组合框下拉列表中格式化日期

php - 为什么在 php 类中用作数组项不起作用

Java-反射 : Get fields belonging to current class only

excel - activeworkbook/activesheet什么时候改变?

excel - 粘贴时限定单元格中的 VBA 递增数

excel - ForEach 循环对象需要错误

excel - 打开 Access 数据库并从 Excel 运行其中一个宏

javascript - 向元素添加类以在 Javascript 中运行 CSS 动画