首页 文章

如何使用combobox keydown事件而不选择列出的项目

提问于
浏览
0

我的Excel VBA项目中有一个组合框,它使用一系列单元格作为项目列表 . 我在其中使用了一个过滤器,因此无论何时输入值,列表都会缩小到包含该字符串的项目,并显示下拉列表 . 但是,出现问题,当显示下拉列表时,导航键不能用于在项目中滚动 . 按下向下键后,下拉列表将再次被过滤 .

我猜它正在发生,因为在关注项目的同时关键,也在选择它 . 因此,会自动调用combobox_change事件 .

有没有办法让我可以自动停止keydown事件选择一个项目,但只能滚动它们?

1 回答

  • 2

    编辑答案:

    现在已经构建了我自己的工作表并使用了这些想法,具有讽刺意味的是 Application.EnableEnable 仅在某些情况下有所帮助,因为 Combobox_Change() 事件仍然会在事件被禁用的情况下触发(或者至少似乎是这种情况) . 我发现的基本思想涉及操纵 KeyCodes 并设置标志 . 我下面的例子涉及使用一个名为 TempComboComboBox 并在VBA中的 TempCombo_KeyDown() 事件之后运行代码(为了示例目的,我已经修剪了我的东西):

    Option Explicit
    Dim Abort as Boolean
    
    Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        Select Case KeyCode
            Case 38  'Up
                If TempCombo.ListIndex <= 0 Then KeyCode = 0 'ignore "Up" press if already on the first selection, or if not on a selection
                Abort = True
                If Not KeyCode = 0 Then ' If on a selection past the first entry
                    KeyCode = 0
                'Manually choose next entry, cancel key press
                    TempCombo.ListIndex = TempCombo.ListIndex - 1
                End If
                Me.TempCombo.DropDown
            Case 40 'Down
                If TempCombo.ListIndex = TempCombo.ListCount - 1 Then Keycode = 0 
            ' This method was from the discussion I linked, prevents "falling off the bottom of the list"
                Abort = True
                If Not KeyCode = 0 Then ' If on a selection before the last entry
                    KeyCode = 0
                'Manually choose next entry, cancel key press
                    TempCombo.ListIndex = TempCombo.ListIndex + 1
                End If
                Me.TempCombo.DropDown
        End Select
        Abort = False
    End Sub
    
    Private Sub TempCombo_Change()
        If Abort Then Exit Sub ' Stop Event code if flag set
        Abort = True
        ' sets the flag until finished with commands to prevent changes made by code triggering the event multiple times
    
        ' ~~~ Insert Code you want to run for other cases here ~~~
    
        Abort = False
    End Sub
    

    我使用 Abort 变量作为 TempCombo_Change() 中的标志来防止事件代码的多次触发,并允许键不更改链接单元格的文本结果,从而阻止我的动态范围更新 . 确保两个子程序都在 ComboBox 所在的工作表上!

    所以这是我为此所做的一个骷髅,如果有人发现问题让我知道,但我希望这可以帮助别人 .


    旧答案我不确定这会有多大帮助,如果我有声誉,我会将其作为评论提交,因为这确实不符合答案 . 但是我遇到了同样的问题,偶然发现了一个尝试回答这个问题的线程 . 我希望微软帮助页面上的代码之一:http://answers.microsoft.com/en-us/office/forum/office_2007-customize/disable-userform-combobox-change-event-when-arrow/ 598b44a1-dcda-4a2c-8e12-2b84762f98ae?db = 5看起来向上和向下箭头的KeyDown事件以及与ComboBox_Change事件配对将允许您隔离它们然后在按下时防止组合框更新然后向下导航列表 . 我建议通过OP的后续帖子查看,它提供了令人难以置信的信息,并帮助我适应我自己的情况 . 另请注意UserForm和常规Excel VBAcode之间的区别,例如UserForm的Me.EnableEvents需要是针对一般excel的Application.EnableEvents!我知道现在已经老了,但如果这有助于任何人,祝你好运!

相关问题