gpt4 book ai didi

excel - 在 Excel VBA 中将文本框中的字符串格式化为 TimeValue

转载 作者:行者123 更新时间:2023-12-03 00:58:38 27 4
gpt4 key购买 nike

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

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

最佳答案

正如 @MatthewD 评论的那样,您通过更新更新事件内的文本框来创建无限循环。最终 VBA 停止循环,因此它并不是无限的。您不断获取当前时间是因为您在 ErrorHandler: 之前没有 Exit Sub。错误处理标签下的代码 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

您无法使用 Application.EnableEvents 禁用用户窗体中的事件,因此您必须自己执行此操作。我创建了一个名为 mbEventsDisabled 的模块级变量,它将跟踪是否启用了事件(模块级变量在模块的声明部分中声明,位于任何过程的外部和之上)。最好以负数命名该变量,因为 bool 变量默认为 False,并且除非您进行其他设置,否则您希望禁用 = false。

我没有更新主代码和错误处理程序中的文本框,而是只在一处更新它。我认为它使代码更清晰。

关于excel - 在 Excel VBA 中将文本框中的字符串格式化为 TimeValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31564494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com