查找具有相同相邻元素的所有其他单元格

时间:2016-04-16 18:56:06

标签: excel-formula

我有一个带有以下列的excel spreadhseet

  • A:City
  • B:州
  • C:与A列状态相同的其他城市

例如,结果可能如下所示:

    City             State                Other cities in State
    --------------------------------------------------------------
    Philadelphia     Pennsylvania        Pitsburgh
    Pitsburgh        Pennsylvania        Philadelphia
    San Diego        California          Palo Alto, Mountain View, LA, San Jose, Houston
    Palo Alto        California          San Jose, Mountain View, San Diego
    Mountain View    California          San Jose, LA, Palo Alto, San Diego
    LA               California          San Jose, Mountain View, Palo Alto, San Diego
    San Jose         California          LA, Mountain View, Palo Alto, San Diego
    Austin           Texas               Houston, Dallas
    Houston          Texas               Austin, Dallas
    Dallas           Texas               Dallas, Houston

我可以使用什么公式来生成“州内其他城市”栏目?

1 个答案:

答案 0 :(得分:1)

使用Excel工作表函数很难进行粗糙的边缘字符串连接;即使使用新的Excel 2016 / Office 365 / Excel Online CONCATTEXTJOIN函数¹。

编写良好的UDF²可以轻松克服这些限制。

<强> Module1 code sheet

Option Explicit

Function CITYJOIN(rst As Range, sst As String, rct As Range, _
                  Optional sct As String = "", _
                  Optional bIncludeSelf As Boolean = False, _
                  Optional delim As String = ", ")
    Dim r As Long
    Static dict As Object
    If dict Is Nothing Then
        Set dict = CreateObject("Scripting.Dictionary")
        dict.compareMode = vbTextCompare
    End If

    dict.RemoveAll
    'truncate any full column references to the .UsedRange
    Set rst = Intersect(rst, rst.Parent.UsedRange)
    'set the cities to the same size as the states
    Set rct = rct.Resize(rst.Rows.Count, rst.Columns.Count)

    'loop through the cells to create unique dictionary keys
    For r = 1 To rst.Cells.Count
        If LCase(rst(r).Value2) = LCase(sst) Then
            dict.Item(StrConv(rct(r).Value2, vbProperCase)) = vbNullString
        End If
    Next r

    'get rid of 'self-city'
    If Not bIncludeSelf Then
        dict.Remove sct
    End If

    'return a delimited string
    CITYJOIN = Join(dict.keys, delim)

End Function

cityjoin

如果您选择将城市包含在同一行,则可选城市(例如sct)仅是可选的。默认情况下,同一行中的城市被排除在外,必须作为参数提供才能将其删除。

static dict对象意味着您只需创建一次Scripting.Dictionary对象。相同的对象用于后续调用该函数。当使用包含此UDF的公式填充长列时,这尤其有用。

¹ 有关详细信息,请参阅What's new in Excel 2016 for Windows

²用户定义函数(又名UDF)被放入标准模块代码表中。点击 Alt + F11 ,当VBE打开时,立即使用下拉菜单插入►模块 Alt + 中号)。将功能代码粘贴到标题为 Book1 - Module1(Code)的新模块代码表中。点击 Alt + Q 返回工作表。