excel 有没有办法在VBA中将三位数和四位数转换为时间代码?

wbrvyc0a  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(181)

我正在创建一个需要大量时间输入的工作簿,我希望通过允许用户只键入时间的数字而不需要输入":“来加快数据输入速度。基本上,如果有人在指定范围的单元格中键入315或1100,那么我希望它们分别成为时间3:15和11:00。所讨论的单元格范围已经是“时间”格式,不需要担心AM或PM。我需要这是一个“类型”转换,而不是“格式”转换。(我尝试过的唯一代码都是错误的,因为我是新来的,不知道这个代码从哪里开始)

cx6n0qe3

cx6n0qe31#

对于任何感兴趣的人,这是我想出的快速时间进入:

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

相关问题