【问题标题】:Collection of Collections - Refer to SubCollection Item with Variable for Primary Collection集合的集合 - 请参阅带有变量的子集合项以用于主集合
【发布时间】:2020-10-15 21:18:20
【问题描述】:

我正在使用(作为示例)在 3x2 矩阵上带有六个文本框的用户窗体:像这样:

c1  c2  c3
c4  c5  c6

我正在尝试将这两个文本框行添加到集合(辅助)中,然后将此集合添加到集合的集合(主)中。 然后使用主Collection 中的Collection 变量来引用嵌套Collection(辅助)中的对象。 喜欢:“集合(主要)。第一个元素。 Collection (secondary).Third Element.name”是 c3。

我尝试阅读和实现Referencing an object within a collection of collections by keyCollection of Collections - How to make sub-collections by value rather than reference?,我还尝试使用类似建议的Dynamically Create collection of Collections VBA 的字典,但我不断得到:

运行时错误“438”:对象不支持此属性或方法

在这一行(或下面代码中发布的行变体之一):

If rigavar.ItemCollection(q)(3).Name = "c3" Then

我试图理解和调整这些示例,但我无法完成,我不知道我是否遗漏了什么,或者我做的完全错误,或者我只是不明白事情如何运作或所有这些。

我通过为每一行创建一个集合并为每个单独的集合创建一个特定的过程来解决问题。 当例程到达某个集合时,它会使用该集合的特定引用触发例程,如下所示:

Private Sub workaround_Click() 
    Set rigaAA = New Collection
    rigaAA.Add c1
    rigaAA.Add c2
    rigaAA.Add c3
    
    Set rigaBB = New Collection
    rigaBB.Add c4
    rigaBB.Add c5
    rigaBB.Add c6
    
    If rigaAA.ItemCollection(3).Name = "c3" Then
    
    Call rigaAAspecificRoutine
        
        End if
    End sub

    Private Sub rigaAAspecificRoutine()
        MsgBox c1.value & c2.value  & c3.value
    End sub

但我希望通过变量而不是具体来完成它,例如:

Private Sub test_Click()

Dim rigaAA As VBA.Collection
Dim rigaBB As VBA.Collection
Dim rigavar As VBA.Collection

Set rigaAA = New Collection
rigaAA.Add c1
rigaAA.Add c2
rigaAA.Add c3

Set rigaBB = New Collection
rigaBB.Add c4
rigaBB.Add c5
rigaBB.Add c6

Set rigavar = New Collection
rigavar.Add rigaAA
rigavar.Add rigaBB

'none of this works:

For q = 1 To 2
    If rigavar.ItemCollection(q)(3).Name = "c3" Then
        MsgBox c1.value & c2.value  & c3.value
    End If
Next

For q = 1 To 2
    If rigavar.ItemCollection(q)(3).Name = "c3" Then
        MsgBox c1.value & c2.value  &  c3.value
    End If
Next

For q = 1 To 2
    If rigavar.ItemCollection(q, 3).Name = "c3" Then
        MsgBox c1.value & c2.value  & c3.value
    End If
Next

For q = 1 To 2
    If rigavar.ItemCollection(q).ItemCollection(3).Value <> "" Then
        MsgBox c1.value & c2.value  & c3.value
    End If
Next
    
End Sub

有什么建议吗? 非常感谢

【问题讨论】:

  • 要访问内部集合,语法为rigavar(q)(3)

标签: vba vba7


【解决方案1】:

Collection 没有属性 ItemCollection。要访问集合rigavar 的元素q,可以使用以下方法之一

rigavar(q)
rigavar.Item(q)

(通常使用较短的形式,这基本上是较长形式的缩写,因为Item 属性是集合的所谓默认属性

由于元素rigavar(q) 又是一个集合,您可以使用

访问第三个元素
rigavar(q)(3)
rigavar.Item(q)(3)
rigavar.Item(q).Item(3)

检查控件名称的最简单方法,使用rigavar(q)(3).Name

你不能写rigavar(q, 3),因为现在VBA会将这两个参数作为参数放入rigavar.Item(好像它是一个二维数组)。

【讨论】:

  • 非常感谢。所以这只是一个愚蠢的语法错误和对集合属性缺乏了解。我将在几分钟内实施并尝试一下。再次感谢您的时间和解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多