问题
How can I repopulate a combobox itemlist without affecting what is currently written inside the combobox?
I currently have code that looks kind of like:
Private Sub ComboBox1_DropButtonClick()
Dim v As Variant
Dim selText As String
selText = ComboBox1.selText
Dim i As Integer
For i = 0 To ComboBox1.ListCount - 1
ComboBox1.RemoveItem (0)
Next i
v = Call CreateList()
For i = 0 to Ubound(v)
ComboBox1.AddItem v(i)
Next v
If selText <> "" Then ComboBox1.Text = selText
End Sub
I haven't worked with comboboxes before so there are probably better methods. The code above has several problems
- It changes the selected value of the combobox (before attempting to restore it)
- It triggers the Combobox1_change event
- There are loops that I think might be unnecessary. Is is possible to remove all items without looping and adding multiple items without looping. The items to be added are created from a string that has comma separated values.
I would really appreciate help
回答1:
There are loops that I think might be unnecessary. Is is possible to remove all items without looping and adding multiple items without looping.
ComboBox1.Clear will remove all items without looping. For adding you can use .List after you create the loop to add items to the ComboBox.
Private Sub Sample()
Dim MyAr(1 To 5)
For i = 1 To 5
MyAr(i) = i
Next i
ComboBox1.List = MyAr
End Sub
It triggers the Combobox1_change event
To prevent the Combobox1_change event, you will have to use a boolean variable like This
It changes the selected value of the combobox (before attempting to restore it)
Store the value in a variable and then reset the combobox value if that value is part of the dropdown list
来源:https://stackoverflow.com/questions/30617525/repopulate-a-combobox-itemlist-without-affecting-what-is-currently-written-insid