Excel VBA – 如果时间大于24小时,则突出显示单元格

我有一个报告,一般会在每天上午7点后运行,但偶尔可能会在白天晚些时候运行。 D栏中列出了机票更新时间/date。 如果票是昨天更新的,那么这个单元应该放在一边; 如果票据昨天没有更新(IE,如果今天是第三,并且从一号的X点开始没有更新),那么该单元应该突出显示。 由于报告有时候不会运行,直到当天晚些时候,我不能做一个简单的CurrentTime – 24小时来解决这个问题。 我需要的function,总是寻找前一天,早上7点。

不知道如何编码这个,我知道它应该是这样的:

If ticketUpdateTime < currentDay at 0700 - 24 Then highlight (I know the code for this part already) End If 

希望这是有道理的

 If DateDiff("h", CDate(ticketUpdateTime), CDate(Format(Now(), "mm/dd/yy")) + TimeSerial(7, 0, 0)) > 24 Then highlight End If 

用简单的英语:

如果ticketUpdateTime与今天07:00 AM之间的时间超过24小时,请突出显示

原来的问题有点超出范围,但这里也有用法示例:

 Sub CheckTimes(rng As String) Dim someRange As Range, someCell As Range Set someRange = Range(rng) ' Convert input string to an actual range object For Each someCell In someRange If DateDiff("h", CDate(someCell.Value), CDate(Format(Now(), "dd/mm/yy")) + TimeSerial(7, 0, 0)) > 24 Then Debug.Print "Highlight" End If Next cell End Sub 

要调用它,请inputCall CheckTimes("D2:D100")或您需要的任何范围

请注意,这里没有错误检查/处理或数据validation – 您必须自己做。 😉

您可以使用dateserial(年份为整数,月份为整数,date为整数)和TimeSerial(小时为整数,分钟为整数,秒为整数)。 我不知道你的ticketUpdateTime是怎么样的,所以很难写出expression式。 不过,前一天早上7点会是:

 dateserial(year(date-1), month(date-1), day(date-1)) & " " &timeserial(7, 0, 0) 

似乎是一个问题。 所有的date/时间都是昨天,除了D2中的值是11/01/2017 10:47:02,并且该值没有突出显示。

 Call CheckTimes("D2:D" & lastRow) Sub CheckTimes(rng As String) Dim someRange As Range, someCell As Range Set someRange = Range(rng) ' Convert input string to an actual range object For Each someCell In someRange If DateDiff("h", CDate(someCell.Value), CDate(Format(Now(), "dd/mm/yy")) + TimeSerial(7, 0, 0)) > 24 Then someCell.Interior.Color = 16750899 End If Next someCell End Sub