View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
joeu2004 joeu2004 is offline
external usenet poster
 
Posts: 2,059
Default If then statement based on time of day

On Jun 22, 4:46*pm, Sabosis wrote:
I am trying to update a cell with text (time of day) based
on the time the report is actually run. The report runs at
roughly 15 past the hour 3 times a day, but I dont want the
report to show the actual time but rather the "top of the
hour" time as shown in the code. The code doesnt work though,
any ideas?


In what way does it not work? Gives examples. "When the time is
this, I expect that, but I get this instead".

Range("A2").Select
If Time < TimeSerial(11, 30, 0) Then
Range("A2").Select
ActiveCell.FormulaR1C1 = "11:00"
ElseIf Time < TimeSerial(2, 30, 0) Then
Range("A2").Select
ActiveCell.FormulaR1C1 = "2:00"
ElseIf Time < TimeSerial(5, 30, 0) Then
Range("A2").Select
ActiveCell.FormulaR1C1 = "5:00"
End If


I suspect you want:

Sub doit()
Dim t As Date
Select Case Time
Case Is < TimeSerial(11, 30, 0)
t = TimeSerial(11, 0, 0) '11:00 AM
Case Is < TimeSerial(14, 30, 0)
t = TimeSerial(14, 0, 0) '2:00 PM
Case Else
t = TimeSerial(17, 0, 0) '5:00 PM
End Select
Range("A2") = t
Range("A2").NumberFormat = "h:mm am/pm"
End Sub

But I don't understand that logic. I presume that the report
__should_be__ at 11:00-, 2:00- and 5:30-ish. But why not capture the
hour of the day that the report is actually run?

To that end:

Sub doit()
Range("A2") = TimeSerial(Hour(Time), 0, 0)
Range("A2").NumberFormat = "h:mm am/pm"
End Sub

In both cases, add Range("A2").Select only if you want the cursor to
be positioned in A2 when you are done. Normally, that is not the case.