减去剩余时间,并比较VBA中的数字

我有下面的代码,检查Col K为“星期天”date和“时间”,并与Col M中的数字进行比较。

这段代码是做什么的? :

例如,如果Col K中的date/时间是2/5/2017 18:00:00,则应该减去剩下的剩余时间,即当天的0.6小时,以数字M表示。如果Col M中的值大于1,则应该高亮显示,如果小于1,则应该用红色着色。

问题:

  1. 如果Col M中的值在1.5,1.6,1.7等范围内,则代码不会显示为红色。只有超过> = 2时,才会以红色着色。如何解决此问题?
  2. 目前有两个过程定义为通过和失败。 我如何结合这一点?

    Sub MinusSunday() Dim r, LastRow, RemainingDay As Double LastRow = Range("M:O").Cells(Rows.Count, "A").End(xlUp).Row Application.ScreenUpdating = False For r = 2 To LastRow RemainingDay = 0 If Weekday(Range("K" & r).Value, vbSunday) = 1 Then RemainingDay = Round((24 - Format(TimeValue(Range("K" & r)), "h")) / 24, 1) If InStr(1, Range("O" & r).Text, "Pass", vbTextCompare) > 0 Then If Range("M" & r) - RemainingDay >= 1 Then Range("M" & r).Cells.Font.ColorIndex = 3 Else Range("M" & r).Cells.Font.ColorIndex = 0 End If End If End If Next r For r = 2 To LastRow RemainingDay = 0 If Weekday(Range("K" & r).Value, vbSunday) = 1 Then RemainingDay = Round((24 - Format(TimeValue(Range("K" & r)), "h")) / 24, 1) If InStr(1, Range("O" & r).Text, "Fail", vbTextCompare) > 0 Then If Range("M" & r) - RemainingDay >= 1 Then Range("M" & r).Cells.Font.ColorIndex = 3 Else Range("M" & r).Cells.Font.ColorIndex = 0 End If End If End If Next r End Sub 

RemainingDay = Round((24 - Format(TimeValue(Range("K" & r).Value), "h")) / 24, 1)返回从0到1的剩余天数(你的例子返回0.2 )。

所以当运行它时,如果列M> = 1.3中的值,它将使该单元格中的字体以红色着色。

我有一个Select Case与一个小“窍门”来结合你的两个程序。

注意 :由于您使用RemainingDay以分数(从0到1)获取当天剩余时间的值,因此您可以使用:

 RemainingDay = 1 - TimeValue(Range("K" & r).Value) 

(目前尚未在代码中执行,等待PO反馈)。

要在几小时内获得RemainingDay时间,您可以使用:

 RemainingDay = 24 * (1 - TimeValue(Range("K" & r).Value)) 

 Option Explicit Sub MinusSunday() Dim r As Long, LastRow As Long, RemainingDay As Double With Worksheets("Latency") LastRow = .Range("M:O").Cells(.Rows.Count, "A").End(xlUp).Row Application.ScreenUpdating = False For r = 2 To LastRow RemainingDay = 0 If Weekday(.Range("K" & r).Value, vbSunday) = 1 Then ' returns the RemainindDay value in part of days (rounded) RemainingDay = Round((24 - Format(TimeValue(.Range("K" & r).Value), "h")) / 24, 1) ' Use Select case "Trick" for both cases Select Case True Case .Range("O" & r).Text Like "Pass", .Range("O" & r).Text Like "Fail" ' ===== Line below Just for DEBUG ===== .Range("L" & r).Value = .Range("M" & r) - RemainingDay If .Range("M" & r) - RemainingDay >= 1 Then .Range("M" & r).Cells.Font.ColorIndex = 3 Else .Range("M" & r).Cells.Font.ColorIndex = 0 End If Case Else ' currently do Nothing, maybe for the future ? End Select End If Next r End With End Sub 

运行此代码将返回以下结果(请参阅“L”列中添加的debugging):

在这里输入图像说明