Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to give an item in a combobox an ID or key?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading