如何在列中搜索日期早于特定日期的任何单元格并突出显示它们?

时间:2012-11-15 18:26:16

标签: excel vba excel-vba excel-2010

我只是尝试在特定列中搜索比用户指定的日期更早的日期。

Dim rCell As Range
Dim TheAnswer$
TheAnswer = InputBox("In M/D/YYYY format, enter the first day of the month for which this report is being run." & _
                     vbCr & vbCr & "For example, you would enter ""12/1/2012"" for the December 2012 report.", "Enter Date M/D/YYYY")

For Each rCell In ActiveSheet.Range("D:D").Cells
    If rCell.Value < TheAnswer Then
        rCell.Interior.Color = RGB(255, 102, 0)
    End If
Next rCell

我的问题是,这并不总是选择正确的。如果我使用两个数字的月份或日期,它会完全忽略那些带有一位数的月份和日期。我已经使用03/14/01日期格式格式化了单元格,因此它们显示正常,但值不匹配。我可以简单地更改显示的值以匹配值吗?如果是这样,我该怎么做?

提前致谢。

更新:在Kevin的帮助下,我能够解决这个问题。如果有人发现它有用,这是我的最终代码:

Range(Cells(2, 4), Cells(Rows.Count, 4).End(xlUp)).Select

Dim rCell As Range
Dim TheAnswer$
Dim ConvertedDate#

TheAnswer = InputBox("In M/D/YY format, enter the first day of the month for which this report is being run." & _
                     vbCr & vbCr & "For example, you would enter ""12/1/2012"" for the December 2012 report.", "Enter Date M/D/YY")
ConvertedDate = CDate(TheAnswer)

For Each rCell In Selection
    If rCell.Value <> "" Then
        If rCell.Value < ConvertedDate Then
            rCell.Interior.Color = RGB(255, 102, 0)
        End If
    End If
Next rCell

1 个答案:

答案 0 :(得分:1)

您已将TheAnswer定义为字符串,而rCell.Value将是日期,因此结果将不一致。试试这个:

Dim rCell As Range
Dim TheAnswer$
Dim ConvertedDate#
TheAnswer = InputBox("In M/D/YYYY format, enter the first day of the month for which this report is being run." & _
                 vbCr & vbCr & "For example, you would enter ""12/1/2012"" for the December 2012 report.", "Enter Date M/D/YYYY")
ConvertedDate = CDate(TheAnswer)
For Each rCell In ActiveSheet.Range("D:D").cells
If rCell.Value < ConvertedDate Then
    rCell.Interior.Color = RGB(255, 102, 0)
End If
Next rCell

另外,请考虑不使用整个列(D:D),而是使用设定范围或动态范围。