动态添加嵌套循环

时间:2015-03-20 15:08:04

标签: excel vba dynamic nested-loops

我有一个'X'个变量(可能在3到20个选项之间),它们将被组合起来计算所有可能的组合以满足标准。对于每个额外的变量,引入了一个额外的循环,但我不知道是否可以动态创建循环(在excel VBA中,代码不必非常快)。

要证明: 我有var。 a,h = 2,var。 B,h = 3。 我想知道所有等于10的组合或2个变量的最佳组合。

在这种情况下:选项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

1 个答案:

答案 0 :(得分:1)

这里有两个不同的问题。你没有提到第一个,那就是你还需要用不确定数量的参数来计算一个值。为此,您可以使用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

可以像这样使用和测试:

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