Is there a way to turn three and four digit numbers into time codes in VBA?

84 Views Asked by At

I'm creating a workbook that requires a lot of time entry and I want to make data entry faster by allowing the user to type in only the digits of the time and not need to enter the ':'. Basically, if someone types in 315 or 1100 in a cell in the specified range, then I want them to become the times 3:15 and 11:00 respectively. The range of cells in question are already in "Time" format and there is no need to worry about AM or PM. I need this to be a 'type' conversion, not a 'format' conversion. (The only codes I've tried have been way off base, because I'm new and have no idea where the begin on this one)

1

There are 1 best solutions below

1
Dominique On

For anyone that is interested, this is what I came up with for fast time entry:

Dim HourPart As Integer
Dim MinutePart As Integer
If Not Intersect(prevTarget, Range("E8:F52")) Is Nothing Then 'If it's in the time area of the worksheet
'This is to skip the formatting code if the entry is blank or has a formula
If prevTarget.Value = 0 Or prevTarget.Value = "" Then
    Exit Sub
End If
If prevTarget.Value >= 0 And prevTarget.Value < 1 Then 'This is to skip the formatting code if the entry already has a colon (If it already has a colon, then Excel will automatically format it for time and give it a value less than 1)
    If Len(prevTarget) = 4 Then 'This If is to define the minutes to make sure not over 60
        MinutePart = Mid(prevTarget, 3, 2)
    ElseIf Len(prevTarget) = 5 Then
        MinutePart = Mid(prevTarget, 4, 2)
    End If
    If MinutePart >= 60 Then
        MsgBox "Minutes shouldn't be greater than or equal to 60"
    End If
    GoTo ChangeAmPm
ElseIf prevTarget.Value > 100 And prevTarget.Value < 2359 Then 'This is to handle hour and minute time values that are entered without a colon
    HourPart = prevTarget.Value \ 100
    MinutePart = prevTarget - HourPart * 100
    If MinutePart >= 60 Then
        MsgBox "Minutes shouldn't be greater than or equal to 60"
    End If
    prevTarget = HourPart & ":" & MinutePart
ElseIf prevTarget.Value >= 1 And prevTarget.Value <= 12 Then 'This is to handle time code where only an hour is entered and without a colon
    HourPart = prevTarget.Value
    MinutePart = 0
    prevTarget = HourPart & ":"
End If
End If