Excel求解器忽略VBA中的约束 [英] Excel Solver Ignoring Constraint in VBA

查看:379
本文介绍了Excel求解器忽略VBA中的约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Solver找到一个简单投资组合的最大回报。在工作表中使用Solver可以直观地工作,但是在VBA中没有设置命令时。相反(从screengrab可以看出)它忽略了一个约束(T10中计算的权重之和应该= 1)。有趣的是,如果我更改第三行来说:

  SolverAdd CellRef:=$ T $ 10,关系:= 2,FormulaText:=100

或1以外的任何其他整数。
(也可能忽略其他约束,但我无法检查)。
表格如下所示:



我的代码是:

  Sub FindRange()

SolverReset
SolverOk SetCell:=$ T $ 7,MaxMinVal = 1,ValueOf:=0,ByChange:=$ O $ 10:$ R $ 10
SolverAdd CellRef:=$ T $ 10,关系:= 2,FormulaText:=1
SolverAdd CellRef:=$ O $ 10:$ R $ 10,关系:= 3,FormulaText:=0
SolverSolve UserFinish: = True
SolverFinish KeepFinal:= 1
范围(T9)。值=范围(T7)值
End Sub
/ pre>

任何建议都非常欢迎!

解决方案

周围的bug。对于FormulaText:= 1的标志。而不是使用1,而是使用值为1的任何单元格的引用。



即,将FormulaText:= 1更改为FormulaText:= $ H $ 5其中$ H $ 5的值为1


I am trying to find a maximum return for a simple portfolio using Solver. Using Solver in the worksheet directly works sensibly, however it does not when the commands are set in VBA. Instead (as you can see from the screengrab)it ignores one of the constraints (that the sum of weights calculated in T10 should =1). Interestingly it works fine if I change the third line to say:

SolverAdd CellRef:="$T$10", Relation:=2, FormulaText:="100"

Or any other integer other than "1". (It may also be ignoring the other constraint but I cannot check this). The table looks like this:

And my code is:

Sub FindRange()

                SolverReset
                SolverOk SetCell:="$T$7", MaxMinVal:=1, ValueOf:="0", ByChange:="$O$10:$R$10"
                SolverAdd CellRef:="$T$10", Relation:=2, FormulaText:="1"
                SolverAdd CellRef:="$O$10:$R$10", Relation:=3, FormulaText:="0"
                SolverSolve UserFinish:=True
                SolverFinish KeepFinal:=1
                Range("T9").Value = Range("T7").Value
           End Sub

Any suggestions gratefully welcomed!

解决方案

Found a work around for the bug. For the flag "FormulaText:=1". instead of using 1, use a reference to any cell with the value 1 instead.

I.e., Change "FormulaText:=1" to "FormulaText:=$H$5" where $H$5's value is 1

这篇关于Excel求解器忽略VBA中的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆