VBA Solver不喜欢注意约束

时间:2017-03-27 22:42:14

标签: excel vba excel-vba excel-2010

我一直试图让VBA中的求解器很好地处理具有命名范围的GRG非线性问题。它一直如此 - 它一直忽略二元约束。尝试关注其他类似问题的帖子都失败了。

Sub Solver()
'
' Solver Macro
' For solving once we have the data
'

    SolverReset
       'Clearing out the old solver data, allows for named ranges to be used

    SolverAdd CellRef:=Range("VariableRange"), Relation:=1, FormulaText:=Range("One")
    ' Previous advice has been to used a range that ='s 1, as that can sometimes make things work. Part A
    SolverAdd CellRef:=Range("VariableRange"), Relation:=3, FormulaText:="0"
    'Part B
    SolverAdd CellRef:=Range("VariableRange"), Relation:=4, FormulaText:="integer"
    'Parts A and B along with this part are supposed to mimic the binary setting, in an attempt to get things working.

    SolverAdd CellRef:="$D$1", Relation:=1, FormulaText:="$D$2"
    'D2 is my limit that D1 needs to stay inside of.
    SolverAdd CellRef:="$D$1", Relation:=3, FormulaText:="-$D$2"
    'Could probably include an ABS on D1 to reduce VBA-ness. Either way, needs to fall within D2

    SolverOk SetCell:="$A$1", MaxMinVal:=1, ValueOf:=0, ByChange:=Range("VariableRange"), _
        Engine:=1, EngineDesc:="GRG Nonlinear"
        'And now we TRY to solve

        SolverSolve UserFinish:=True
        'I don't want to have to confirm to keep the results
        SolverFinish KeepFinal:=1
        'And I'd like to keep the results!

End Sub

我的研究让我偶然发现了Excel Solver Ignoring Constraint in VBA和其他线索。我已经尝试过该主题中的每一个组合,但我一无所获。

值得注意的是:我还尝试过强制二进制的手动方法 - sumproduct(range)= sum(range)必须为true - 但这只会生成0,这是无用的。

1 个答案:

答案 0 :(得分:0)

我通过执行两次而不是一次的求解器来使它起作用:

SolverOk SetCell:="$A$1", MaxMinVal:=1, ValueOf:=0, ByChange:=Range("VariableRange"), _
    Engine:=1, EngineDesc:="GRG Nonlinear"
    'And now we TRY to solve

    SolverSolve UserFinish:=True
    'I don't want to have to confirm to keep the results
    SolverSolve UserFinish:=True
    'This second iterations solves it correctly
    SolverFinish KeepFinal:=1
    'And I'd like to keep the results!