Using Arrow Keys to Change items in a Combo Box

sujittalukde

Well-known Member
Joined
Jun 2, 2007
Messages
520
I am using the following codes to scroll list items in a list box through arrow keys.
Code:
Private Sub UserForm_Initialize()
    With ComboBox1
        .AddItem "Ahemdabad"
        .AddItem "Bombay"
        .AddItem "Calcutta"
        .AddItem "Delhi"
        .Style = fmStyleDropDownList
        .ListIndex = 0
    End With
End Sub

Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
    Case vbKeyDown
        If ComboBox1.ListIndex <> ComboBox1.ListCount - 1 Then
            '
        Else
            ComboBox1.ListIndex = -1
        End If
    Case vbKeyUp
        If ComboBox1.ListIndex <> 0 Then
            '
        Else
            ComboBox1.ListIndex = ComboBox1.ListCount - 1
        End If
    End Select
End Sub

When I am using the Down arrow key, it is working well ie when the item "Delhi" is reached and then again Down arrow key is pressed, "Ahemdabad" is coming in the combobox.

But when I am using the Up arrow key, problem is coming. When the combobox is displaying the item "Ahemdabad" and Up key is pressed, "Calcutta" is coming instead of "Delhi".

How can I fix it?
 
sujittalukde,

Try adding line in red.......

Rich (BB code):
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
    Case vbKeyDown
        If ComboBox1.ListIndex <> ComboBox1.ListCount - 1 Then
            '
        Else
            ComboBox1.ListIndex = -1
         Exit Sub
         
        End If
    Case vbKeyUp
    
        If ComboBox1.ListIndex <> 0 Then
           '
        Else
        ComboBox1.ListIndex = ComboBox1.ListCount - 1
        KeyCode = 0   '*****************
          
        End If
    End Select
End Sub

Hope that helps.
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top