如何限制输入框输入仅限日期
我想在下面的代码中实现一个控件,只允许带有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
您的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
谢谢,我上面发布的解决方案似乎也可以使用elseif而不是两个独立的if语句。 应在用户输入格式为mm/dd/yyyy的日期后添加rpt日期。 – UnbrokenChain
以下准确地做我想要的。感谢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
在我的文章中查看我的编辑,以避免使用'GoTo'(这是VB的最佳实践)。它也缩短了一点。 – BruceWayne
完美,感谢学习新东西的帮助。 – UnbrokenChain
使用'GoTo'应该保留极少数情况下('On Error GoTo ErrHandler'是一个),在VBA和我所见过的大多数编程语言中。如果你有很多使用'GoTo'的宏,真正值得一读的是如何通过If/Then',Do While'或Do Do'等循环来避免它们。 (我也意识到我忘了添加'Range“B8”)。Value = rptdate'在我的编辑中,但我已经将它添加到最后)。 – BruceWayne
试试'elseif'代替? – findwindow
你知道究竟在哪里吗?遇到问题,如果我通过elseif或第二个替换第一个。 – UnbrokenChain
啊!如果在查看elseif语法之后,我将它添加到第二个。谢谢! – UnbrokenChain