Excel Solver循环遍历公式中的行

时间:2016-02-22 19:16:52

标签: excel-vba solver vba excel

D       G
529.01  531.27
523.26  524.33
515.00  516.18
507.00  507.24
497.99  503.48
504.76  504.92
494.94  495.98
498.84  502.98
494.65  503.23
505.57  505.68
500.01  508.19
511.00  512.5
507.25  519.28
521.48  536.33
535.59  542.17
538.53  539



Formula in L14: =SUMPRODUCT($L$13:$P$13,$L$12:$P$12)

Formula in L13: =SUMPRODUCT($L$7:$L$11,D7:D11)
Formula in M13: =SUMPRODUCT($M$7:$M$11,D7:D11)
Formula in N13: =SUMPRODUCT($N$7:$N$11,D7:D11)
Formula in O13: =SUMPRODUCT($O$7:$O$11,D7:D11)
Formula in P13: =SUMPRODUCT($P$7:$P$11,D7:D11)

我的解算器宏代码是:

SolverOk SetCell:="$I$13", MaxMinVal:=3, ValueOf:=0, ByChange:="$L$7:$P$12", _
    Engine:=1, EngineDesc:="GRG Nonlinear"
SolverOk SetCell:="$I$13", MaxMinVal:=3, ValueOf:=0, ByChange:="$L$7:$P$12", _
    Engine:=1, EngineDesc:="GRG Nonlinear"
SolverSolve True

我的专栏我是:

=G12-$L$14

我的专栏K是:

=$L$14

每次我们向下行一行时,行D7:D11应该增加1。通过这种方式,我们一直向下直到达到D105,这就是列结束的时候。 我目前让Solver运行一个目标函数值,但我需要对G列中的每个单元格执行此操作,不包括G中的前5个单元格。

我面临的问题是我在Solver的目标函数中的单元格还有其他单元格也是公式的函数,所以我无法弄清楚如何通过迭代它们并编写求解器来更改公式在继续之前回答K列。

例如,我们从G6开始,因为我们使用D1-5的值来获得G6的值。公式如下: **

Formula in L13: =SUMPRODUCT($L$7:$L$11,D7:D11)
Formula in M13: =SUMPRODUCT($M$7:$M$11,D7:D11)
Formula in N13: =SUMPRODUCT($N$7:$N$11,D7:D11)
Formula in O13: =SUMPRODUCT($O$7:$O$11,D7:D11)
Formula in P13: =SUMPRODUCT($P$7:$P$11,D7:D11)

**

现在Solver应该像这样改变G7的公式:

Formula in L13: =SUMPRODUCT($L$7:$L$11,D8:D12)
Formula in M13: =SUMPRODUCT($M$7:$M$11,D8:D12)
Formula in N13: =SUMPRODUCT($N$7:$N$11,D8:D12)
Formula in O13: =SUMPRODUCT($O$7:$O$11,D8:D12)
Formula in P13: =SUMPRODUCT($P$7:$P$11,D8:D12)

对于G8解算器,应将公式更改为:

Formula in L13: =SUMPRODUCT($L$7:$L$11,D9:D13)
Formula in M13: =SUMPRODUCT($M$7:$M$11,D9:D13)
Formula in N13: =SUMPRODUCT($N$7:$N$11,D9:D13)
Formula in O13: =SUMPRODUCT($O$7:$O$11,D9:D13)
Formula in P13: =SUMPRODUCT($P$7:$P$11,D9:D13)

如何在使用Solver时迭代这样的公式?

1 个答案:

答案 0 :(得分:0)

这应该可以让你到达某个地方。只需将您的范围设置为命名并添加一个looper变量,将RowShift增加1 ...在测试电子表格中使用它...

Dim workingRange As Range
Set workingRange = Sheets(1).Range("A7:A11")

'alternate version, assuming you are in some sort of i-j double loop
Set workingRange = Sheets.Range( Cells(7+i,7+j) , Cells(11+i,7+j) ) 'G7:G11

'now you have some options....
workingRange.Value = "testing"
workingRange.Formula = "=Abs(B1)"

'if working with cells() and indices, the R1C1 style may be for you...
workingRange.FormulaR1C1 = "=  {formula here} "

这里是R1C1表示法的文档,它非常简单。

https://msdn.microsoft.com/en-us/library/office/ff823188.aspx

问候,凯文