Home > Software design >  Is it possible to give an item in a combobox an ID or key?
Is it possible to give an item in a combobox an ID or key?

Time:03-29

I've created a Userform, where I have a combobox and a textbox. My goal is after clicking on an element in the combo box it then shows the key, id or whatever was assigned.

This is how far I come:

 Private Sub UserForm_Initialize()
  With ComboBox1
     .AddItem "Item1", A
     .AddItem "Item2", B
     .AddItem "Item3", C
  End With
End Sub


  Private Sub ComboBox1_Change()
    Me.TextBox1.Value = Me.ComboBox1.ListIndex
  End Sub

This code works, but instead of letters I get numeric values from 0 upwards. I know this is due to the listindex property. But there must be a way to get letters correctly so that if I select Item1 in the ComboBox the letter A in the TextBox should pop up, if select Item2 then B should pop up and so on.

CodePudding user response:

Define your ListValues like below

Option Explicit

Private Sub UserForm_Initialize()
    Dim ListValues(2, 1) As Variant
    ListValues(0, 0) = "Item1"
    ListValues(0, 1) = "A"
    
    ListValues(1, 0) = "Item2"
    ListValues(1, 1) = "B"
    
    ListValues(2, 0) = "Item3"
    ListValues(2, 1) = "C"
    
    With ComboBox1
        .List = ListValues
    End With
End Sub


Private Sub ComboBox1_Change()
    Me.TextBox1.Value = Me.ComboBox1.List(Me.ComboBox1.ListIndex, 1)
End Sub

enter image description here

  • Related