简体   繁体   中英

VBA Solver dislikes paying attention to constraints

I've been trying to make the solver in VBA work nicely on GRG non-linear problems with named ranges. It's going so-so - it keeps ignoring the binary constraint. Attempts to follow other posts with similar issues have failed.

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

My research has had me stumble upon Excel Solver Ignoring Constraint in VBA along with other threads. I've tried every combination present in that thread, and I've gotten nowhere.

Worth noting: I've also tried a manual approach to forcing binary - sumproduct(range)=sum(range) must be true - but that just generates everything as 0, which is useless.

I got it to work by executing the solver twice rather than once:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM