2011-10-03 161 views
1

我有一個「黑匣子」excel模型與1張。它有2個輸入,命名範圍爲「Input1」和「Input2」,以及一個輸出,命名範圍爲「輸出」。我寫了一個宏以測試它的輸入該模型的變化的敏感度,但我想知道如果有一個更優雅的方式來做到這一點:「壓力測試」Excel模型框架

Sub LoopMacro() 

Dim outrow As Integer 
outrow = 1 

For i = 1 To 10 Step 0.5 
    Range("Input1").Value = i 

    For j = 1 To 10 Step 0.5 
     Range("Input2").Value = j 

     Output outrow 
     outrow = outrow + 1 

    Next j 
Next i 
End Sub 

Sub Output(outrow As Integer) 

Sheets("Output").Cells(outrow, 1) = Range("Input1").Value 
Sheets("Output").Cells(outrow, 2) = Range("Input2").Value 
Sheets("Output").Cells(outrow, 3) = Range("Output").Value 

End Sub 

這種宏觀的問題是,它需要的爲每個輸入變量循環,如果我有更多的輸入,會變得非常乏味。我試圖弄清楚是否有編寫代碼的方法,以便我可以定義n輸入(名爲ranged「Input1」,「Input1」,「Inputn」)以及它們的最小值和最大值,並將宏自動循環輸入Input1-Inputn的相關值

+0

輸入是否需要如您所示嵌套,或者它們可以是線性的? –

+0

@Doug格蘭西我不確定你的意思。在我展示的例子中,我想在我定義的範圍內測試「Input1」和「Input2」的所有可能組合。 – Zach

+1

在what-if分析菜單下查看Excel「數據表」:http://office.microsoft.com/en-us/excel-help/calculate-multiple-results-by-using-a-data-table- HP010072656.aspx。另見這裏:http://stackoverflow.com/questions/4640336/using-a-sheet-in-an-excel-user-defined-function/4640866#4640866 – jtolle

回答

1

不確定,但這可能是您要查找的內容:只需修改包含參數名稱和值範圍的數組即可。

Sub TestModelInputs() 

    Dim shtModel As Worksheet, shtResults As Worksheet 
    Dim arrNames, arrMin, arrMax, arrStep, arrVals, x 
    Dim rw As Long, lb, ub, n, incr As Boolean 

    '###modify input parameters here 
    arrNames = Array("Input1", "Input2", "Input3") 
    arrMin = Array(1, 1, 1) 
    arrMax = Array(4, 5, 6) 
    arrStep = Array(1, 1, 1) 
    '###done with parameter setup 

    Set shtModel = ThisWorkbook.Sheets("Model") 
    Set shtResults = ThisWorkbook.Sheets("Results") 

    rw = 1 
    arrVals = arrMin 
    lb = LBound(arrNames) 
    ub = UBound(arrNames) 
    n = (ub - lb) + 1 
    shtResults.UsedRange.ClearContents 

    Do    
     rw = rw + 1 
     For x = lb To ub 
      shtModel.Range(arrNames(x)).Value = arrVals(x) 
     Next x 

     With shtResults.Rows(rw) 
      .Cells(1).Resize(1, n).Value = arrVals 
      .Cells(n + 1).Value = shtModel.Range("Output").Value 
     End With 

     For x = lb To ub 
      If arrVals(x) < arrMax(x) Then 
       arrVals(x) = arrVals(x) + arrStep(x) 
       Exit For 
      Else 
       If x = ub Then 
        Exit Do 
       Else 
        arrVals(x) = arrMin(x) 
       End If 
      End If 
     Next x 
    Loop 

End Sub 
+0

所以如果我決定我需要4個輸入,我只是添加第四個值到每個參數數組?我喜歡它,謝謝你的回答。 – Zach