VBA求解器循环

时间:2015-10-07 16:05:19

标签: vba excel-vba loops solver excel

我使用Solver并使用以下代码:

Sub Test()

  SolverReset

  SolverOk SetCell:="$K$7", MaxMinVal:=1, ValueOf:=0, ByChange:="$I$7:$J$7", _
    Engine:=1, EngineDesc:="GRG Nonlinear"

  SolverAdd CellRef:="$G$7", Relation:=2, FormulaText:="$H$7"
  SolverAdd CellRef:="$K$7", Relation:=2, FormulaText:="$B$7"

  SolverSolve UserFinish:=False

  SolverFinish KeepFinal:=1

End Sub

我现在需要把它放到一个循环中,以便从第7行到第17行运行Solver。我按照下面的代码对它进行编码,但它不起作用:

Dim i As Long
For i = 7 To 17
  SolverReset

  SolverOk SetCell:="$K$" & i, MaxMinVal:=1, ValueOf:=0, ByChange:="$I$ & i:$J$ & i", _
    Engine:=1, EngineDesc:="GRG Nonlinear"

  SolverAdd CellRef:="$G$" & i, Relation:=2, FormulaText:="$H$" & i
  SolverAdd CellRef:="$K$" & i, Relation:=2, FormulaText:="$B$" & i

  SolverSolve UserFinish:=False

  SolverFinish KeepFinal:=1

Next i  

End sub

1 个答案:

答案 0 :(得分:1)

也许......

Dim i             As Long

For i = 7 To 17
  SolverReset

  With Rows(i)
    SolverOk SetCell:=.Range("K1").Address, _
             MaxMinVal:=1, _
             ByChange:=.Range("I1:J1").Address, _
             Engine:=1
    SolverAdd CellRef:=.Range("G1").Address, _
              Relation:=2, _
              FormulaText:=.Range("H1").Address
    SolverAdd CellRef:=.Range("K1").Address, _
              Relation:=2, _
              FormulaText:=.Range("B1").Address
    SolverSolve UserFinish:=True
  End With
Next i