Search 2.0

Thursday, August 23, 2007

Excel VBA: Mask Time Entry in Excel.

Unlike Access, Excel does not allow for us to mask time and/or date entries. However, we can use the Worksheet Change Event to achieve masked time entries. For the code to work times should be entered as 4 digits, e.g. 2244, 0130, 1325 will change to 22:44, 01:30 and 13:25 respectively. Note how the time mask is only applicable to the range A1:A100, but can be any range. You can change the display format (.NumberFormat = "[h]:mm") of the code to suit your needs.

To insert the code, right click on the Sheet name tab, select View Code and in here paste the code below;

Private Sub Worksheet_Change(ByVal Target As Range)
Dim vVal
If Target.Cells.Count > 1 Then Exit Sub
If Intersect(Target, Range("A1:A100")) Is Nothing Then Exit Sub

With Target

vVal = Format(.Value, "0000")
If IsNumeric(vVal) And Len(vVal) = 4 Then
Application.EnableEvents = False
.Value = Left(vVal, 2) & ":" & Right(vVal, 2)
.NumberFormat = "[h]:mm"
End If
End With

Application.EnableEvents = True
End Sub

Come and visit excelfanactics.com

No comments: