VBA_Combobox can not show the list

时间:2016-10-20 13:19:06

标签: vba excel-vba combobox userform excel

I've made a ComboBox to choose the name of students. But when I click the triangle button to show the list of names, the area to choose is empty:

enter image description here

But when I tap some letters, the list shows up :

And the list keep adding the names, so it becomes longer and longer.

Here is the code:

Private Sub ComboBox1_Change()

Dim MyArray As Variant
Dim Ctr As Integer
Dim listvar As Variant

MyArray = Array("Denis", "Daniel", "Jimmy", "David", "Eric")
For Ctr = LBound(MyArray) To UBound(MyArray)
    UserForm1.ComboBox1.AddItem MyArray(Ctr)
Next

listvar = ComboBox1.List

On Error Resume Next
If IsError(WorksheetFunction.Match(ComboBox1.Value, listvar, 0)) Then

    ComboBox1.AddItem ComboBox1.Value
End If

Operateur = ComboBox1.Text
UserForm1.Show

End Sub

Besides, when I enter a new name like Mary, the list will remember every letter that I've tapped, like M, Ma, Mar, Mary.

So I just want when I click the triangle button, it can show me the names to choose, and when I write a new name, it can put it in the list the following times (without repeating names). Thank you!

1 个答案:

答案 0 :(得分:1)

You need to add values to combobox earlier, when UserForm is displaying with Initialize event of UserForm but not with Change event of ComboBox. Try something like this:

Private Sub UserForm_Initialize()

Dim MyArray As Variant
Dim Ctr As Integer
Dim listvar As Variant

MyArray = Array("Denis", "Daniel", "Jimmy", "David", "Eric")
For Ctr = LBound(MyArray) To UBound(MyArray)
    UserForm1.ComboBox1.AddItem MyArray(Ctr)
Next

End Sub

End remove this section from your ComboBox1_Change() event.


Edit, simple example of how to use KeyDown event working with Enter button:

Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
        Me.ComboBox1.AddItem Me.ComboBox1.Value

    End If
End Sub