循环按列计算求解器

时间:2016-06-22 19:57:25

标签: excel-vba loops solver vba excel

我刚刚开始使用VBA,我试图设置解算器计算在多年的范围内一个接一个地进行设置。这是1年的简单代码。如何对它进行编程以告诉它对一系列列进行操作,例如从$ 96美元到96美元,一个接一个?非常感激。

    SolverOk SetCell:="$i$96", MaxMinVal:=3, ValueOf:=0, ByChange:="$i$72", Engine _
    :=1, EngineDesc:="GRG Nonlinear"
SolverOk SetCell:="$i$96", MaxMinVal:=3, ValueOf:=0, ByChange:="$i$72", Engine _
    :=1, EngineDesc:="GRG Nonlinear"
SolverSolve userFinish = False


End Sub

2 个答案:

答案 0 :(得分:0)

如果要为给定范围执行此代码片段:

  1. 将您的代码片段定义为接收" setcell"和" bychange"作为范围(如果" bychange"永远不会改变,你可以让它在功能中硬定义并从参数中删除它)

    Public Sub Solver(byval cell as range, byval change as range)
        SolverOk SetCell:=cell, MaxMinVal:=3, ValueOf:=0, ByChange:=change, Engine:=1, EngineDesc:="GRG Nonlinear"
        SolverSolve userFinish = False
    End sub
    
  2. 定义要计算的范围,并为范围

    中的每个单元格运行此函数
    dim cell as range, rng as range
    set rng = Range("I96:AP96")    ' You should need to set range with Worksheet(<sheet>).Range()
    for each cell in rng
        call Solver(cell, Range("I72"))
    next
    

答案 1 :(得分:0)

您可以使用for循环,然后通过cells函数和Address方法生成地址字符串:

Dim i As Integer
For i = 9 To 42
    s1 = Cells(96, i).Address(RowAbsolute:=True, ColumnAbsolute:=True)
    s2 = Cells(72, i).Address(RowAbsolute:=True, ColumnAbsolute:=True)
    SolverOk SetCell:=s1, MaxMinVal:=3, ValueOf:=0, ByChange:=s2, Engine _
        :=1, EngineDesc:="GRG Nonlinear"
    SolverOk SetCell:=s1, MaxMinVal:=3, ValueOf:=0, ByChange:=s2, Engine _
        :=1, EngineDesc:="GRG Nonlinear"
    SolverSolve userFinish = False
Next i