MS ACCESS OpenRecordset 四舍五入小数

MS ACCESS OpenRecordset rounding decimals

我有一个显示我的产品价格并与前几个月进行比较的查询。 Access 中的查询正确显示了小数点后 4 位的价格,但是当我使用下面的代码导出到 Excel 时,数字四舍五入到小数点后 2 位。 我的代码有很多我省略的格式行。请注意,我没有在 excel 中格式化价格。我想显示整个数字。 我认为 Recordset 函数以某种方式对数字进行四舍五入。 感谢您的帮助。谢谢

            Dim xlApp As Object
            Dim xlBook As Object
            Dim xlSheet As Object
            Dim i As Integer

            Dim SQL As String
            Dim rs1 As DAO.Recordset

 SQL = "SELECT tblTempCurrentPastRawPrice.ID, tblTempCurrentPastRawPrice.[Raw Material]," & _
        "tblTempCurrentPastRawPrice.Lastbought, tblTempCurrentPastRawPrice.PreviousPrice," & _
        "tblTempCurrentPastRawPrice.Newdate, tblTempCurrentPastRawPrice.LastPrice," & _
        "tblTempCurrentPastRawPrice.ReportDate FROM tblTempCurrentPastRawPrice ORDER BY tblTempCurrentPastRawPrice.[Raw Material]"


        Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)


 Set xlApp = CreateObject("Excel.Application")

            xlApp.Visible = False
            Set xlBook = xlApp.Workbooks.Add
            Set xlSheet = xlBook.Worksheets(1)

    With xlSheet

   i = 7    

            Do While Not rs1.EOF


                .Range("A" & i).Value = Nz(rs1![Raw Material], "")
                .Range("B" & i).Value = Nz(rs1!Lastbought, "")
                .Range("C" & i).Value = Nz(rs1!PreviousPrice, 0)
                .Range("D" & i).Value = Nz(rs1!Newdate, 0)
                .Range("E" & i).Value = Nz(rs1!LastPrice, 0)

                i = i + 1
                rs1.MoveNext

有趣,我可以重现这个。发生这种情况是因为列的类型为 Currency.

显然,Excel 像往常一样想变得更聪明而不是对你有好处,并假设货币总是带有两位小数并四舍五入。

要轻松重现,请使用此代码:

With xlSheet
    i = 7
    .Range("F" & i).Value = CDbl(1.2345)    ' Result: 1.2345
    .Range("G" & i).Value = CCur(1.2345)    ' Result: 1.23 €
End With

请注意,Access 中的 CCur(1.2345) 仍然是 1.2345

要解决它,在写入Excel之前转换为Double,然后格式作为Excel中的货币(使用2或4 位小数,在这两种情况下,数字实际上都有 4 位小数):

        With .Range("C" & i)
            .Value = CDbl(Nz(rs1!PreviousPrice, 0))
            .NumberFormat = "#,##0.0000 $"
        End With