dynamic添加嵌套循环

我有一个“X”数量的variables(可能范围在3到20个选项之间),这些variables将被组合来计算所有可能的组合以符合标准。 对于每个额外的variables引入一个额外的循环,但是我不知道是否有可能创build循环dynamic(在Excel VBA中,代码不必非常快)。

为了演示:我有var。 A与h = 2,var。 B与h = 3.我想知道所有等于10的组合或2个variables的最佳组合。

在这种情况下:选项1 = 5 * A = 10,3 * B = 9,2 * A和2 * B = 10,3 * A和1 * B = 9。

代码如下所示:

For A = 0 to 5 h = 0 'Reset previous h if solution is found For B = 0 to 5 h_test = A * height(A) + B * heigth(B) if h_test > 10 if h = 0 then exit for else write h exit for end if h = h_test Next B Next A 

如果引入了另一个参数(例如C = 4),则代码为:

 For A = 0 to 5 h = 0 'Reset previous h if solution is found For B = 0 to 5 h = 0 'Reset previous h if solution is found For C = 0 to 5 h_test = A * height(A) + B * heigth(B) + C * heigth(C) if h_test > 10 if h = 0 then exit for else write h exit for end if h = h_test Next C Next B Next A 

换句话说,我想知道是否有可能将伪代码翻译成实际的代码:

 For #parameter. = X For loop1 = 1 to 5 h = 0 For loop2 = 1 to 5 h = 0 .... For loopX = 1 to 5 h_test = loop1 *parameter1 + loop2 * parameter 2 ... + loopX * parameter X If h_test > 10 Somecode exit for End if Next X ... Next loop2 Next loop1 

这里有两个截然不同的问题。 你没有提到第一个,那就是你也需要用一个不确定的参数来计算一个值。 为此,您可以使用ParamArray

例如:

 Public Function Sum(ParamArray args() As Variant) As Long Dim i As Long Dim operand As Integer Dim result As Long For i = LBound(args) To UBound(args) result = args(i) + result Next i Sum = result End Function 

可以像这样使用和testing:

 Public Sub Test() Debug.Print Sum(1,2) '=> 3 Debug.Print Sum(1,2,3) '=> 6 End Sub 

所以,这个照顾这个问题。 现在,关于你问到的问题,我们会采取类似的方法。 关键是为每个收到的参数循环一次。

 Public Sub Run() NestedLoop 1, 2, 3 End Sub Public Sub NestedLoop(ParamArray args() As Variant) Dim result As Long Dim a As Variant a = args Dim h_test As Long Dim i As Long, j As Long For i = LBound(args) To UBound(args) For j = 1 To 5 result = 0 h_test = Sum(a) If h_test > 10 Then If result = 0 Then Exit For Else Debug.Print result Exit For End If End If result = h_test Next j Next i End Sub Public Function Sum(args As Variant) As Long Dim i As Long Dim operand As Integer Dim result As Long For i = LBound(args) To UBound(args) result = args(i) + result Next i Sum = result End Function