2015-12-02 236 views
0

我想在下面的代碼中實現一個控件,只允許帶有mm/dd/yyyy格式的日期,並防止在輸入框中輸入空格。我試着添加一些代碼,但仍然遇到錯誤。第一個檢查它是否空白的控件有效,但是第二個控件如果Not似乎只是被忽略。如何限制輸入框輸入僅限日期

'Updates the report date located in report generation tab cell B8 
Dim ws1 As Worksheet 
Set ws1 = Sheets("Report Generation") 
ReTry: 
With ws1 
    Dim rptdate As Variant 
     rptdate = InputBox("Please Enter the Report Date *Must be EOM format mm/dd/yyyy*", "Enter Date") 
     If rptdate = "" Then 
     MsgBox ("You did not enter a date!"), vbCritical, Error 
     GoTo ReTry 
     If Not IsDate(rptdate) Then 
     MsgBox ("You did not enter the correct format!"), vbCritical, Error 
     GoTo ReTry 
     End If 
     Else 
     Range("B8").Value = rptdate 
     End If 
End With 
+1

試試'elseif'代替? – findwindow

+0

你知道究竟在哪裏嗎?遇到問題,如果我通過elseif或第二個替換第一個。 – UnbrokenChain

+0

啊!如果在查看elseif語法之後,我將它添加到第二個。謝謝! – UnbrokenChain

回答

3

您的If語句對此有點偏離。這是一個代碼,它將刪除GoTo(這是最佳實踐)的使用,並且仍然正確循環,直到獲得所需的格式。

Sub tt() 
Dim ws1  As Worksheet 
Set ws1 = Sheets("Report Generation") 

With ws1 
    Dim rptdate As Variant 
    rptdate = InputBox("Please Enter the Report Date *Must be EOM format mm/dd/yyyy*", "Enter Date") 

    Do While rptdate = "" Or Not IsDate(rptdate) 
     MsgBox ("You did not enter a date in the correct format!"), vbCritical, Error 
     rptdate = InputBox("Please Enter the Report Date *Must be EOM format mm/dd/yyyy*", "Enter Date") 
    Loop 

    .Range("B8").Value = rptdate 
End With 
End Sub 
+0

謝謝,我上面發佈的解決方案似乎也可以使用elseif而不是兩個獨立的if語句。 應在用戶輸入格式爲mm/dd/yyyy的日期後添加rpt日期。 – UnbrokenChain

0

以下準確地做我想要的。感謝findwindow。

'Updates the report date located in report generation tab cell B8 
Dim ws1 As Worksheet 
Set ws1 = Sheets("Report Generation") 
ReTry: 
With ws1 
Dim rptdate As Variant 
    rptdate = InputBox("Please Enter the Report Date *Must be EOM format mm/dd/yyyy*", "Enter Date") 
    If rptdate = "" Then 
    MsgBox ("You did not enter a date!"), vbCritical, Error 
    GoTo ReTry 
    ElseIf Not IsDate(rptdate) Then 
    MsgBox ("You did not enter the correct format!"), vbCritical, Error 
    GoTo ReTry 
    Else 
    Range("B8").Value = rptdate 
    End If 
End With 
+1

在我的文章中查看我的編輯,以避免使用'GoTo'(這是VB的最佳實踐)。它也縮短了一點。 – BruceWayne

+0

完美,感謝學習新東西的幫助。 – UnbrokenChain

+1

使用'GoTo'應該保留極少數情況下('On Error GoTo ErrHandler'是一個),在VBA和我所見過的大多數編程語言中。如果你有很多使用'GoTo'的宏,真正值得一讀的是如何通過If/Then',Do While'或Do Do'等循環來避免它們。 (我也意識到我忘了添加'Range「B8」)。Value = rptdate'在我的編輯中,但我已經將它添加到最後)。 – BruceWayne