用户在VBA中定义Excel Solver功能的范围

时间:2014-03-17 12:53:06

标签: excel vba excel-vba solver

我到处搜索并尝试让它正常工作几个小时,但我的宏不会打球,而且解决方案因“设置问题...”而停滞不前。阶段!

这就是我想要做的: 1)用户启动宏并提示选择要优化的单元格范围 2)求解器找到解决方案并退出

如果有人能够建议我如何让这个工作,我将非常感激!

非常感谢,

Rendeverance

This is my code:

Sub Optimise()
Dim UserRange As Range

SolverReset


  Set UserRange = Application.InputBox("Use the mouse to select cells to optimise (Hold       Ctrl to select multiple films)", Type:=8)

    If UserRange Is Nothing Then
        MsgBox "Cancel pressed"
    Else

    'Set solver parameters and solve using GRG Nonlinear
    '
    SolverOk SetCell:="$V$13", MaxMinVal:="$V$15", ValueOf:=0, ByChange:="UserRange", Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve UserFinish:=True
    SolverFinish KeepFinal:=1
    End If


End Sub

1 个答案:

答案 0 :(得分:1)

感谢Simoco识别出'.Address'的遗漏,但是当将MaxMinVal定义为一个单元格(而不仅仅是'1'或'2')时,我仍然无法完成上述工作

所以我使用了一个嵌套的IF语句,如下所示 - 这可行,但可能有一个更优雅的方式,如果有人可以给我这方面的提示,将不胜感激:

Sub Optimise()

'
Dim OptiRange As Range

' Activate the sheet required and reset solver settings
Sheets("Dashboard").Activate
SolverReset

' Add-in some bad error handling ;-)
On Error GoTo endofmacro

'Ask user for what cells to optimise
Set OptiRange = Application.InputBox("Use the mouse to select cells to optimise (Hold Ctrl to select multiple films individually)", Type:=8)

        'Check if this is a maximise or minimise problem
        If Range("$Z$15").Value = 1 Then
            '
            'Set solver parameters and solve using GRG Nonlinear
            SolverOk SetCell:="$Z$13", MaxMinVal:=1, ValueOf:=0, ByChange:=OptiRange.Address, Engine:=1, EngineDesc:="GRG Nonlinear"
            SolverSolve UserFinish:=True
            SolverFinish KeepFinal:=1
        Else
            '
            'Set solver parameters and solve using GRG Nonlinear
            SolverOk SetCell:="$Z$13", MaxMinVal:=2, ValueOf:=0, ByChange:=OptiRange.Address, Engine:=1, EngineDesc:="GRG Nonlinear"
            SolverSolve UserFinish:=True
            SolverFinish KeepFinal:=1
        End If

endofmacro:

End Sub