VBA If statement to see if time is between 2 paramters

Sullster47

New member
Local time
Today, 01:55
Joined
Apr 29, 2021
Messages
2
I have an if statement where i need to see if the time of a field is between 8pm and 6 am. If it is, we have a different rate but i can't get the if statement to work.
i have:
If me.txtTime < #5:59:00 AM# and me.txtTime > #7:59:00 PM# then
me.txtrate.vale = CDbl(Nz(me.SatNightRate))
else
me.txtrate.vale = CDbl(Nz(me.SatRate))
end if


any help much appreciated
thanks
 
In a computer, time of day by itself isn't a circle, it's a line: It goes from 0 to 24. So a time can't be under 6 and over 20--> theres no such number on the line that can ever meet those 2 conditions.

You need to flip the logic. You want a time that is under 6 or over 20.
 
Your statement would work correctly if you wrote it using OR instead of AND.

Also, were you writing .vale meaning .value? Because that isn't necessary. The default for a control that has a value at all IS the .Value property so if that is what you meant, you can omit the value reference. If you actually wrote .vale, you should have gotten an "unknown property" error.

Note that not all controls have values. For instance, a LINE control and a LABEL control have no value. There are others such as the individual buttons of a radio button group that don't have values - but the radio button group (as a whole) actually DOES have a value.
 
Code:
(hour(control)>=20) and (hour(control)=6) then ...
 
There is contradiction to your first If statement.

If the Time is Less than 6 am but Greater than 7:59 pm? how is that.
should be:

If TimeValue(me.txtTime) > #5:59:59 AM# and TimeValue(me.txtTime) < #7:59:59 PM# then
me.txtrate = Val(me.SatRate & "")
else
me.txtrate = Val(me.SatNightRate & "")
end if
 
The statement could have been done by reversing the inequalities and changing it to an OR (based on DeMorgan's Theorem).

Code:
IF TimeValue( Me.txtTime ) < # 06:00:00 AM # OR  TimeValue( Me.txtTime ) > # 08:00:00PM # THEN
    Me.txtRate = Val( Me.SatNightRate & "" )
ELSE
    Me.txtRate = Val( Me.SatRate & "" )
END IF
 
Thank you to all that have replied. Yes, you are correct in that the statement doesn't make literal sense.
I have turned it round as per the answers and it now works.
Great to have the help put there.
All the best
J
 
Wouldn't
Code:
 TimeValue( Me.txtTime ) < # 06:00:00 AM
be Friday night?
 
There is no way in the expression given to determine day of the week so the question is moot:)
 

Users who are viewing this thread

Back
Top Bottom