gpt4 book ai didi

excel - 可变数量的嵌套循环

转载 作者:行者123 更新时间:2023-12-04 21:28:45 25 4
gpt4 key购买 nike

我有一个无法解决的问题。似乎递归函数可以完成这项工作,但我需要一些帮助才能开始
我有一个看起来像这样的集合:

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
我想为“ColInput”中的给定项目返回所有后续项目的集合
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)
我已经尝试了 For each, Do until, For i = 1 to CollInput(x).count 的几种组合,但我真的什么都做不了
希望清楚!
谢谢
编辑:实际上不是很清楚,所以这里有一些精度:
在第二级中找到的值给出了我需要循环的项目。
因此,当我们查看上面的示例时,函数 CollOuput 的参数 CollInput 具有索引值(在这​​种情况下为 1)。
  • 它应该查看 CollInput 的第 1 项,保存在第 2 级(2 和 4)中找到的值
  • 转到第 1 级的第 2 项,要么因为没有第 2 级而得到 0,要么干脆通过
  • 查看第 4 级第 1 级,保存第 2 级中找到的值 (6)
  • 查看第 1 级的第 6 项,保存在第 2 级(7 和 8)中找到的值
  • 查看第 7 项第 1 级,要么因为没有第 2 级而得到 0,要么干脆通过
  • 查看第 8 项第 1 级,要么因为没有第 2 级而得到 0,要么干脆通过

  • 如果给定索引参数 3,则结果应为:
    CollOuput(CollInput(3))
    Item 1 = 5
    Item 2 = 7
    Item 3 = 0 'or ignore
    Item 4 = 0 'or ignore
    希望它有所帮助

    最佳答案

    想象一下下面的测试集合 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

    请注意,如果集合中的项目太多或级别太多,那么您将很容易耗尽内存。

    关于excel - 可变数量的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61889642/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com