2012-11-15 25 views
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日期格式格式化單元格,所以它們顯示正常,但值不匹配。我可以簡單地更改顯示的值以符合值嗎?如果是這樣,我該怎麼做?

在此先感謝。

更新:在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

您正在比較實際日期和字符串。您需要先從用戶輸入的值創建一個日期。 –

回答

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),而是使用設置範圍或動態範圍。

+0

謝謝凱文!我通過輸入幾種不同的日期格式來測試你的代碼,它們都可以工作!我知道我必須錯過日期格式的東西,但我不像Excel VBA那麼熟悉Word VBA。 我最終將「if then」語句嵌套在另一個檢查(並跳過)空白單元格的語句中,所以現在它不會更改整列中成千上萬的空行。我想按照你的建議使用設置的範圍或動態範圍,但我不知道如何。我要去看看,但任何幫助都會很棒。 – Mike

+0

好吧,我想出瞭如何獲得一個動態範圍,並經過一些調整後,我得到了它正是我所需要的。再次感謝你的幫助。 – Mike

+0

非常好 - 做得很好。很高興我能幫上忙! –

相關問題