Visual Basic MacroSolve循环错误 – 数据只填充最后一行,我只想要综合返回的整个variables

下面是我的代码,我有两个主要问题:

  1. 我想要variablesvariables只是整个值(四舍五入)(例如:一个病人只需要x的药量,但包装的大小是设定的数量和剩余的药物被浪费,我不能使用1和半小瓶的药物,我必须使用2个小瓶)。

  2. 我的代码只填充底部行(36),而不是行数25在我的数据开始

Sub MacroSolve() Worksheets("Sheet1").Activate Rowcount = 25 Do While Not IsEmpty(Worksheets("Sheet1").Range("D" & Rowcount)) SolverReset SolverOptions precision:=0.001 SolverOk SetCell:="$H$" & Rowcount, MaxMinVal:=2, ValueOf:=0, ByChange:="$E$" & Rowcount & ":$F$" & Rowcount SolverAdd CellRef:="$E$" & Rowcount, Relation:=3, FormulaText:="0" SolverAdd CellRef:="$F$" & Rowcount, Relation:=3, FormulaText:="0" SolverAdd CellRef:="$G$" & Rowcount, Relation:=3, FormulaText:=Range("$D$" & Rowcount) SolverAdd CellRef:="$H$" & Rowcount, Relation:=3, FormulaText:=Range("$F$21") SolverSolve UserFinish:=True SolverFinish keepFinal:=1 Rowcount = Rowcount + 1 Loop End Sub 

你有第一个问题是一个容易的。 为了让它总是显示整个药丸容器或任何你只需要添加0.5的数字和使用这样的东西:

 Dim packageSize As Integer packageSize = WorksheetFunction.Round(3.1 + 0.5, 0) 'Replace 3.1 with whatever value you will be using/with a cell reference 

你可以testing任何数字,你会看到它的工作(例如:3.9999 + 0.5将返回4和3.0001 + 0.5也将返回4)

现在第二个问题,如果你正在循环单元格,我会build议使用For Loop而不是一个Do Loop

 Dim workingCell as Range Dim workingRange as Range dim i as long 'This finds the last row in which you have data (assuming nothing goes beyond row 500,000) i = Sheets("Sheet1").Range("D500000").End(xlUp).Row Set workingRange = Sheets("Sheet1").Range("D25:D" & i) 'This is the loop that goes through all the cells in the column For each workingCell in workingRange.Cells '... place your code here... Next workingCell 

希望这可以帮助。

对于问题中的某些单元格的整数约束,只需告诉求解器,例如: SolverAdd CellRef:="$E$" & RowCount, Relation:=4, FormulaText:="integer"说到循环,很好,当我testing它大概更简单的公式。 解决scheme可能只是碰巧find最后一行的解决scheme。 尝试在所有行中具有完全相同的参数,就像你在最后一样,注意你不能总是得到一个解决scheme!