Textbox automatically format as time and make sure actual time

sharky12345

Well-known Member
Joined
Aug 5, 2010
Messages
3,373
Office Version
  1. 2016
Platform
  1. Windows
I'm using this to format a Textbox as a time value;

Code:
Private Sub txttime_Change()
Dim T As Date

If Len(txttime.Value) = 4 Then
On Error Resume Next
T = TimeSerial(Left(txttime.Value, 2), Right(txttime.Value, 2), 0)
On Error GoTo 0
ElseIf Len(txttime.Value) = 5 Then
On Error Resume Next
T = TimeValue(txttime.Value)
On Error GoTo 0
End If
If T > 0 Then
txttime.Value = Format(T, "hh:mm")
End If
If KeyCode = vbKeyTab Then
End If

End Sub

Is there a way I can make sure that the time that is entered is an actual time and if not get a message prompting to enter a new time?

Also, I want to allow numerical key presses and a backspace so they can clear the box if they want to but no other key presses permitted. At the moment I'm getting an error if I try to clear the Textbox with a backspace.
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.

snb_

Well-known Member
Joined
Nov 9, 2009
Messages
567
Use a combobox as dropdownlist (style=2) containing only valid timevalues.
 
Upvote 0

sharky12345

Well-known Member
Joined
Aug 5, 2010
Messages
3,373
Office Version
  1. 2016
Platform
  1. Windows
Thanks - I want to avoid anything where the user has to click multiple times simply to enter a time and have seen a 'Time Picker' which has a spin button to enter a time, I think that would be quite frustrating if they had to use buttons. However, if there is a way to enter the time quickly using keys and your suggestion then that would be fine.
 
Upvote 0

Forum statistics

Threads
1,191,304
Messages
5,985,891
Members
439,986
Latest member
DaveTee

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top