在Excel VBA中将TextBox中的字符串格式化为TimeValue

ura*_*aba 2 excel vba excel-vba

我在UserForm中有一个TextBox.使用事件_AfterUpdate(),我想使用此代码将格式更新为TimeValue,"hh:mm".

Private Sub TimeTextBox_AfterUpdate()
On Error GoTo ErrorHandler

With TimeTextBox
    .Value = Format(TimeValue(.Value), "hh:mm")
ErrorHandler:
    .Value = Format(TimeValue(Now), "hh:mm")
End With

End Sub
Run Code Online (Sandbox Code Playgroud)

问题是:即使我在框中输入13:13,它也总会失败.我该如何解决这个问题?

Dic*_*ika 5

正如@MatthewD评论的那样,您通过更新update事件中的文本框来创建无限循环.最终VBA退出循环,所以它不是无限的.你不断获得当前时间,因为你没有Exit Sub在你之前ErrorHandler:.错误处理标签下的代码会在100%的时间内执行.

如果您Exit Sub在上面的行上面,ErrorHandler:那么只有在出现错误时才会执行下面的代码.

但是,我会提出一个不同的方式.

Private mbEventsDisabled As Boolean

Private Sub TimeTextBox_AfterUpdate()

    Dim dtTime As Date

    'See if you can convert the text into a time
    On Error Resume Next
        dtTime = TimeValue(Me.TimeTextBox.Value)
    On Error GoTo 0

    'if you can't, the variable will be zero and you set
    'it to the current time
    If dtTime = 0 Then dtTime = Now

    'To prevent recursive calling, see if you've disabled events
    If Not mbEventsDisabled Then

        'disable events so you can update the textbox
        mbEventsDisabled = True

        'now this line will trigger AfterUpdate again, but it won't
        'execute this if block because of the variable
        Me.TimeTextBox.Value = Format(dtTime, "hh:mm")

        'now re-enable events
        mbEventsDisabled = False
    End If

End Sub
Run Code Online (Sandbox Code Playgroud)

您无法在用户表单中禁用事件Application.EnableEvents,因此您必须自己执行此操作.我创建了一个模块级变量mbEventsDisabled,它将跟踪事件是否已启用(模块级变量在模块的声明部分中声明,在任何过程之外和之上).最好将此变量命名为否定因为布尔变量默认为False,除非您另外设置,否则您希望disabled = false.

我只是在一个地方更新它,而不是更新主代码和错误处理程序中的文本框.它让我认为代码更清晰.