【问题标题】:How to shorten the length of my cell reference code using a loop in VBA?如何使用 VBA 中的循环缩短单元格引用代码的长度?
【发布时间】:2018-07-04 13:19:21
【问题描述】:

这是我关于非线性求解器的 VBA 代码:

Sub solver_macro()

    SolverOk SetCell:="$H$1", MaxMinVal:=2, ValueOf:=0, ByChange:="$E$2:$E$33", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverAdd CellRef:="$F$5", Relation:=2, FormulaText:="$G$5"
    SolverAdd CellRef:="$F$9", Relation:=2, FormulaText:="$G$9"
    SolverAdd CellRef:="$F$13", Relation:=2, FormulaText:="$G$13"
    SolverAdd CellRef:="$F$17", Relation:=2, FormulaText:="$G$17"
    SolverAdd CellRef:="$F$21", Relation:=2, FormulaText:="$G$21"
    SolverAdd CellRef:="$F$25", Relation:=2, FormulaText:="$G$25"
    SolverAdd CellRef:="$F$29", Relation:=2, FormulaText:="$G$29"
    SolverAdd CellRef:="$F$33", Relation:=2, FormulaText:="$G$33"
    SolverOk SetCell:="$H$1", MaxMinVal:=2, ValueOf:=0, ByChange:="$E$2:$E$33", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverOk SetCell:="$H$1", MaxMinVal:=2, ValueOf:=0, ByChange:="$E$2:$E$33", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve

End Sub

我试图在上面的代码中包含一个 for 循环。我的第一次尝试:

Sub solver_macro()

Dim i As Integer
Dim PERIOD As Integer

PERIOD = 7

    SolverOk SetCell:="$H$1", MaxMinVal:=2, ValueOf:=0, ByChange:="$E$2:$E$33", _
        Engine:=1, EngineDesc:="GRG Nonlinear"

        For i = 0 To PERIOD
    SolverAdd CellRef:="$F$5+4*i", Relation:=2, FormulaText:="$G$5+4*i"
        Next i

    SolverOk SetCell:="$H$1", MaxMinVal:=2, ValueOf:=0, ByChange:="$E$2:$5+4*PERIOD", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverOk SetCell:="$H$1", MaxMinVal:=2, ValueOf:=0, ByChange:="$E$2:$5+4*PERIOD", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve

End Sub

您能帮我纠正这个循环吗?提前感谢您!

编辑:感谢您的回答。如果我想用字母而不是数字循环,我该怎么做?

仍然是相同的代码,但数据是水平的。因此,循环通过字母(列)而不是数字(行):

SolverAdd CellRef:="$G$88", Relation:=2, FormulaText:="$G$89"
SolverAdd CellRef:="$K$88", Relation:=2, FormulaText:="$K$89"
SolverAdd CellRef:="$O$88", Relation:=2, FormulaText:="$O$89"
SolverAdd CellRef:="$S$88", Relation:=2, FormulaText:="$S$89"
SolverAdd CellRef:="$W$88", Relation:=2, FormulaText:="$W$89"
SolverAdd CellRef:="$AA$88", Relation:=2, FormulaText:="$AA$89"

【问题讨论】:

    标签: excel for-loop excel-2010 vba


    【解决方案1】:

    我会保持简单:

      For i = 5 To 33 Step 4
         SolverAdd CellRef:="$F$" & i, Relation:=2, FormulaText:="$G$" & i
      Next i
    

    【讨论】:

      【解决方案2】:

      您需要在引号之外进行计算,例如

      SolverAdd CellRef:="$F$" & 5+4*i, Relation:=2, FormulaText:="$G$" & 5+4*i
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多