Excel-使用箭头键(上/下)在“组合框”下拉列表中移动

时间:2018-10-19 18:15:17

标签: excel vba excel-vba combobox

我创建了一个组合框,以帮助用户键入他要查找的项目的正确名称。 该组合框将建议用户可以选择的可能值。我通过使用本指南(https://trumpexcel.com/excel-drop-down-list-with-search-suggestions/)来完成此组合框

我发现的唯一问题是,选择值的唯一方法是键入每个字母或在下拉列表中使用鼠标单击,但是我想允许用户使用箭头键在列表中移动。

如果用户使用箭头键,则使用该组合框,它将在下拉列表中选择第一个值,从而删除所有其他匹配项。Exemple of the problem

我想要的是在使用箭头键时不会选择该值,而是滚动列表直到找到所需的东西。

我四处张望,发现有些人遇到相同的问题,但没有一个人能帮助我,这就是为什么我在这里试图找到答案。

1 个答案:

答案 0 :(得分:0)

此功能在ms Access vba中起作用。不确定excel vba的必要更改。希望对您有所帮助。

n.b。字节链接代码有错误(至少对于ms access vba),我在此处发布了与更正相同的代码。

Public Sub ArrowKeys(ByRef KeyCode As Integer, combo As ComboBox, ByRef Flag As Boolean)
' flag is used to be able to toggle normal action in combo_change()
Select Case KeyCode
    Case vbKeyDown
        KeyCode = 0 ' make sure the action wont be duplicated
        If combo.ListIndex <> combo.ListCount - 1 Then
          combo.Value = combo.ItemData(combo.ListIndex + 1)
          Flag = True
          combo.Dropdown
        Else
          combo.Value = combo.ItemData(0)
          Flag = True
          combo.Dropdown
        End If
   
   Case vbKeyUp
        KeyCode = 0 ' make sure the action wont be duplicated
        If combo.ListIndex = -1 Then ' In case nothingg is selected yet (-1 index)
          combo.Value = combo.ItemData(combo.ListCount - 1)
          combo.Dropdown
        ElseIf combo.ListIndex <> 0 Then
          combo.Value = combo.ItemData(combo.ListIndex - 1)
          Flag = True
          combo.Dropdown
        Else
          combo.Value = combo.ItemData(combo.ListCount - 1)
          Flag = True
          combo.Dropdown
        End If
End Select
End Sub