首页 > 解决方案 > 从一个工作表中创建与另一个工作表上的单元格匹配的所有值的列表

问题描述

好的,我需要在 Sheet2 上自动构建一个列表(在第 2 行的 A 列中)。

如果我在 Sheet2 上的 A1 中输入数据“团队 1”,我需要它从 Sheet1 列 B 中提取任何人的姓名。(A 列有他们所在的团队)。

我尝试了以下方法,但没有运气。

=IFERROR(INDEX($A$1:$A$4,SMALL(IF($B$1:$B$4=$D$1,ROW($B$1:$B$4)-ROW($B$1)+1),行($B$1:$B1))),"")

不会产生任何东西。

我过去曾见过一个类似的 VBA 代码,但在这种情况下无法尝试操纵它来工作。

标签: excelvbalistarraylist

解决方案


或者在 Sheet2 的代码模块中使用它...

    Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim vSourceSheet As Worksheet
    Dim VRow As Range
    Dim VTargetCounter As Long

    If Target.Address = "$A$1" Then
        ' clear out the names in the target column
        Range("A2:A" & Rows.Count).Clear

        ' read through Sheet1 and populate names into Sheet2
        VTargetCounter = 2
        Set vSourceSheet = ThisWorkbook.Worksheets("Sheet1")
        For Each VRow In vSourceSheet.Range("A1:A" & vSourceSheet.Range("A" & vSourceSheet.Rows.Count).End(xlUp).Row)
            If VRow.Cells(1, 1) = Target.Value2 Then
                Target.Cells(VTargetCounter, 1) = VRow.Cells(1, 2)
                VTargetCounter = VTargetCounter + 1
            End If
        Next
    End If

End Sub

推荐阅读