1

我只是想在特定列中搜索早于用户指定日期的任何日期。

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 日期格式格式化了单元格,所以它们显示得很好,但值不匹配。我可以简单地更改显示内容以匹配该值吗?如果是这样,我该怎么做?

提前致谢。

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

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
4

1 回答 1

1

您已定义TheAnswer为字符串,而 therCell.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

Also, consider not using the entire column (D:D) and instead use a set range or a dynamic range.

于 2012-11-15T18:54:03.903 回答