从下拉框中选择值,但填充隐藏列

时间:2016-01-08 22:00:10

标签: excel

我有一组唯一的ID和名称:

ID   NAME
aa   Jeff
bb   Matt
cc   Trung
dd   Trung

所有ID都是唯一的。名字不是。

在工作表上,我有一系列专栏:

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

现在,用户将填充ID字段,vlookup将返回Name。

有没有办法在ID单元格上设置一个下拉列表,显示ID和名称的串联,但是在选中时,只存储ID?

这个想法是下拉列表中显示的连接值(例如:aa | Jeff)更加用户友好,只是“aa”。

2 个答案:

答案 0 :(得分:1)

嗯,希望我的回答会有所帮助。如果没有,请告诉我,我会尽力改进它。

代码在工作表中

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

在工作表中只是这个

An image is worth a thousand words

如您所见,表格中唯一的公式是J1,即VlookUp。在J2中,使用VBA插入名称。 ComboBox有任何特殊属性。一切都在上面的代码中。

结果是名称总是来自ComboBox,然后无论选择哪一个,总是正确的,就像在VlookUp中一样。

答案 1 :(得分:-1)

这应该有效

  1. 选择第二张纸上的单元格(将成为vlookup的单元格)
  2. 转到数据标签>数据验证>数据验证
  3. 在设置上选择列表>单击输入框右侧的“源”按钮>从第一个工作簿Screenshot
  4. 中选择范围
  5. 现在将该单元格复制并粘贴到第二个工作簿的列中