1

I have code that moves a time entered value to a field using a specific time format. However, when entering the time, if it isn't entered in the correct format, the user gets the Runtime 13 error and then cannot do anything other than close the userform, stop the code from running, and try again. I can format a message to return an error telling the user to correct the entry but what code do I use to put the user back into the field and allow them to make a correction? I am putting the code for this userform textbox here for reference:

Private Sub txtDepartTime_AfterUpdate()
'When time is entered, time transfers immediately to spreadsheet datafield.

Dim TargetRow As Integer
TargetRow = Sheets("Codes").Range("D43").Value + 1

With Sheets("Travel Expense Voucher").Range("Data_Start").Offset(TargetRow, 25)
 .Value = TimeValue(txtDepartTime)
 .NumberFormat = "hh:mm" 'departure time

 End With

End Sub

1 Answer 1

1

Start by testing whether txtDepartTime can be converted to a time. If it can't, then notify the user and exit execution, so that they can re-enter the time.

Private Sub txtDepartTime_AfterUpdate()
'When time is entered, time transfers immediately to spreadsheet datafield.

Dim TargetRow As Integer, TestTime As Date

On Error Resume Next
TestTime = TimeValue(txtDepartTime)
On Error GoTo 0

If TestTime = 0 Then
    MsgBox "Time entered is not valid. Please try again.", vbExclamation
    Exit Sub
End If

TargetRow = Sheets("Codes").Range("D43").Value + 1

With Sheets("Travel Expense Voucher").Range("Data_Start").Offset(TargetRow, 25)
    .Value = TimeValue(txtDepartTime)
    .NumberFormat = "hh:mm" 'departure time
End With

End Sub

(This solution assumes no one will intentionally enter 12am or 00:00 as the time)

4
  • 1
    Side note: Long should be used instead of Integer to avoid a potential Overflow error. There is no benefit here and only potential problems from using an Integer. Worth pointing out.
    – BigBen
    Commented Jan 17, 2020 at 3:56
  • Thank you, Michael and Big Ben, l'm not getting the error anymore but I'm also not getting the message box nor is an invalid time requiring me to make a change?
    – Kristen
    Commented Jan 18, 2020 at 1:58
  • Sorry, I created the test incorrectly. I've updated it to use TimeValue instead of DateValue. Can you please try again?
    – Michael
    Commented Jan 19, 2020 at 22:33
  • Perfect! :) Thank you so much, Michael. I feel like I learn something new every time I have a response from you!
    – Kristen
    Commented Jan 20, 2020 at 1:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.