如何基于单元格的值搜索列并将相邻列的值添加到列表中?

时间:2019-01-24 19:30:01

标签: excel vba excel-formula

我想基于一个单元格搜索一列,并将相邻的列值添加到列表中。

示例: 工作表上的数据的布局如下:

**enter image description here**

当我转到另一张纸并从下拉列表中选择 Henry Ben 时,相邻单元格会下拉与A列中的名称相关的所有IDS

示例2:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

让我们假设对于这个答案,我们使用工作表1。 工作表1的结构:

enter image description here

Option Explicit

    Private Sub Worksheet_Change(ByVal Target As Range)

        Dim Lastrow As Long
        Dim cell As Range, rng As Range, rngResults As Range
        Dim strSearch As String, strResults As String

        With ThisWorkbook.Worksheets("Sheet1")

            If Not Intersect(Target, .Range("D2")) Is Nothing Then

                strSearch = Target.Value

                Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

                Set rng = .Range(.Cells(2, 1), .Cells(Lastrow, 1))
                Set rngResults = .Range("E2")

                For Each cell In rng

                    If strSearch = cell.Value Then

                        If IsEmpty(strResults) Then
                            strResults = cell.Offset(0, 1).Value
                            Debug.Print strResults
                        Else
                            strResults = strResults & "," & cell.Offset(0, 1).Value
                            Debug.Print strResults

                        End If

                    End If

                Next

                    With rngResults.Validation
                        .Delete
                        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
                            Formula1:=strResults
                    End With

            End If

        End With

    End Sub