2015-10-07 67 views
0

我使用求解用下面的代碼:VBA求解循環

Sub Test() 

    SolverReset 

    SolverOk SetCell:="$K$7", MaxMinVal:=1, ValueOf:=0, ByChange:="$I$7:$J$7", _ 
    Engine:=1, EngineDesc:="GRG Nonlinear" 

    SolverAdd CellRef:="$G$7", Relation:=2, FormulaText:="$H$7" 
    SolverAdd CellRef:="$K$7", Relation:=2, FormulaText:="$B$7" 

    SolverSolve UserFinish:=False 

    SolverFinish KeepFinal:=1 

End Sub 

我現在需要把它變成一個循環,以便從7行求解器運行至行17.我編碼它按以下但它不工作:

Dim i As Long 
For i = 7 To 17 
    SolverReset 

    SolverOk SetCell:="$K$" & i, MaxMinVal:=1, ValueOf:=0, ByChange:="$I$ & i:$J$ & i", _ 
    Engine:=1, EngineDesc:="GRG Nonlinear" 

    SolverAdd CellRef:="$G$" & i, Relation:=2, FormulaText:="$H$" & i 
    SolverAdd CellRef:="$K$" & i, Relation:=2, FormulaText:="$B$" & i 

    SolverSolve UserFinish:=False 

    SolverFinish KeepFinal:=1 

Next i 

End sub 
+0

「不工作」應該加入審查列表...你能解釋更詳細的結果是什麼你得到 - 是編譯錯誤,運行時異常還是其他? – GSazheniuk

+0

它工作沒有循環,所以它似乎是一個編譯錯誤(我不知道ByChange函數的正確語法)。 – fdt6243

+0

因此,您在該位置錯過了雙引號 - ByChange:=「$ I $&i:$ J $&i」,您應該使用ByChange:=「$ I $」&i&「:$ J $ 「&我試着讓我知道這是否是一個問題。 – GSazheniuk

回答

1

也許......

Dim i    As Long 

For i = 7 To 17 
    SolverReset 

    With Rows(i) 
    SolverOk SetCell:=.Range("K1").Address, _ 
      MaxMinVal:=1, _ 
      ByChange:=.Range("I1:J1").Address, _ 
      Engine:=1 
    SolverAdd CellRef:=.Range("G1").Address, _ 
       Relation:=2, _ 
       FormulaText:=.Range("H1").Address 
    SolverAdd CellRef:=.Range("K1").Address, _ 
       Relation:=2, _ 
       FormulaText:=.Range("B1").Address 
    SolverSolve UserFinish:=True 
    End With 
Next i