Search code examples
excelvbasolver

Pick applicable Excel solvers based on conditional logic (VBA)


I am wanting to set up a VBA that will run an appropriate solver based on conditional logic. For Example: if cell A1 is greater than cell B1 then run Solver1, otherwise run Solver2. Here is what my Solver1 VBA looks like currently:

SolverAdd CellRef:="$AC$79:$AD$79", Relation:=1, FormulaText:="100"
SolverAdd CellRef:="$AE$79", Relation:=2, FormulaText:="0"
SolverAdd CellRef:="$AF$79", Relation:=2, FormulaText:="2"
SolverAdd CellRef:="$AG$79", Relation:=2, FormulaText:="0"
SolverAdd CellRef:="$X$79", Relation:=1, FormulaText:="10"
SolverAdd CellRef:="$AB$79", Relation:=1, FormulaText:="10"
SolverAdd CellRef:="$Y$79:$AA$79", Relation:=1, FormulaText:="100"
SolverAdd CellRef:="$X$79:$AD$79", Relation:=4, FormulaText:="integer"
SolverOk SetCell:="$CQ$4", MaxMinVal:=1, ValueOf:=0, ByChange:="$X$79:$AD$79", _
    Engine:=3, EngineDesc:="Evolutionary"
SolverSolve

Solution

  • Like this maybe?

    Dim ws As Worksheet, i as Long, rw As Range
    
    Set ws = ActiveSheet 'for example
    
    For i = 79 to 90 'for example
        Set rw = ws.Rows(i)
        SolverReset 'clear existing settings
        If Range("A1").Value > Range("B1").Value Then
            'note here Range() is *relative* to `rw`...
            SolverAdd CellRef:=rw.Range("AC1:AD1"), Relation:=1, FormulaText:="100"
            SolverAdd CellRef:=rw.Range("AE1"), Relation:=2, FormulaText:="0"
            SolverAdd CellRef:=rw.Range("AF1"), Relation:=2, FormulaText:="2"
            SolverAdd CellRef:=rw.Range("AG1"), Relation:=2, FormulaText:="0"
            SolverAdd CellRef:=rw.Range("X1"), Relation:=1, FormulaText:="10"
            SolverAdd CellRef:=rw.Range("AB1"), Relation:=1, FormulaText:="10"
            SolverAdd CellRef:=rw.Range("Y1:AA1"), Relation:=1, FormulaText:="100"
            SolverAdd CellRef:=rw.Range("X1:AD1"), Relation:=4, FormulaText:="integer"
            SolverOk SetCell:=ws.Range("CQ4"), MaxMinVal:=1, ValueOf:=0, ByChange:=rw.Range("X1:AD1"), _
            Engine:=3, EngineDesc:="Evolutionary"
            SolverSolve UserFinish:=True 'don't show the results dialog
        Else
            'run a different configuration
        End If
    Next i