2016-04-26 140 views
-1

我想通過改變(列H中的單元格)來重複地解決目標函數(列P中的單元格)的VBA代碼。因此,我有以下約束:VBA代碼重複解決

第一個約束:H_i <= H_i-1, e.g. H3 <= H2等等直到最後一行。

第二個約束:L_i >= L_i-1, e.g. L3 >= L2等等直到最後一行。

到目前爲止的代碼:

Sub Solver_Balances() 
'Automated solver to calculate the mass and heat balance 
'at each time increment of 1 sec as given by the datalogger 
' 
Worksheets("Sheet1").Activate 
RowCount = 2 
Do While Not IsEmpty(Worksheets("Sheet1").Range("H" & RowCount)) 
    SolverReset 
    SolverOk SetCell:=Range("P" & RowCount), MaxMinVal:=2, _ 
     ByChange:=Range("H" & RowCount), Engine:=1, _ 
     EngineDesc:="GRG Nonlinear" 
    SolverAdd Cellref:=Range("H" & RowCount), _ 
     Relation:=1, _ 
     FormulaText:=Range("H" & RowCount - 1) 
    SolverAdd Cellref:=Range("L" & RowCount), _ 
     Relation:=3, _ 
     FormulaText:=Range("L" & RowCount - 1) 
    Solversolve userfinish:=True 
    SolverFinish keepFinal:=1 
    RowCount = RowCount + 1 
Loop 
End Sub 

我的值在H20.931起始值(一個給定的值)。出於某種原因,我的代碼在H3中回覆了0.53的值,其中我期望找到更接近0.93的值。此外,我的目標函數是基於值0.53低於下限的物理關係計算的。

任何人都可以告訴我,如果我使用的代碼是正確的?任何幫助表示讚賞!

回答

1

做了一些調整後,我設法解決了我的問題。

特此的代碼:

Sub Solver_Balances() 
'Automated solver to calculate the mass and heat balance 
'at each time increment of 1 sec as given by the datalogger 
' 
Worksheets("Sheet1").Activate 
RowCount = 2 
Do While Not IsEmpty(Worksheets("Sheet1").Range("H" & RowCount)) 
    SolverReset 
    SolverOk SetCell:="P" & RowCount, MaxMinVal:=2, ValueOf:=0, _ 
     ByChange:="H" & RowCount, Engine:=1, _ 
     EngineDesc:="GRG Nonlinear" 
    SolverAdd CellRef:="H" & RowCount, _ 
     Relation:=1, _ 
     FormulaText:="H" & RowCount - 1 
    SolverAdd CellRef:="L" & RowCount, _ 
     Relation:=3, _ 
     FormulaText:="L" & RowCount - 1 
    SolverSolve userfinish:=True 
    SolverFinish keepFinal:=1 
    RowCount = RowCount + 1 
Loop 
End Sub 
+0

獲取單元參考信息以解算器是棘手的。還有其他一些挑戰...... [請參閱此問題的答案](http://stackoverflow.com/questions/36671991/use-solver-in-vba-with-loop-in-rows/36682703) – OldUgly