如何限制input框input仅限于date

我想在下面的代码中实现一个控制,只允许使用mm / dd / yyyy格式的date,并防止在input框中input空格。 我已经尝试添加一些代码,但仍然遇到错误。 第一个检查是否是空白的控件,但是第二个如果不是似乎只是被跳过了。

'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 

你的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 

以下准确地做我想要的。 感谢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