设置求解器循环以更改单元格引用,相邻列

时间:2017-02-04 10:52:15

标签: excel vba loops solver

我正在尝试为二次优化编写一个宏。我的VBA技能非常有限,但是我手动使用了解算器并记录了一个宏,我的代码目前看起来像这样:

Sub Macro2()
'
' Macro2 Macro
'

'
    SolverReset
    SolverAdd CellRef:="$C$179:$C$185", Relation:=3, FormulaText:="0"
    SolverAdd CellRef:="$C$186", Relation:=2, FormulaText:="1"
    SolverOk SetCell:="$C$174", MaxMinVal:=2, ValueOf:=0, ByChange:="$C$179:$C$185" _
    , Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve UserFinish:=True
    SolverFinish KeepFinal:=1

End Sub

我要做的是做一个求解器循环,以便下次单元格引用和目标单元格中​​的C列将更改为D时,其他所有内容都将保持不变。我想对20个相邻的列进行此操作,从C到V.任何帮助都将非常感谢!

1 个答案:

答案 0 :(得分:0)

如果我在上面的评论中提出的假设是正确的,那么下面的代码会做你想要的 - 但是我无法测试所有这些因为我没有求解器函数的代码......见下文:

Public Sub sampleCode()
Dim targetWS As Worksheet
Dim colCounter As Long
Dim colAddress As String
Dim colLetter As String

Set targetWS = ThisWorkbook.Sheets(1)   'Make sure to replace sheet(1) with sheet(<your sheet name>)
For colCounter = 3 To 22    'Loop through columns C through V
    'Get the column letter you want to run solver on
    colAddress = Replace(targetWS.Range("A1")(1, colCounter).address, "$", "")
    colLetter = Left(colAddress, InStr(1, colAddress, "1") - 1)
    SolverReset
    'Run solver but with the references being set by using colLetter
    SolverAdd CellRef:=colLetter & "179:" & colLetter & "185", Relation:=3, FormulaText:="0"
    SolverAdd CellRef:=colLetter & "186", Relation:=2, FormulaText:="1"
    SolverOk SetCell:=colLetter & "174", MaxMinVal:=2, ValueOf:=0, ByChange:=colLetter & "179:" & colLetter & "185", Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve UserFinish:=True
    SolverFinish KeepFinal:=1
Next
End Sub

希望这有帮助, TheSilkCode