2013-07-29 35 views
-2

我在B2範圍內有日期範圍到文檔末尾。我想讓用戶收到一個輸入框「你在找什麼日期」,用戶將輸入日期。然後,用戶數據將用於搜索行B2到最後並查找該特定日期。如果該日期不存在,則會彈出另一個框,讓用戶知道他們需要延長範圍並再次嘗試。即使在輸入正確的數據時,我仍然會收到「添加天數」,但不會輸出「您的好評」。誰能幫我嗎?VBA循環查找具有用戶輸入的具體日期

Sub Macro2() 
    datein = CDate(InputBox("Date Project Will Start")) 

    For Each c In Worksheets("sheet1").Range("A1:D100").Cells 
      If datein = c.Value Then MsgBox "Your Good" 

    Next 
    MsgBox "Add More Days" 
End Sub 
+0

我不確定你的問題是什麼。想必不是,請寫一些代碼來執行上述任務。 – grantnz

+0

抱歉,我想複製代碼 –

回答

1

由grantnz提供的答案確實解決了值比較的問題,但你需要打破循環,執行某種驗證,以避免第二個消息......事情是這樣的:

Sub Macro2() 
    Dim datein as Date, found as Boolean ' I prefer explicit variable declaration 

    datein = CDate(InputBox("Date Project Will Start")) 
    found = False 

    For Each c In Worksheets("sheet1").Range("A1:D100").Cells 
     If datein = c.Value Then 
      MsgBox "Your Good" 
      found = True 
      Break ' You don't need to continue the iteration if you find a date 
     End If 
    Next 
    If Not found Then 
     MsgBox "Add More Days" ' This message pops up only if found is false 
    End If 
End Sub 
1

你只需要將datein轉換爲日期即可。

datein = CDate(InputBox("Date Project Will Start")) 
+0

這很好,但我得到兩個消息框。我將上面的代碼更新爲我擁有的最新代碼。我知道它正在發生,因爲它的下一行代碼發生在該循環的外側。我是否在下一個或之後放置if語句? –

+0

您可以在「您的好」消息框之後添加Exit Sub和End If。 – grantnz

+0

@MarkAustin。如果你打算在你的問題中加入修正,最好把它作爲第二塊,並且有評論說這是修復。否則,將來遇到這個問題的人會對原來的問題感到困惑。 – grantnz