【问题标题】:How to create 2D arrays or collections of custom classes in VBA?如何在 VBA 中创建 2D 数组或自定义类的集合?
【发布时间】:2020-01-03 22:58:09
【问题描述】:

我有一个自定义类,以及该类的 700 个实例。其中一些实例共享特定属性 (TourID) 的相同值。我想根据 TourID 的值将这些实例组装到二维数组或集合中。

创建 2D 数组会给我一个类型不匹配错误,并且创建一个集合不允许我将具有 TourID 值的键分配给项目。

Dim list_of_stops() As New Stops
For i = 0 To UBound(list_tours)
LastValue = Ubound(list_of_stops(list_tours(i).TourID))
Redim Preserve list_of_stops(list_tours(i).TourID, LastValue + 1)
list_of_stops(list_tours(i).TourID, LastValue) = list_tours(i)
Next

我希望 list_of_stops() 的结构如下:

list_of_stops(1,0) = first stop with tour ID = 1
list_of_stops(1,1) = second stop with tour ID = 1
...
list_of_stops(1,n) = n-th stop with tour ID = 1
...
list_of_stops(n,n) = n-th stop with tour ID = n

【问题讨论】:

  • 当list_of_stops() 尚未确定尺寸时,LastValue = Ubound(list_of_stops(list_tours(i).TourID)) 有什么意义?无论如何,1)字典而不是集合可能是一个不错的选择,2)minimal reproducible example 会有所帮助。如果不付出过多的努力,我们实际上无法运行您的代码。
  • 另外——数组声明行中的New 没有意义
  • @JohnColeman 它使每个数组元素成为一个自动实例化的对象......这确实很奇怪(从未见过),但显然是合法的。 Dim foo(1 To 10) As New Collection 然后Debug.Print foo(2) Is Nothing 将输出False,即使您从未为任何对象引用设置任何下标。
  • @MathieuGuindon 很有趣。我很惊讶它是合法的。
  • @JohnColeman 我也是,很高兴 RD 的 SelfAssignedDeclaration 检查正在标记它 =)

标签: arrays vba class


【解决方案1】:

我无法解释为什么你会在没有看到更多代码(主要是声明)的情况下得到一个 type mismatch 错误,但是如果没有 Set 关键字,赋值可能会导致 let-强制,失败(虽然,我遗漏了一些东西,因为那将是错误 91,或者如果该类具有 默认属性,那么最接近类型不匹配的是编译时“无效使用财产”)。

无论如何,如果Dictionary 使用唯一的TourID 值作为键,您的生活会更简单,在所有具有该TourID 值的实例中保持Collection。

参考 Microsoft Scripting Runtime 库 (Scripting):

Dim values As Dictionary
Set values = New Dictionary ' avoid "As New" unless you *NEED* an auto-instantiated object

Dim k As Variant
Dim currentGroup As Collection
For Each k In GetUniqueValuesForTourID 'TODO: a function that returns the unique IDs
    Set currentGroup = New Collection
    Dim v As Variant
    For Each v In GetAllValuesForTourID(k) 'TODO: a function that returns the records for given ID
        currentGroup.Add v, k 'note: Collection.Add value, key
    Next
    Set values(k) = currentGroup 'note the "Set" keyword; or: Dictionary.Add key, value
Next

现在,如果您迭代字典条目,每个项目都是一个Collection,并且在每个集合中每个项目都是一个Stops 实例(为什么它是复数形式?它是一个自定义集合类吗?)。这使得立即检索所有Stops 的集合变得非常容易,给定TourID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多