Pra*_*osh 2 excel vba combobox keydown drop-down-menu
我的 Excel VBA 项目中有一个组合框,它使用一系列单元格作为项目列表。我在其中使用了一个过滤器,这样每当输入一个值时,列表就会缩小到包含该字符串的项目,并显示下拉列表。但是,问题出现了,当显示下拉菜单时,导航键无法用于在项目内滚动。一旦按下向下键,下拉列表将再次被过滤。
我猜它的发生是因为向下键在关注项目的同时也选择了它。因此,combobox_change 事件会被自动调用。
有没有办法让我可以停止 keydown 事件自动选择一个项目,但只滚动它们?
编辑后的答案:
现在,我已经构建了自己的工作表并使用了这些想法,具有讽刺意味的是,Application.EnableEvents它只在某些情况下有帮助,因为Combobox_Change()事件在禁用事件的情况下仍然会触发(或者至少看起来是这样)。我发现的基本思想涉及操纵KeyCodes和设置标志。我下面的示例涉及在工作表的 VBA 内的事件之后使用ComboBox调用TempCombo和运行的代码(出于示例目的,我已修剪了我的内容):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
Run Code Online (Sandbox Code Playgroud)
我使用该Abort变量作为标志来TempCombo_Change()防止事件代码的多次触发,并允许按键不更改链接单元格的文本结果,从而防止我的动态范围更新。确保两个子例程都位于工作表上ComboBox!
这就是我为此所做的工作的框架,如果有人发现问题请告诉我,但我希望这可以帮助别人。
旧答案
我不确定这会真正有多大帮助,如果我有声誉,我只会将其作为评论提交,因为这确实不符合答案。然而,我有同样的问题,并偶然发现了一个试图回答这个问题的线程。我希望 Microsoft 帮助页面之一上的代码之一: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的后续帖子,它提供了令人难以置信的信息,并帮助我适应了自己的情况。另请注意与通用 Excel VBA 代码之间的差异
UserForm,例如Me.EnableEventsforUserForm需要用于Application.EnableEvents通用 Excel!我知道这现在已经过时了,但如果这对任何人有帮助,祝你好运!
| 归档时间: |
|
| 查看次数: |
7080 次 |
| 最近记录: |