Excel VBA:求解器不在循环中工作

时间:2017-05-16 09:09:03

标签: excel vba excel-vba solver xla

循环中的求解器适用于第一次迭代,但不能休息。循环的其余部分工作正常。

field1 value1;
field2 value2;
field3 value3;
field4 value4;
field5 17 col1 col2 col3 col4 col5 col6 col7 col8;
field6
val1 val 2 val3 val4 val5 val6 val7 val8
val9 val10 val11 val12 val13 val14 val15 val16
val17 val18 val19 val20 val21 val22 val23 val24;
EndOfFile; 

1 个答案:

答案 0 :(得分:0)

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