Forum Discussion

JonathanSantos's avatar
JonathanSantos
Copper Contributor
Jul 18, 2022

VBA multiple codes

Hi Everyone,

 

I have two different codes I would like to use in the same sheet/cell, is there a way I can put both together on VBA or make one better code?

 

First code converts hhmm into hh:mm am/pm  ex: 1500 = 03:00 PM

Second code converts h am/pm into hh:mm am/pm ex: 5p = 05:00 PM

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("a:a")) Is Nothing Then Exit Sub
Dim xHour As String
Dim xMinute As String
Dim xWord As String
Application.EnableEvents = False
xWord = Format(Target.Value, "0000")
xHour = Left(xWord, 2)
xMinute = Right(xWord, 2)
On Error Resume Next
Target.Value = TimeValue(xHour & ":" & xMinute)
On Error Resume Next
Application.EnableEvents = True
End Sub


Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    Dim h As Long
    If Not Intersect(Range("a:a"), Target) Is Nothing Then
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        For Each rng In Intersect(Range("a:a"), Target)
            h = Val(rng.Value)
            If h >= 1 And h <= 12 Then
                If h = 12 Then h = 0
                If rng.Value Like "*a" Then
                    rng.Value = TimeSerial(h, 0, 0)
                ElseIf rng.Value Like "*p" Then
                    rng.Value = TimeSerial(h + 12, 0, 0)
                End If
            End If
        Next rng
        Application.EnableEvents = True
        Application.ScreenUpdating = True
    End If
End Sub

Resources