首页 > 解决方案 > vba access - datediff

问题描述

I have 2 textboxes where the user will input a start and finish time. When I use the following code;

    Text88 = DateDiff("n", TEXTStart, TEXTFinish)

The box "Text88" will calculate the time in minutes perfectly. ie 06:00 > 14:00 = 480 minutes. However If I input say, 22:00 > 06:00, instead of equating to 480minutes it will register as -960.

How can I get it so that whatever is in the start box, it has to do up to finish, so when I input a time for 22:00 > 06:00 it will register as 480 minutes?

标签: vba

解决方案


You need to control when the user writes a greater time on the first textbox. Because DateDiff expects the second parameter to be a greater date than the first one. So, If is the case, before calculate the DateDiff you should apply a DateAdd to the second Time adding one day to the date. Then, do the DateDiff and the result will be what you expect.

Something like this:

If TEXTFinish > TEXTStart Then
    Text88 = DateDiff("n", TEXTStart, TEXTFinish)
Else
    Text88 = DateDiff("n", TEXTStart, DateAdd("d", 1, TEXTFinish))
End If

推荐阅读