VBA Excel TimeValue()输入可能性

VBA Excel TimeValue() input possibilities

新在这里。阅读了很多主题,但实际上无法弄清楚。
我正在将字符串从用户窗体文本框转换为代表时间的双精度型。当前代码效果很好:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
On Error Resume Next
With textbox_inMyUserform
TimeValue(.Value)
    If Err.Number <> 0 Then
        startingTime = CDbl(.Value)
        Err.Clear
        On Error GoTo 0
    Else
        On Error GoTo 0
        startingTime = 24 * TimeValue(.Value)
    End If
End With

TimeValue(.value)检查格式是否正确。没有错误意味着在else中使用了该函数,错误使if运行正常的Cdbl(.value)。

效果很好,除了...小数点显然不会触发错误。由于时间值错误," 5"变为5,由于时间值没有错误," 5:30"变为5,5,但" 5.5"和" 5,5"不会触发错误,从而导致结果分别为5.0833333和0 TimeValue(.value)。我希望这些字符串有错误吗?

我现在的解决方案是不使用小数,但我不知道出什么问题。

谢谢。

更新
因此,根据Slai的回答,我开始使用它。显然,VBA中的TimeValue()和Excel内部的TIMEVALUE()行为不同。我也把我最初计划的'if not IsError()'放回去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
With textbox_starttijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value &""")")) Then
        startingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        startingTime = CDbl(.Value)
    Else
        startingTime = 0
    End If
End With
With textbox_eindtijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value &""")")) Then
        endingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        endingTime = CDbl(.Value)
    Else
        endingTime = 0
    End If
End With
totalTime = endingTime - startingTime

更新2
最好还是将此代码保持最新状态:用户窗体中的空文本框在" CDbl(.value)"处引发错误,因此我使用ElseIf更新了上面的代码,以检查vbNullString,而Else将我的时间设置为0,因此现在字符串永远不会为空。


您可能可以改用Excel TIMEVALUE函数:

1
2
3
4
For Each s In Split("5:30 5.5 5,5 5 a")
    v = Evaluate("TIMEVALUE(""" & s &""")")
    Debug.Print s, IsNumeric(s), IsError(v), VarType(v), TypeName(v), v
Next

导致:

1
2
3
4
5
6
s             IsNumeric(s)  IsError(v)    VarType(v)    TypeName(v)   v
5:30          False         False          5            Double         0.229166666666667
5.5           True          True           10           Error         Error 2015
5,5           True          True           10           Error         Error 2015
5             True          True           10           Error         Error 2015
a             False         True           10           Error         Error 2015


TimeValue函数尝试将字符串转换为日期和时间字段。它的工作方式类似于Excel本身。将单元格格式设置为time并尝试不同的值:Excel将尝试将值解释为日期/时间。例如," 5.5"表示为5月5日,并且TimeValue仅读取时间部分,则返回0。

您可以强制用户以hh:mm的形式输入时间并手动检查输入(通过regEx等),也可以将输入字段更改为DateTime选择器。在Excel <= 2010上,您可能必须首先选择以下选项:右键单击"工具箱"窗口,选择"其他控件...",然后搜索" Microsoft日期和时间选择器控件"。但是,如果您使用的是高于2010的Excel,则不再安装该软件,这可能会有所帮助: Excel VBA宏-日期/时间选择器