我正在努力为工资单输入时间表。我希望以hhmmAM / PM格式输入时间,没有空格或冒号,最好只输入/ p而不是AM / PM,并将其转换为带冒号和空格的标准时间格式。
我搜索了这个社区,找到了一个让我大部分时间都能回答的答案。唯一的问题是,此代码在输入小时时需要使用“0”示例“0545p”转换为“5:45 PM”但“545p”转换为“54:5 PM”
我希望能够输入0545p或545p,仍然可以在下午5:45
以下是我正在使用的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
Application.EnableEvents = False
s = Target.Text
If Right(s, 1) = "a" Or Right(s, 1) = "A" Then
s2 = " AM"
Else
s2 = " PM"
End If
Target.Value = Left(s, 2) & ":" & Mid(s, 3, 2) & s2
Application.EnableEvents = True
End Sub
来源问题:How can I format an hhmmAM/PM (no space) to time hh:mm AM/PM in excel?
感谢您的时间。
答案 0 :(得分:0)
这是我的答案......希望这有帮助...
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
'Remarks:
'if you want to use another column for your code just to change this
'Range("A:A") to the desire column
'if you want the imput column G then
'Range("G:G") and the new resulting line of code will be
'If Intersect(Target, Range("G:G")) Is Nothing Then Exit Sub
Application.EnableEvents = False
s = Target.Text
If Right(s, 1) = "a" Or Right(s, 1) = "A" Then
s2 = " AM"
Else
s2 = " PM"
End If
If Left(s, 2) = "11" Or Left(s, 2) = "12" Or Left(s, 2) = "10" Then
Target.Value = Left(s, 2) & ":" & Mid(s, 3, 2) & s2
End If
If Left(s, 1) = "0" Then
Target.Value = Left(s, 2) & ":" & Mid(s, 3, 2) & s2
End If
If Len(s) = 4 Then
Target.Value = Left(s, 1) & ":" & Mid(s, 2, 2) & s2
End If
'the minutes inside the input (545p | 0545p | 500p)
'always need to be with 2 digits otherwise will return
'other hour or smonthing like this 54:5 PM then... the formta input is:
'hmmA/P
'hhmmA/P
'if you want to use 24H format would need another implementation
Application.EnableEvents = True
End Sub
告诉我你是否还需要更多东西。