背景
我有一个带有ComboBox(ComboBox1
)的UserForm,其中包含可搜索的列表(由于代码)。但是,当我使用向下按钮时,它只是选择了第一项并摆脱了第一项的其余列表(就像基本上将第一项作为搜索名称一样)。
我在堆栈溢出时发现了一个非常相似的问题,但该解决方案对我而言并不完全有效。
以下是链接:How use the combobox keydown event without selecting the listed item
我为用户窗体提供的代码如下:
Dim a()
Private Sub CommandButton2_Click()
End Sub
Private Sub UserForm_Initialize()
a = [Liste].Value
Me.ComboBox1.List = a
End Sub
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Abort As Boolean
Select Case KeyCode
Case 38 'Up
If ComboBox1.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
ComboBox1.ListIndex = ComboBox.ListIndex - 1
End If
Me.ComboBox1.DropDown
Case 40 'Down
If ComboBox1.ListIndex = ComboBox1.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
ComboBox1.ListIndex = ComboBox1.ListIndex + 1
End If
Me.ComboBox1.DropDown
End Select
Abort = False
End Sub
Private Sub ComboBox1_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
Set d1 = CreateObject("Scripting.Dictionary")
tmp = UCase(Me.ComboBox1) & "*"
For Each c In a
If UCase(c) Like tmp Then d1(c) = ""
Next c
Me.ComboBox1.List = d1.keys
Me.ComboBox1.DropDown
Abort = False
End Sub
Private Sub CommandButton1_Click()
ActiveCell = Me.ComboBox1
Unload Me
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
显然试图阻止comboBox选择第一个项目的特定部分是这样的:
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Abort As Boolean
Select Case KeyCode
Case 38 'Up
If ComboBox1.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
ComboBox1.ListIndex = ComboBox.ListIndex - 1
End If
Me.ComboBox1.DropDown
Case 40 'Down
If ComboBox1.ListIndex = ComboBox1.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
ComboBox1.ListIndex = ComboBox1.ListIndex + 1
End If
Me.ComboBox1.DropDown
End Select
Abort = False
End Sub
但是,当我输入某些内容时(假设我输入“ App”以找到“ Applesauce”,并且下拉列表同时显示了“ Apple”和“ Applesauce”),然后单击向下按钮,它会转到第一项并不再移动。列表并没有消失,只是停留在第一项上。
有人知道我需要在代码中进行哪些更改才能使其正常工作吗? (或其他有关如何使其整体运行的想法)?
GIF进行说明: KeyDown not moving beyong first item