简体   繁体   中英

Is is possible to set a large set of constraints for the Solver in Excel using named ranges?

So, I have a 50 variables that have a minimumum and a maximum bound.

I want to set these as constraints.

The 50 variables are in cells A1 through A50

The maximum constraints are in B1 through B50 and the mininums are in C1 through C50.

Can I name A1:A50 A, B1:B50 B, and C1:C50 C and then set the constraint as follows:

SolverAdd cellRef:="A", relation:=1, formulaText:="B"

and

SolverAdd cellRef:="A", relation:=3, formulaText:="C"

instead of 100 lines that go:

SolverAdd cellRef:=range("A1)", relation:=1, formulaText:=Range("B1")
SolverAdd cellRef:=Range("A1"), relation:=3, formulaText:=Range("C1")
...
SolverAdd cellRef:=range("A25)", relation:=1, formulaText:=Range("B25")
SolverAdd cellRef:=Range("A25"), relation:=3, formulaText:=Range("C25")

...

and so on?

You can used named ranges, and in fact it is a good idea for readability. "A","B","C" are themselves not valid names, but things like "A_" are (though something which has a meaning in your model such as eg "Purchase" might be better). To use the named ranges, use syntax like this (which is similar to your proposed syntax):

SolverAdd CellRef:=Range("A_"), Relation:=1, FormulaText:="B_"
SolverAdd CellRef:=Range("A_"), Relation:=3, FormulaText:="C_"

which should work as expected.

Here is a complete example: A_ is the name of A1:A50 , B_ of B1:B50 and C_ of C1:C50 . I use A51 as the objective function which is simply the sum of A_ . I initialize A_ to be all 0 , B_ to be all 10 and C_ to be all 1 . Then I run the following code:

Sub Test()
    SolverOk SetCell:="$A$51", MaxMinVal:=1, ByChange:="A_", Engine:=2
    SolverAdd CellRef:=Range("A_"), Relation:=1, FormulaText:="B_"
    SolverAdd CellRef:=Range("A_"), Relation:=3, FormulaText:="C_"
    SolverSolve True
End Sub

After running the code, A_ contains all 10 , as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM