VBA高级输入框日期

时间:2017-02-16 20:25:11

标签: vba excel-vba excel

我的代码工作得非常好,但是,我发现当用户输入dd / mm / yy时,如果不应该接受它,如果用户没有输入mm / dd / yyyy,我该如何捕获用户。

Dim LastReportDate As String
Dim StartDate As String


reTry:


LastReportDate = InputBox("Insert date in format mm/dd/yyyy", "Date Range Validated:", Format(Now(), "mm/dd/yyyy"))

'User Presses "Cancel"
If StrPtr(LastReportDate) = 0 Then MsgBox "Cancel button pressed, Data Range Validated - Range (B3) will be blank.", vbCritical, "User Cancelled Date Entry": Exit Sub

'If user does not enter anthying restart at 0
If LastReportDate = vbNullString And StrPtr(LastReportDate) > 0 Then MsgBox "You entered no string": GoTo reTry

'If user did enter a date, then go validate it
If LastReportDate <> vbNullString Then: GoTo ValidateDateFormat


ValidateDateFormat:
    'User Entered a Valid Date
If IsDate(LastReportDate) Then

     'Put start date - end date in B3
     'Note start date = -6 days: Data Range Validation is one week
ThisWorkbook.Worksheets(1).cells(3, 2).Value = DateAdd("d", -6, LastReportDate) & " - " & LastReportDate
     'If user entered wrong date format then go to 0
Else
MsgBox "Wrong Date Format": GoTo reTry
End If

1 个答案:

答案 0 :(得分:0)

Dim LastReportDate As String
Dim StartDate As String

reTry:

LastReportDate = InputBox("Insert date in format mm/dd/yyyy", "Date Range Validated:", Format(Now(), "mm/dd/yyyy"))

'User Presses "Cancel"
If StrPtr(LastReportDate) = 0 Then MsgBox "Cancel button pressed, Data Range Validated - Range (B3) will be blank.", vbCritical, "User Cancelled Date Entry": Exit Sub

'If user does not enter anthying restart at 0
If LastReportDate = vbNullString And StrPtr(LastReportDate) > 0 Then MsgBox "You entered no string": GoTo reTry

'If user did enter a date, then go validate it
If LastReportDate <> vbNullString Then: GoTo ValidateDateFormat


ValidateDateFormat:

'Trap user if the user did not enter the required format
'Thanks @cyboashu
If Format(LastReportDate, "mm/dd/yyyy") <> LastReportDate Then
MsgBox "Wrong Date Format": GoTo reTry

'User Entered a Valid Date
ElseIf IsDate(LastReportDate) Then

     'Put start date - end date in B3
     'Note start date = -6 days: Data Range Validation is one week
ThisWorkbook.Worksheets(1).cells(3, 2).Value = DateAdd("d", -6, LastReportDate) & " - " & LastReportDate
     'If user entered wrong date format then go to 0
Else
End If

MsgBox "CFR Macro Completed.", vbInformation + vbOKOnly, "Macro Status: Successful"
ThisWorkbook.Worksheets(1).Range("B4") = Format(Now, "mm/dd/yyyy")
ThisWorkbook.Worksheets(1).Range("B2").Select