VBA:如何标记单元格中的输入

时间:2016-03-10 20:52:00

标签: vba time tokenize

我想要做的是将单元格中的时间输入转换为特定格式。例如:

"9" or "9 am" = 9:00:00 AM, which is the same as TIME(9, 0, 0)  
"9 30" = 9:30:00 AM = TIME(9, 30, 0)  
"4 30 pm" = 4:30:00 PM = TIME(16, 30, 0)

如何在VBA中实现这一目标?

只是旁注,这实际上是我第一次尝试VBA。

感谢。

2 个答案:

答案 0 :(得分:2)

我可以支持一些学习:

Function timm(str As String) As Double
Dim spltstr() As String
Dim hr As Integer
Dim min As Integer
Dim sec As Integer
hr = 0
min = 0
sec = 0
str = Replace(str, """", "")
spltstr = Split(str)
hr = spltstr(0)
If UCase(spltstr(UBound(spltstr))) = "PM" Then hr = hr + 12
If 1 <= UBound(spltstr) Then
    If IsNumeric(spltstr(1)) Then min = spltstr(1)
End If
timm = TimeSerial(hr, min, sec)


End Function

将其放在工作簿附带的模块中。然后可以直接在工作表上或从另一个子句中将其作为函数调用。

它会将文本更改为数字,因此如果将其用作UDF,您仍需要将自定义数字格式应用于单元格。

enter image description here

根据你的评论,你可以使用Worksheet_Change事件。

首先在整个列上使用自定义格式,如hh:mm:ss AM/PM。把它放在工作表代码中。

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo getout
Application.EnableEvents = False
If Not Intersect(Range("A:A"), Target) Is Nothing Then
    If Not IsDate(Target.Value) Then
        Target = timm(Target.Value)
    End If
End If
Application.EnableEvents = True
Exit Sub
getout:
Application.EnableEvents = True
End Sub

它调用先前的代码并返回数字。因此,当您离开编辑模式时,它会将其更改为时间。

答案 1 :(得分:0)

看起来你想要使用Split和TimeSerial。这是一个让你入门的例子。

Public Function ConvertToTime(ByVal Input_ As String) As Date

    Dim vaSplit As Variant
    Dim lHour As Long, lMinute As Long

    'split the string into an array using space as a delimiter
    vaSplit = Split(Input_, Space(1))

    'The first element is the hour
    lHour = vaSplit(0)

    'If there's more than one element, the second element is the minute
    If UBound(vaSplit) > 0 Then lMinute = vaSplit(1)

    'if the last element is "pm", then add 12 to the hour
    If vaSplit(UBound(vaSplit)) = "pm" Then lHour = lHour + 12

    ConvertToTime = TimeSerial(lHour, lMinute, 0)

End Function