如何匹配Excel中两个单独列中与返回相关的单元格字段?

时间:2019-04-01 21:25:10

标签: excel

我试图创建一个显示所有匹配字段但又包括“链接单元格”的公式。像这样-

在“ Brad”中键入用户,并且结果框应显示“ Brad,Adam,Charlie,David”,因为Brad与Adam关联,而Adam与Charlie和David关联。

A     B
Adam|Brad
Adam|Charlie
Adam|David
Evan|Fred

公式:

{IFERROR(IFERROR(INDEX(Column B,SMALL(IF(Column A=InputCriteria,ROW(Column A)-1),ROW(1:1))),INDEX(Column A,SMALL(IF(Column B=InputCriteria,ROW(Column B)-1),ROW(1:1)))),"")}

1 个答案:

答案 0 :(得分:2)

我的名字叫布拉德(Brad),所以我无能为力,我不得不给出解决方案。 :-)

将以下代码添加到VBA编辑器中的新模块中...

Public Function GetAssociatedNames(ByVal strName As String, ByVal rngCells As Range) As String
    Dim lngRow As Long, lngCol As Long, lngBlanks As Long, objNames As Scripting.Dictionary
    Dim strName1 As String, strName2 As String, i As Long, strNameToAdd As String, x As Long
    Dim lngStart As Long, lngCount As Long, lngForCount As Long

    strName = Trim(strName)

    Set objNames = New Scripting.Dictionary
    objNames.Add strName, strName

    With rngCells
        lngStart = 0

        Do While True
            lngForCount = objNames.Count - 1

            If lngStart > lngForCount Then Exit Do

            For x = lngStart To lngForCount
                strName = objNames.Keys(x)

                lngCount = objNames.Count

                For lngRow = 1 To .Rows.Count
                    strName1 = .Cells(lngRow, 1)
                    strName2 = .Cells(lngRow, 2)

                    If strName1 & strName2 = "" Then
                        lngBlanks = lngBlanks + 1
                    Else
                        lngBlanks = 0

                        If strName1 = strName Then strNameToAdd = strName2
                        If strName2 = strName Then strNameToAdd = strName1

                        If Not objNames.Exists(strNameToAdd) And strNameToAdd <> "" Then objNames.Add strNameToAdd, strNameToAdd
                    End If

                    If lngBlanks = 10 Then Exit For
                Next

                lngStart = lngStart + 1
            Next
        Loop
    End With

    For i = 0 To objNames.Count - 1
        GetAssociatedNames = Trim(GetAssociatedNames & "," & objNames.Keys(i))
    Next

    GetAssociatedNames = Replace(Mid(GetAssociatedNames, 2), ",", ", ")
End Function

...然后添加对 Microsoft脚本运行时 ...

的引用

enter image description here

然后您可以在单元格中使用公式,就像这样...

enter image description here

它对我有用,希望它对您有用。