在Excel VBA中从TextBox到TimeValue的格式string

我有一个用户窗体中的文本框。 使用事件_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 

问题:即使我在框中input13:13,它总是会失败。 我如何解决这个问题?

正如@MatthewD所评论的那样,通过更新更新事件中的文本框来创build一个无限循环。 最终VBA退出循环,所以它不是无限的。 由于在ErrorHandler:之前没有Exit Sub所以你不断得到当前时间ErrorHandler: 。 error handling标签下的代码在100%的时间内执行。

如果你把Exit Sub放在ErrorHandler:的上面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 

您不能使用Application.EnableEvents禁用用户窗体中的事件,所以您必须自己动手。 我创build了一个名为mbEventsDisabled的模块级variables,用于跟踪是否启用事件(模块级variables在模块的声明部分中,在任何程序之外和之上声明)。 最好将这个variables命名为否定的,因为默认情况下,布尔variables将为False,并且您希望disable = false,除非您另行设置。

而不是更新主代码和error handling程序中的文本框,我只是在一个地方更新它。 它使我认为的代码更清洁。