【问题标题】:VBA List all possible combination of variable number of items (number of nested loops as variable)VBA列出可变数量的项目的所有可能组合(嵌套循环的数量作为变量)
【发布时间】:2022-11-04 17:56:37
【问题描述】:

绅士!在列出所有可能的组合时,我无法找出将元素数量定义为变量的方法。我有一个硬编码示例,其中元素数 = 3


'Declare variables
Dim a as long
Dim b as Long
Dim C as Long
Dim ElementsArray  as variant

'Array
ElementsArray = array("1400","1900","2400")

'Loop through combinations
for a = lbound(ElementsArray) to ubound(ElementsArray)
    for B= lbound(ElementsArray) to ubound(ElementsArray)
        for c = lbound(ElementsArray) to ubound(ElementsArray)
        debug.print(ElementsArray(a) & " - " & ElementsArray(b) & " - " & ElementsArray(c))
        next c
    next b
next a

但我正在寻找的是一个代码,其中嵌套的 For 循环的数量可能是一个变量,或者是一些其他方式来排列所有可能的组合。请帮助解决这个问题。

【问题讨论】:

  • 嵌套循环不能是可变的 - 除非您编写一个为您编写代码的例程,将其注入 VBE 项目并执行它。但是,递归例程可以解决问题,而不是嵌套循环。
  • 感谢您的澄清,我的意思是也许它可以表示为“goto RepeatLoop”的东西,其中代码将通过相同的循环必要次数。我想这有点像你的建议?你想举一个例子来说明我按照你的建议编写的代码吗?

标签: vba for-loop permutation


【解决方案1】:

这是递归实现的示例。请注意,您不应该使数组太大,因为您将获得 n 的 n 个解决方案的幂 - 对于 4 个元素,即 256,对于 5 个元素,3'125,对于 6,您将获得 46'656,对于 7 823'543 - 如果程序需要很长时间才能执行,请不要抱怨。当然你需要一种方法来每个排列的东西。

Option Explicit

Sub test()
    Dim ElementsArray  As Variant
    ElementsArray = Array("1400", "1900", "2400")
    ReDim SolutionArray(LBound(ElementsArray) To UBound(ElementsArray))
    
    recursion ElementsArray, SolutionArray, LBound(ElementsArray)
End Sub

Sub recursion(elements, solution, level As Long)
    Dim i As Long
    For i = LBound(elements) To UBound(elements)
        solution(level) = elements(i)
        If level = UBound(elements) Then
            Debug.Print Join(solution, " - ")
        Else
            recursion elements, solution, level + 1
        End If
    Next i
End Sub

更新:这是结果:

【讨论】:

  • 感谢您提供建议的答案,但是您的代码仅返回 3 个元素的 3 个组合,其中仅迭代最后一个元素
  • @Eduards 你是什么意思?答案代码返回正是你的所作所为对于您使用/显示的数组。有什么我想念的吗?做你的代码返回你需要的东西?
  • 我不明白你的问题。见截图。
  • 我使用UBoundLBound。无需硬编码
  • @Eduards 元素数量为UBound(elements)。现在,你想用返回的(所有)组合做什么?上述解决方案可适用于返回包含所有这些组合的数组......
猜你喜欢
  • 2014-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
相关资源
最近更新 更多