Excel VBA: Solver not working in loop

1.8k Views Asked by At

The Solver in the loop works for the first iteration but not rest. The rest of the loop works fine.

Sub Macro1()

Sheets("model").Select
Dim i As Double
Dim p As Double


For i = 1 To 10
p = -0.1565 + ((i - 1) * 0.0015)
Sheets("model").Range("J15").Value = p


SolverOk SetCell:="$J$12", MaxMinVal:=2, ValueOf:=0, ByChange:="$B$4:$F$4", _
    Engine:=1, EngineDesc:="GRG Nonlinear"
SolverOk SetCell:="$J$12", MaxMinVal:=2, ValueOf:=0, ByChange:="$B$4:$F$4", _
    Engine:=1, EngineDesc:="GRG Nonlinear"
SolverSolve (True)



Sheets("rec").Select
Range("B1:H1").Select
Selection.Copy
Sheets("rec").Range(Cells((i + 4), 2), Cells((i + 4), 8)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("C5").Select

Next i

End Sub
1

There are 1 best solutions below

0
On

Unfortunately, the Solver will only operate if the sheet is Active, so insert a

Worksheets("model").Activate

before your first SolverOk statement.

Sub Macro1()

    Dim i As Long
    Dim p As Double

    For i = 1 To 10
        p = -0.1565 + ((i - 1) * 0.0015)
        With Worksheets("model")
            .Activate
            .Range("J15").Value = p
            SolverOk SetCell:="$J$12", _
                     MaxMinVal:=2, _
                     ValueOf:=0, _
                     ByChange:="$B$4:$F$4", _
                     Engine:=1, _
                     EngineDesc:="GRG Nonlinear"
            SolverOk SetCell:="$J$12", _
                     MaxMinVal:=2, _
                     ValueOf:=0, _
                     ByChange:="$B$4:$F$4", _
                     Engine:=1, _
                     EngineDesc:="GRG Nonlinear"
            SolverSolve True 
        End With

        With Worksheets("rec")
            .Range(.Cells(i + 4, "B"), .Cells(i + 4, "H")).Value = .Range("B1:H1").Value
        End With
    Next i
End Sub