等到用户停止键入ComboBox运行macros(VBA)

我正在编写一个交叉引用数据库。 根据select或创build的文档名称生成ID。

标题中提到的ComboBox在更改(3个字母后)时会执行,检查数据库是否有类似的条目,并显示与之匹配的下拉选项。 从匹配列表中选取一个条目或创build一个新名称 – 生成相应的编号。

由于DropDown列表是在每个字母input后生成的,因此需要一段时间才能input所需内容。 我想在最后一次更改后等待几秒钟来运行macros。

任何想法,我怎么能做到这一点?

这有点棘手,因为VBA不支持multithreading。 但是我们可以使用Application.OnTime事件来触发未来的testing,以testing最后一个关键事件是否至less在3秒之前。

模块插入:

 Option Explicit Public LastKeyEvent As Date Public Const WaitTimeValue As String = "00:00:03" 'test for key event in 3 seconds Public Sub TestKeyEvent() 'test if last key event is at least 3 seconds ago. 'If so: run your search or message box 'If not: do nothing If LastKeyEvent <> 0 And LastKeyEvent + TimeValue(WaitTimeValue) <= Now Then LastKeyEvent = 0 'Ensure this is only triggered once: 'If we don't do this and multiple keys are pressed within 1 second 'then it would run multiple times. MsgBox "3 seconds without keypress, we can start search" 'start your search here (instead of message box) … End If End Sub 

现在你可以使用你的文本框更改事件,例如TextBox1

 Private Sub TextBox1_Change() Dim alertTime As Date LastKeyEvent = Now 'remember when the last key event was alertTime = LastKeyEvent + TimeValue(WaitTimeValue) Application.OnTime alertTime, "TestKeyEvent" 'run TestKeyEvent in 3 seconds End Sub 

注意:
这是一个解决scheme,可以工作2秒或更长时间。 但不less于2秒。

另一种方法是再次使用Application.OnTime

在用户窗体中

 Private Sub ComboBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) StartTimer End Sub 

模块中

 Public RunTime As Double Public Sub StartTimer() On Error Resume Next Application.OnTime EarliestTime:=RunTime, Procedure:="YourCode", Schedule:=False RunTime = Now() + TimeValue("00:00:03") Application.OnTime RunTime, "YourCode" End Sub Public Sub YourCode() MsgBox "It's working!" End Sub