等到用户停止在ComboBox中键入以运行宏(VBA)

时间:2017-10-04 14:13:19

标签: excel vba excel-vba combobox

我正在编写一种交叉引用数据库。根据选择或创建的文档名称生成ID。

我在标题中提到的ComboBox更改(在3个字母后面),检查数据库中是否输入了类似的条目,并显示匹配的下拉选项。从匹配列表中选择条目或创建新名称后,将生成相应的数字。

由于Dropdown列表是在输入每个字母后生成的,因此输入所需内容需要一段时间。我想在 last 更改后等待几秒钟以运行宏。

关于如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:1)

再次使用Application.OnTime

Userform

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

答案 1 :(得分:0)

这有点棘手,因为VBA不支持多线程。但我们可以使用Application.OnTime事件在将来触发测试,以测试最后一次关键事件是否至少在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
  

注意:
  这是一种有效2秒或更长时间的解决方法。但不会少于2秒。