0

我有一个自定义类和这个类的 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
4

1 回答 1

2

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

Dictionary无论如何,使用具有唯一TourID值的键控,保存Collection具有该值的所有实例中的一个,您的生活会更简单TourID

参考Microsoft 脚本运行时库 ( 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

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

于 2019-08-30T19:06:18.310 回答