2
votes

I would like to have a formula which will tell me if a time in a cell is between 2 separate vlaues in other cells and to return a value if so.

I have already created the below code but this is not returning any values back at all.

=IF(AND(F4>=$R$1,F4<P1),"Night Shift",IF(AND(F4>=$P$1,F4<$Q$1),"AM Shift",IF(AND(F4>=$Q$1,F4<$R$1),"PM Shift","")))

In this example the cell values are (P1 = 06:00, Q1 = 14:00, R1 = 22:00). The value in the F4 is 00:31:38.

Any help would be appreciated.

2

2 Answers

2
votes

Your first AND needs to adjust a little.

Excel sees TIME as a fraction of 1 whole day. So 00:31:38 though you meant it to be the next day from 22:00, Excel does not know that and as such will not see it greater than 22:00

We also do not need to test for the Night Shift. It is the only option left if the time is not in one of the others:

=IF(F4<>"",IF(AND(F4>=$P$1,F4<$Q$1),"AM Shift",IF(AND(F4>=$Q$1,F4<$R$1),"PM Shift","Night Shift")),"")

enter image description here


You could also create a small table like such:

0            6:00       14:00       22:00
Night Shift AM Shift    PM Shift    Night Shift

Then use a HLOOKUP to return the correct value:

=HLOOKUP(F4,O1:R2,2,TRUE)

enter image description here

2
votes

I took a slightly different path that Scotts.

  • A Night Shift occurs if the time is greater or equal to 10PM, OR is less than 6AM.
    =OR($F$4<$P$1,$F$4>=$R$1)
  • An AM Shift occurs when the time is greater or equal to 6AM, AND is less than 2PM.
    =AND($F$4>=$P$1,$F$4<$Q$1)
  • A PM Shift occurs when the time is greater or equal to 2PM, AND is less than 10PM.
    =AND($F$4>=$Q$1,$F$4<$R$1)

Stick the three conditions together and you have:

=IF(OR($F$4<$P$1,$F$4>=$R$1),"Night Shift",IF(AND($F$4>=$P$1,$F$4<$Q$1),"AM Shift",IF(AND($F$4>=$Q$1,$F$4<$R$1),"PM Shift","")))

Edit
During testing I entered 00:00:00 in A1 and =A1+TIMEVALUE("00:01:00") in A2:A1440.
At 06:00:00, 14:00:00 and 22:00:00 the changeover in shift happened a minute later.
If, however, I manually typed in 06:00:00 the changeover happened on the hour. This seems to be because TIMEVALUE is calculating 6AM as 0.2499999 rather than 0.25.