将 hhmmAM/PM(无空格)格式化为 HH:MM AM/PM,如果没有输入时间,则将单元格留空



我的问题与 2014 年的问题有关:"如何在 excel 中将 hhmmAM/PM(无空格)格式化为时间 hh:mm AM/PM?

Gary's Student建议的代码确实有效。但是,如果在目标单元格中没有输入时间,则代码将输入":PM"并导致 #VALUE!包含工作簿中其他位置的计算的单元格中的错误。

我可以在下面的代码中添加一些东西来说明 Target.Value = ": PM" 是否将其留空?谢谢。

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

结束子

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 Trim(s) <> "" Then
        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
    End If
Application.EnableEvents = True
End Sub

现在,它只会在有文本的情况下更改单元格。

把它扔到Application.EnableEvents = False line之前

if Len(Trim(Target.text))=0 then exit sub

或使用 将其添加到相交线。

相关内容

最新更新