【问题标题】:VBA Solver loopVBA 求解器循环
【发布时间】:2016-01-04 23:26:35
【问题描述】:

我正在使用带有以下代码的 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

【问题讨论】:

  • “不起作用”应添加到审查列表中...您能否更详细地解释一下您得到了什么结果 - 是编译错误、运行时异常还是其他什么?
  • 它在没有循环的情况下工作,所以它似乎是一个编译错误(我不确定 ByChange 函数的正确语法)。
  • 就是这样,你在那个地方错过了双引号 - ByChange:="$I$ & i:$J$ & i" 你应该使用 ByChange:="$I$" & i & ":$J$" & i 尝试让我知道是否有问题。
  • 这就是问题所在,使用您的语法 (ByChange:="$I$" & i & ":$J$" & i) 一切正常
  • 好消息!很高兴帮助你:)

标签: vba excel loops solver


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多