未能更正简单的舍入错误
Failing to correct a simple rounding error
我有一个小脚本,可以将预算安排成另一个软件接受的月度格式。该脚本大部分工作正常,除了一些数字不能被 12 整除。我无法更正它。
table 原来是这样的:
..当脚本为 运行 时,table 变为:
..总计 12 999.60 - 不是原来的 13 000.00。差异可能看起来有点微不足道,但数字是数以万计,所以不幸的是它们确实很重要。
我确实认为我可以通过取四舍五入的总数并减去最后一个条目中的原始数字来解决舍入误差,这听起来像是一个笨拙的解决方案,但没关系,但这给出了以下结果:
..总共 13 003.60。我可能会把这一切都弄错,解决方案可能很简单,我请你原谅我的无能,但这是尝试更正的代码:
'For each budget post..'
For Each row In rng.Rows
Dim i As Long
'Decimal count var'
Dim countDec As Long
countDec = 0
'Repeat twelve times'
For i = 1 To 12
'Test if row is empty'
If Len(Range("A" & x).Value) > 0 Then
'Add the current periods number to the variable..'
countDec = countDec + Round(Range("D" & x).Value / 12, 1)
'New values to cells'
Cells(j, 6).Value = Range("A" & x).Value 'Account'
Cells(j, 7).Value = i 'Period value +1'
Cells(j, 8).Value = Range("C" & x).Value 'Cst'
'Correct decimal on 12th iteration'
If i = 12 Then
countDec = countDec - Range("D" & x).Value 'Count the difference between the total periods and the original value'
Cells(j, 9).Value = Round(Range("D" & x).Value / 12, 1) + countDec '1/12th plus sum of decimal difference'
ElseIf i <> 12 Then
Cells(j, 9).Value = Round(Range("D" & x).Value / 12, 1) 'If not last iteration, just print rounded period value'
End If
j = j + 1
End If
Next i
x = x + 1
Next row
试试这个 If i = 12
子句:
If i = 12 Then
Cells(j, 9).Value = Range("D" & x).Value - Round(Range("D" & x).Value / 12, 1) * 11
我有一个小脚本,可以将预算安排成另一个软件接受的月度格式。该脚本大部分工作正常,除了一些数字不能被 12 整除。我无法更正它。
table 原来是这样的:
..当脚本为 运行 时,table 变为:
..总计 12 999.60 - 不是原来的 13 000.00。差异可能看起来有点微不足道,但数字是数以万计,所以不幸的是它们确实很重要。
我确实认为我可以通过取四舍五入的总数并减去最后一个条目中的原始数字来解决舍入误差,这听起来像是一个笨拙的解决方案,但没关系,但这给出了以下结果:
..总共 13 003.60。我可能会把这一切都弄错,解决方案可能很简单,我请你原谅我的无能,但这是尝试更正的代码:
'For each budget post..'
For Each row In rng.Rows
Dim i As Long
'Decimal count var'
Dim countDec As Long
countDec = 0
'Repeat twelve times'
For i = 1 To 12
'Test if row is empty'
If Len(Range("A" & x).Value) > 0 Then
'Add the current periods number to the variable..'
countDec = countDec + Round(Range("D" & x).Value / 12, 1)
'New values to cells'
Cells(j, 6).Value = Range("A" & x).Value 'Account'
Cells(j, 7).Value = i 'Period value +1'
Cells(j, 8).Value = Range("C" & x).Value 'Cst'
'Correct decimal on 12th iteration'
If i = 12 Then
countDec = countDec - Range("D" & x).Value 'Count the difference between the total periods and the original value'
Cells(j, 9).Value = Round(Range("D" & x).Value / 12, 1) + countDec '1/12th plus sum of decimal difference'
ElseIf i <> 12 Then
Cells(j, 9).Value = Round(Range("D" & x).Value / 12, 1) 'If not last iteration, just print rounded period value'
End If
j = j + 1
End If
Next i
x = x + 1
Next row
试试这个 If i = 12
子句:
If i = 12 Then
Cells(j, 9).Value = Range("D" & x).Value - Round(Range("D" & x).Value / 12, 1) * 11