使用 VBA 检查 excel 2016 年的日期年表

Checking date chronology in excel 2016 using VBA

在excel中得到了两列数据,所有数据条目都是日期:

我需要确保第二列 (K) 中的日期不会早于第一列 (J) 中的日期。我不认为我可以为此使用条件格式。

使用 VBA,我如何检查每对日期,然后如果该日期早于 J 中的相应日期,则使 K 列中的单元格变为红色?

感谢大家的帮助!如果有帮助,我在下面附上了一张图片。我认为 K 值是否为空并不重要,因为我想知道它们是否为空,并且代码会像读取任何其他变红的日期一样读取这些值。

截图:

假设您的 sheet 是 sheet1 if not just change the name in Worksheets("")

Sub CompareDates()
     Dim Counter As Integer
     Dim myDate As Date
     Dim myDateCompare As Date

 For Counter = 1 To 100
 myDate = Worksheets("Sheet1").Cells(Counter, 10).Value 'Refers to Column J
 myDateCompare = Worksheets("Sheet1").Cells(Counter, 11).Value 'Refers to Column K
 If myDate > myDateCompare Then Worksheets("Sheet1").Cells(Counter, 11).Interior.ColorIndex = 46
 Next Counter
End Sub

如果我没理解错的话,这对之前的日期或它们为空的日期都有效。

Option Explicit
Public Sub Color()

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") '---Name it whatever the sheet name is
Dim x As Integer

For x = 6 To 100
    If ws.Cells(x, 11).Value2 <= ws.Cells(x, 10).Value2 Then
        ws.Cells(x, 11).Interior.Color = RGB(255, 0, 0) '---colors the cell red
    ElseIf ws.Cells(x, 11).Value2 = "" Then
        ws.Cells(x, 11).Interior.Color = RGB(255, 0, 0) '---If you want to color the blank ones as well
    End If
Next x

End Sub

只是为了表明您可以使用条件格式来做到这一点...

  1. Select 范围 "K6:K100".
  2. 在条件格式下,添加 "New Rule".
  3. 使用公式确定要设置格式的单元格:
  4. 输入 =K6<=J6 作为您的公式并将格式设置为红色填充。

条件格式之前

条件格式后