【问题标题】:Using Solver in VBA excel to find the optimal and specific value of "alpha" in a lot of rows在 VBA excel 中使用 Solver 在很多行中找到“alpha”的最佳和特定值
【发布时间】:2019-01-30 18:27:19
【问题描述】:

我正在用 excel 创建一个预测工作簿,但在为我的单指数平滑计算获取最佳 alpha 值时遇到了一些麻烦。我正在使用的工作表如下所示。

所有这些值的计算发生在不同的工作表中,我不会发布这些,因为我认为它们不相关。我使用了 excel 插件 Solver 来找到第一个产品(底漆)的最佳 alpha 值。我使用的求解器设置如下所示:

当我单击求解时,单元格 AM2 中的值变为最佳值,这很棒。但我不知道如何为其他产品做到这一点。因此,通过更改 AM3 的值并使用约束 AM3 = 0,目标单元格将是 AO3。在工作表的最终版本中,将有 700 多个产品。我尝试在 Google 上搜索,但找不到我要查找的内容。

我正在考虑创建一个宏来执行此操作,但我对 VBA 的了解非常有限。

【问题讨论】:

  • 试试recording a macro,这将暴露求解器计算背后的 VBA 元素,然后您可以将其格式化为循环以重复您的 700 个产品。
  • @OliverCarr 非常感谢您的提示。经过一番谷歌搜索后,它现在可以按预期工作了!

标签: excel vba


【解决方案1】:

感谢@Oliver Carr 提供的提示,我修复了它。希望它对未来的人有用。

  Sub solverMacro()
'
' solverMarco Macro
'

Dim sheetName As String
Dim endRow As Integer
Dim row As Integer


sheetName = "SAP"

With Sheets(sheetName)

    endRow = .UsedRange.SpecialCells(xlCellTypeLastCell).row 'gets the last used row

    For row = 2 To endRow - 1 Step 1 'This loops through all rows that are being used
        SolverReset 'resets the solver

        SolverOk SetCell:="$AO$" & row, MaxMinVal:=2, ValueOf:=0, ByChange:="$AM$" & row, Engine _
        :=1, EngineDesc:="GRG Nonlinear" 'Sets the target set AO + the value of row. I did this so it will increment

        SolverAdd CellRef:="$AM$" & row, Relation:=1, FormulaText:="1" 'adds the constraint. Cel AM + row smaller or equal to 1
        SolverAdd CellRef:="$AM$" & row, Relation:=3, FormulaText:="0" 'adds the constraint. Cel AM + row greater or equal to 0

        SolverSolve True 'This runs the solver. True is there to make sure the dialog window does not show up

    Next row 'Goes to the next row to start all over

    MsgBox "Value is optimised" 'A msgBox to show that the macro is completed

End With

End Sub

希望这会有所帮助,祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 2021-03-25
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多