Excel Visual Basic MacroSolve循环错误-仅填充最后一行的数据,我只希望返回舍入整变量
以下是我的代码,我有两个主要问题:Excel Visual Basic MacroSolve循环错误-仅填充最后一行的数据,我只希望返回舍入整变量,excel,loops,solver,vba,Excel,Loops,Solver,Vba,以下是我的代码,我有两个主要问题: 我希望变化变量仅为整数值(四舍五入)(例如:一名患者只需要x量的药物,但包装尺寸已设定,剩余药物被浪费,我不能使用1瓶半的药物,我必须使用2瓶) 我的代码只填充最下面一行(36),而不是数据开始的第25行 你的第一个问题很简单。为了使其始终显示药丸容器的总量或任何东西,您只需在数字上加0.5,然后使用如下内容: Dim packageSize As Integer packageSize = WorksheetFunction.Round(3.1 + 0.
你的第一个问题很简单。为了使其始终显示药丸容器的总量或任何东西,您只需在数字上加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循环
,而不是Do循环
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
希望这能有所帮助。您遇到的第一个问题很简单。为了使其始终显示药丸容器的总量或任何东西,您只需在数字上加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循环
,而不是Do循环
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”
当涉及到循环时,当我在可能更简单的公式上测试它时,效果很好。可能的情况是,解算器仅碰巧找到最后一行的解。尝试在所有行中使用与上一行完全相同的参数,并注意不能总是获得解决方案 对于问题中某些单元格的整数约束,只需告诉解算器,例如:SolverAdd CellRef:=“$E$”&RowCount,Relation:=4,FormulaText:=“integer”
当涉及到循环时,当我在可能更简单的公式上测试它时,效果很好。可能的情况是,解算器仅碰巧找到最后一行的解。尝试在所有行中使用与上一行完全相同的参数,并注意不能总是获得解决方案