Search code examples
excelvbasolver

SolverAdd function is ignoring my constraints


I've been trying to add constraints to a specific problem I'm trying to get a solution to, but SolverAdd simply ignores my code. I'm coding a macro since this action needs to be done as simple as possible, I'm thinking of linking this macro to an ActiveX button.

I've already tried to add quotations marks to my restraints, as well as deleting them, but this doesn't fix the problem. I've also closed the workbook and re opened it but it still won't work. Moreover, I've tried setting the values of my restraints in cells in the workbook and refer to them with Range, but it doesn't work either.

I've enabled the Solver DialogBox at the end and it claims all my constraints are met, but that's not the case.

Sub OptimizePrice()
    Application.ScreenUpdating = False
    SolverReset
    SolverOk SetCell:=Range("N64"), _ 'Gross Profit
        MaxMinVal:=1, _
        ByChange:=Range("E59,I59,M59"), _ 'Prices that need to be optimized
        Engine:=1
    SolverAdd cellRef:=Range("E59,I59,M59"), _
        relation:=1, _
        formulaText:=Range("H30") ' Tried 80 and "80"
    SolverAdd cellRef:=Range("E59,I59,M59"), _
        relation:=3, _
        formulaText:=Range("H29") 'Tried 50 and "50"
    SolverSolve 'userFinish:=True
    Application.ScreenUpdating = True
End Sub

I expect to get a value between 50 and 80, but I get values as high as 137


Solution

  • Ok. Didn't think it was that odd. Here goes my solution:

    Sub OptimizePrice()
        Application.ScreenUpdating = False
        SolverReset
        SolverOk SetCell:=Range("N64"), _ 'Gross Profit
            MaxMinVal:=1, _
            ByChange:=Range("E59,I59,M59"), _
            Engine:=1
    'Lower limits (H29=50). One constraint per cell.
        SolverAdd CellRef:=Range("E59"), _
            Relation:=3, _
            FormulaText:=Range("H29")
        SolverAdd CellRef:=Range("I59"), _
            Relation:=3, _
            FormulaText:=Range("H29")
        SolverAdd CellRef:=Range("M59"), _
            Relation:=3, _
            FormulaText:=Range("H29")
    'Upper Limits (H30=80). Again, one constraint per cell.
        SolverAdd CellRef:=Range("E59"), _
            Relation:=1, _
            FormulaText:=Range("H30")
        SolverAdd CellRef:=Range("I59"), _
            Relation:=1, _
            FormulaText:=Range("H30")
        SolverAdd CellRef:=Range("M59"), _
            Relation:=1, _
            FormulaText:=Range("H30") ' 
        SolverSolve userFinish:=True
        Application.ScreenUpdating = True
    End Sub