可变数量的嵌套循环

时间:2020-05-19 11:12:26

标签: excel vba

我有一个问题,无法缠住我的头。似乎递归函数可以完成这项工作,但我需要一些帮助才能开始使用

我有一个类似这样的收藏集:

CollInput
'Each Items can have a variable number of SubItems
Item 1
    Item 1 = 2
    Item 2 = 4
Item 2 = 0
Item 3
    Item 1 = 5
    Item 2 = 7
Item 4
    Item 1 = 6
Item 5 = 0
Item 6
    Item 1 = 7
    Item 1 = 8
Item 7 = 0
Item 8 = 0

我想为“ CollInput”中的给定项目返回所有后续项目的集合

CollOuput(CollInput(1))
Item 1 = 2 'CollInput(1)(1)
Item 2 = 4 'CollInput(1)(2)
Item 3 = 0 'CollInput(CollInput(1)(1))
Item 4 = 6 'CollInput(CollInput(1)(2))(1)
Item 5 = 7 'CollInput(CollInput(CollInput(1)(2))(1))(1)
Item 6 = 8 'CollInput(CollInput(CollInput(1)(2))(1))(2)

我已经尝试了几种组合,对于每种,直到,对于i = 1到CollInput(x).count,但我真的无法正常工作

希望很明显! 谢谢

编辑:实际上还不太清楚,所以这里有一些精度:

第二级中找到的值提供了我需要遍历的所有项目。 因此,当我们在上面的示例中查看时,为函数CollOuput提供了带有索引值(在这​​种情况下为1)的参数CollInput。

1)它应该查看CollInput的项目1,保存在2级(2和4)中找到的值

2)转到第1级的项目2,或者由于没有第2级而获得0,或者只是通过

3)查看第4层第1项,保存在第2层(6)中找到的值

4)查看第1层第6项,保存在第2层(7和8)中找到的值

5)查看第7项第1级,要么因为没有第2级而获得0,要么直接通过

6)查看第8项第1级,要么因为没有第2级而获得0,要么只是通过

如果给定索引参数3,则结果应为:

CollOuput(CollInput(3))
Item 1 = 5 
Item 2 = 7 
Item 3 = 0 'or ignore
Item 4 = 0 'or ignore

希望有帮助

2 个答案:

答案 0 :(得分:3)

想象一下以下测试集合TestCol

enter image description here

以及以下返回功能:

Public Function FlattenCollection(ByVal Col As Collection) As Collection
    Dim FlatCol As Collection
    Set FlatCol = New Collection

    Dim i As Long
    For i = 1 To Col.Count
        If TypeName(Col(i)) = "Collection" Then 'if current item of Col is a collection itself …
            Dim TmpCol As Collection
            Set TmpCol = FlattenCollection(Col(i)) ' … flatten this collection too
            Dim j As Long
            For j = 1 To TmpCol.Count
                FlatCol.Add TmpCol(j)
            Next j
            Set TmpCol = Nothing
        Else
            FlatCol.Add Col(i)
        End If
    Next i

    Set FlattenCollection = FlatCol
    Set FlatCol = Nothing
End Function

您可以这样称呼:

Dim OutputCol As Collection
Set OutputCol = FlattenCollection(TestCol)

要获取以下平面输出集合OutputCol

enter image description here

请注意,如果集合中的项目过多或级别过多,则很容易耗尽内存。

答案 1 :(得分:1)

由于@Peh,我设法获得了想要的结果!对我来说,这是一个很好的VBA课程。真令人满足,我非常感谢Peh。

这是代码

Public Function FlattenCollection2(ByVal Col As Collection, ByVal index As Long) As Collection
    Dim FlatCol As Collection
    Set FlatCol = New Collection
    Dim c
    Dim counter As Long
    Dim Val As Long
    counter = 0

    If TypeName(Col(index)) = "Collection" Then
        For Each c In Col(index)
            counter = counter + 1
            Val = Col(index)(counter)
            FlatCol.Add Val
            Dim tmpCol As Collection
            Set tmpCol = FlattenCollection2(Col, Val)
            For j = 1 To tmpCol.Count
                FlatCol.Add tmpCol(j)
            Next j
            Set tmpCol = Nothing
        Next
    End If
    Set FlattenCollection2 = FlatCol
    Set FlatCol = Nothing
    counter = 0
End Function

因此,从这个集合中: Input

我得到索引为2的输出

Ouput

相关问题