0

以下代码工作正常,但它没有将存储的值四舍五入到最接近的便士,例如 8.025 即将到来而不是 8.01 有人可以建议修复吗?

Public Function Fs_Update_AccInvoices_Nexum() As Boolean
    Dim adoRsInvoiceDCID As New ADODB.Recordset
    Dim adoRsNexumInvoices As New ADODB.Recordset

    On Error Resume Next
    adoRsInvoiceDCID.Open "SELECT * FROM [tInvoiceDCID] where Issued=0" _
        , CurrentProject.Connection, 2, 2
    While Not adoRsInvoiceDCID.EOF
        adoRsNexumInvoices.Open "SELECT * FROM [tPrintInvoiceNumbersNexum] " _
            & " WHERE InvoiceID=" & adoRsInvoiceDCID("InvoiceID") _
            , CurrentProject.Connection, 2, 2
        If Not adoRsNexumInvoices.EOF Then
            DoCmd.SetWarnings off
            DoCmd.RunSQL "Update [Acc Invoices t Nexum] " _
                & " SET [Total Due] = Round((Fees/0.8)+(VAT/0.8)+OutLays,2)" _
                & " Fees = Round(Fees/0.8,2), VAT = Round(Vat/0.8,2)" _
                & " WHERE Invoice=" & adoRsNexumInvoices("PrintingasINVOICE")
        End If
        adoRsNexumInvoices.Close

        adoRsInvoiceDCID.MoveNext
    Wend
    adoRsInvoiceDCID.Close
End Function

干杯罗斯

4

2 回答 2

2

快速说明:我注意到 vba 的舍入函数存在格式函数无法修复的一些不准确之处。在我的特殊情况下,我试图四舍五入数字 3687.23486

回合(3687.23486)= 3687.23

格式(3687.23486,“#.00”)= 3687.23

在传统的四舍五入规则下,这应该会导致 3687.24 我已经看到在各种论坛上发布了几个自定义函数来解决舍入问题,但没有一个对我有用,所以我自己写了。

    Function trueRound(ByVal varNumber As Variant, ByVal intDecimals As Integer) As Double
    If IsNull(varNumber) Then
        trueRound = 0
        Exit Function
    End If
    Dim decimals As Integer, testNumber As Double
    decimals = 0
    If InStr(varNumber, ".") > 0 Then decimals = Int(Len(varNumber)) - Int(Len(Fix(varNumber)) + 1)
    If decimals = 0 Or intDecimals > decimals Then
        trueRound = varNumber
        Exit Function
    End If
    Do Until Len(varNumber) - Len(Fix(varNumber)) - 1 <= intDecimals
        testNumber = varNumber * 10 ^ (decimals - 1)
        varNumber = Round(testNumber, 0) / 10 ^ (decimals - 1)
        decimals = decimals - 1
    Loop
    trueRound = varNumber
End Function

我很快就把它算出来了,所以没有错误处理,传递给函数的空值会导致 0,这可能并不适合所有情况。我经常在一些非常大的查询中使用它,希望它可以帮助别人。

于 2012-10-12T19:17:56.010 回答
1

“Round 函数执行从round to even,这与从round to large 不同。” - 微软

Debug.Print Round(19.955, 2)
'Answer: 19.95

Debug.Print Format(19.955, "#.00")
'Answer: 19.96

另请参阅如何在 MS Access、VBA 中舍入

于 2012-07-24T12:32:19.247 回答