简体   繁体   中英

Select value from dropdown box but populate hidden column

I have a set of unique IDs and names:

ID   NAME
aa   Jeff
bb   Matt
cc   Trung
dd   Trung

All IDs are unique. Names are not.

On a worksheet I have a series of columns:

Date  Time  ID   Name  Value
1/1   1:30  aa   Jeff  123124
1/2   2:20  cc   Trung  12443234

Right now, a user will populate the ID field, the vlookup will return Name.

Is there a way to set up a dropdown on the ID cell that shows a concatenation of the ID and Name, but when selected, stores only the ID?

The idea is that the concatenated value that appears in the dropdown (Ex: aa | Jeff) is more user-friendly that just "aa".

Well, hope my answer will help. If not, please tell me and I will try to improve it.

The code is inside the Worksheet

Private Sub ComboBox1_Change()
    'Just use the frist part of the string, ID
    Range("I1").Value = Split(Me.ComboBox1.Value, " | ")

    'Optional, if you want to put the name using code.
    'If not, just use the VLOOLUP
    Range("J2").Value = Split(Me.ComboBox1.Value, " | ")(1)
End Sub

Private Sub Worksheet_Activate()
    Dim r
    Dim c
    Dim i
    Dim L
    Dim myRngID As Range

    r = Range("C2").End(xlDown).Row 'the final row of the ID column
    c = Range("D2").Column ' the number of the column of the name

    Set myRngID = Range(Cells(2, 3), Cells(r, 3)) 'use only the ID range

    'Just to clean the ComboBox everytime to avoid duplicates
    Me.ComboBox1.Value = ""
    L = Me.ComboBox1.ListCount
    On Error Resume Next
    For i = 0 To L
        With Me.ComboBox1
            .RemoveItem i
        End With
    Next i
    On Error GoTo 0

    'Pupulate the ComboBox with the string {ID[space]|[space]NAME}
    For Each i In myRngID
        With Me.ComboBox1
            .AddItem i.Value & " | " & i.Offset(0, 1).Value
        End With
    Next i
End Sub

In the worksheet just this

一张图像值一千个字

As you can see, the only formula in the sheet is in J1 , the VlookUp. In J2 the name is inserted using VBA. The ComboBox has any special property. Everything is in the code above.

The result is that the name is always taken from the ComboBox, and then no matter which one is selected, always will be the right one, as in the VlookUp.

This should work

  1. Select the Cell on the Second Sheet (the one that will be the vlookup)
  2. Go to the Data Tab > Data Validation > Data Validation
  3. On Settings Select List > Click Source button at the right of the input box > Select Range from the first workbook Screenshot
  4. Now copy and paste that cell in the column on the second workbook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM