UserForm ComboBox с доступным для поиска списком, чтобы не выбирать первый элемент с keyDown - PullRequest
0 голосов
/ 21 мая 2019

Фон

У меня есть пользовательская форма с ComboBox (ComboBox1), которая включает в себя список для поиска (благодаря коду). Тем не менее, когда я использую кнопку «вниз», он просто выбирает первый элемент и избавляется от остальной части списка, который был там первым (как если бы он в основном помещал первый элемент в качестве искомого имени).

Я обнаружил очень похожий вопрос о переполнении стека, но решение не полностью помогло мне.

Вот ссылка: Как использовать событие сочетания клавиш без выбора элемента в списке

Код для моей пользовательской формы приведен ниже:

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

Однако, когда я что-то ввожу (скажем, я ввожу «Приложение», чтобы найти «Яблочное пюре», а в раскрывающемся списке отображаются «Яблоко» и «Яблочное пюре») и нажимаю кнопку «Вниз», он просто переходит к первому элементу и больше не двигается. Список не исчезает, а просто застревает на первом предмете.

Кто-нибудь знает, что мне нужно изменить в моем коде, чтобы он работал? (Или какие-нибудь другие идеи о том, как заставить это работать вообще)?

GIF для уточнения: KeyDown не перемещается за первый элемент

...