我正在Excel模型中执行多个变量灵敏度分析,现在我在VBA中绘制功能时遇到了一些障碍。代码需要执行以下操作:
如果变量的数量是固定的,那么使用嵌套的For循环很容易完成步骤2,我已经这样做了。证明有问题的是使变量的数量变得动态。我已经尝试过递归,但我似乎无法让循环正确运行。我的问题是:如何重新创建下面的子过程测试但是有动态数量的变量(即For-loops的数量)?示例代码可以在下面找到。提前谢谢!
Function getVariables()
Dim variables(), values() As Variant
Dim iVariables, iValues, i, j As Integer
Dim rStart, rEnd, rValues As Range
iVariables = Range("A1").End(xlToRight).Column - Range("A1").Column + 1
ReDim variables(1 To iVariables)
For i = 1 To iVariables
Set rStart = Range("A1").Offset(1, i - 1)
Set rEnd = Range("A1").Offset(1, i - 1).End(xlDown)
Set rValues = Range(rStart, rEnd)
iValues = rValues.Count
ReDim values(1 To iValues)
For j = 1 To iValues
values(j) = rValues.Cells(j, 1)
Next j
variables(i) = values
Next i
getVariables = variables
End Function
Sub Test()
Dim variables() As Variant
Dim i1, i2, i3, i4 As Integer
variables = getVariables
For i4 = 1 To UBound(variables(4))
Range("D10").Value = variables(4)(i4)
For i3 = 1 To UBound(variables(3))
Range("C10").Value = variables(3)(i3)
For i2 = 1 To UBound(variables(2))
Range("B10").Value = variables(2)(i2)
For i1 = 1 To UBound(variables(1))
Range("A10").Value = variables(1)(i1)
Next i1
Next i2
Next i3
Next i4
End Sub