Time comparison in VBA: inequal while same time

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 09:29:25

问题


I'm moving a database from Microsoft Access to SQL server, and am validating data equality between the remote and the local table. While doing so, I encountered an oddity when comparing a time field.

I'm using the following function:

Public Function CheckAllFieldsEqual(rs1 As DAO.Recordset, rs2 As DAO.Recordset) As Boolean
    Dim fld As DAO.Field
    CheckAllFieldsEqual = True
    For Each fld In rs1.Fields
        If fld.Value <> rs2.Fields(fld.NAME).Value Then GoTo ReturnFalse
    Next fld
    Exit Function
ReturnFalse:
    Debug.Print "Fields inequal! " & fld.NAME & ": " & fld.Value & " - "; rs2.Fields(fld.NAME).Value
    CheckAllFieldsEqual = False
    MsgBox "Inequal!", vbCritical
    Stop
End Function

rs1 is the remote recordset, set to a random row. rs2 is the local variant, set to a row with the same primary key. They should be identical, since I just created the remote table by moving the local table using DoCmd.TransferDatabase

Debug.Print fld.Value returns 09:46:00. Debug.Print rs2.Fields(fld.NAME).Value also returns 09:46:00. However, the comparison doesn't pass.

The odd part:

Debug.Print CDbl(fld.Value) returns 0.406944444444444

Debug.Print CDbl(rs2.Fields(fld.NAME).Value) returns 0.406944444444445

How do I avoid these kinds of errors? Should I add type checking and check equality for time fields with a certain precision, or is there a more simple way to avoid this?


回答1:


Use DateDiff. It is exactly for a purpose like this to ignore the floating point errors:

If DateDiff("s", fld.Value, rs2.Fields(fld.NAME).Value) <> 0 Then GoTo ReturnFalse


来源:https://stackoverflow.com/questions/47789884/time-comparison-in-vba-inequal-while-same-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!