Visual Basic MacroSolve循环错误-数据只填充最后一行,我只想收集返回的整个变量



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

  1. 我希望更改变量仅为整数值(四舍五入)(例如:患者只需要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

你可以用任何数字测试它,你会看到它是有效的(例如:3.9999 + 0.5将返回4。3.0001 +0.5也会返回4)

第二个问题是如果你要循环遍历单元格我建议使用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"当涉及到循环时,当我在可能更容易的公式上测试它时,它工作得很好。也有可能解算器只找到最后一行的解。尝试在所有行中使用完全相同的参数,就像您在最后一行中使用的一样,并且要意识到您不可能总是得到一个解决方案!

相关内容

最新更新