Home » excel » regex – Check Valid Time in Userform

regex – Check Valid Time in Userform

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to error check in a userform where I want to be able to check that the time that was entered is a valid time expression (00:00 or 00 PM) as I am sending it through a TimeValue command for the output so that the time is standardized. If the value entered is not a valid expression I will have an error message display and allow to reenter a valid expression. I am not sure if this is something I can accomplish with Regex or if there is a simpler option. I have attached my code below.

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
How to&Answers:

It looks like you may want to user error handling with the On Error GoTo Label statement, I think that this will get what you want done

    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