在用户表单中检查有效时间

时间:2018-06-28 12:26:06

标签: regex excel vba userform error-checking

我正在尝试在用户窗体中进行错误检查,以检查输入的时间是否是有效的时间表达式(00:00或00 PM),因为我正在通过TimeValue命令将其发送给输出,以便时间标准化。如果输入的值不是有效的表达式,则将显示错误消息,并允许重新输入有效的表达式。我不确定使用Regex是否可以完成此操作,或者是否有更简单的选择。我在下面附加了我的代码。

Private Sub CommandButton_OK_Click()
Dim emptyrow As Long

'Error Check
If NameText.Value = "" Then
    MsgBox "Please Enter Valid Name", vbOKOnly
    Exit Sub
End If

'Make Sheet 1 Active
Sheet1.Activate

'Determine emptyRow
emptyrow = WorksheetFunction.CountA(Range("E:E")) + 1

'Convert Time of Inspection to Time Value
TimeText.Value = TimeValue(TimeText.Value)

'Transfer Info
Cells(emptyrow, 5).Value = DateText.Value
Cells(emptyrow, 6).Value = NameText.Value
Cells(emptyrow, 7).Value = ShiftText.Value
Cells(emptyrow, 8).Value = TimeText.Value

If CornNo.Value = True Then
    Cells(emptyrow, 9).Value = "No"
Else
    Cells(emptyrow, 9).Value = "Yes"
End If

If SurgeNo.Value = True Then
    Cells(emptyrow, 10).Value = "No"
Else
    Cells(emptyrow, 10).Value = "Yes"
End If

If MillNo.Value = True Then
    Cells(emptyrow, 11).Value = "No"
Else
    Cells(emptyrow, 11).Value = "Yes"
End If

If FBedNo.Value = True Then
    Cells(emptyrow, 12).Value = "No"
Else
    Cells(emptyrow, 12).Value = "Yes"
End If

If DDGOutNo.Value = True Then
    Cells(emptyrow, 13).Value = "No"
Else
    Cells(emptyrow, 13).Value = "Yes"
End If

If DDGInNo.Value = True Then
    Cells(emptyrow, 14).Value = "No"
Else
    Cells(emptyrow, 14).Value = "Yes"
End If

Unload Me

End Sub

1 个答案:

答案 0 :(得分:2)

您似乎可能希望使用On Error GoTo Label语句来处理用户错误,我认为这可以完成您想要的事情

    Private Sub CommandButton_OK_Click()

    If nameText.Value = "" Then GoTo InvalidName

    ''  Do some stuff

    On Error GoTo InvalidTime
    Let TimeText.Value = TimeValue(TimeText.Value)
    On Error GoTo 0

    ''  Do some more stuff

    Let Cells(emptyrow, 9).Value = IIf(CornNo.Value = True, "No", "Yes")

    ''  Do even more stuff

    Exit Sub

InvalidName:
    MsgBox "Please Enter a Name", vbInformation + vbOKOnly, "Error"
    Exit Sub

InvalidTime:
    MsgBox "Please Enter a Valid Time", vbInformation + vbOKOnly, "Error"
    Exit Sub
End Sub