Excel VBA Textbox time validation to [h]:mm

泪湿孤枕 提交于 2019-12-12 12:21:31

问题


I am developing a VBA Excel Userform and need to enter a time in the [h]:mm format. This means that the hours can be unlimited and does not cycle back to 0 after 23:59 like the hh:mm format does. I have searched the web to no avail.

Here is the code I'm currently using:

Private Sub Txtbx_TimeAvailable_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Me.Txtbx_TimeAvailable.Value <> Format(Me.Txtbx_TimeAvailable.Value, "[h]:mm") Then
        MsgBox "Please enter correct time format in hh:mm"
        Cancel = True
        Me.Txtbx_TimeAvailable.Value = vbNullString
    Else
        ThisWorkbook.Sheets(SELECTEDWORKSHEET).Range("C60").Value = Txtbx_TimeAvailable.Text
        Call UpdateDentistMainForm
    End If

End Sub

However, when using this code if I enter 25:53 it converts it to 01:53. I'd appreciate any help I could get on this.


回答1:


You will need to parse the validity manually, here is one way:

Var = "59:59"

Dim IsValid As Boolean
Dim tok() As String: tok = Split(Var, ":")

If (UBound(tok) = 1) Then
    '// `like` to prevent lead +/-
    IsValid = tok(0) Like "#*" And IsNumeric(tok(0)) And tok(1) Like "#*" And IsNumeric(tok(1)) And tok(1) < 60
    '// optionally normalize by removing any lead 0
    Var = Val(tok(0)) & ":" & Val(tok(1))
End If

Debug.Print Var, IsValid


来源:https://stackoverflow.com/questions/36719179/excel-vba-textbox-time-validation-to-hmm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!