执行搜索并获取所有匹配项

时间:2013-10-21 20:24:37

标签: excel vba excel-vba excel-formula pivot-table

让我们举个例子,问题是:“安妮有多少次科学与任何评论”? (回答:2次)。

    A         B         C       D
1   Name    Gender  Subject Commentary
2   Anne    Female  Maths   
3   Anne    Female  English 
4   Anne    Female  Science whatever...
5   Anne    Female  Maths   
6   Anne    Female  English 
7   Anne    Female  Science blah, blah 
8   Kath    Female  Maths   
9   Kath    Female  English 
10  Kath    Female  Science 
11  Tony    Male    Maths   etc...
12  Tony    Male    English 
13  Tony    Male    Science blah, blah

我使用COUNTIFS解决了它:

=COUNTIFS(Sheet1!A1:A13,"Anne",D1:D13,"*")

但是现在我需要搜索所有的Anne + Science评论并检索它们在结果单元格中连接,这样:“不管......等等,等等。”

怎么办?
如果使用公式无法做到这一点,那么如何使用VBA?

2 个答案:

答案 0 :(得分:2)

Public Function Commentary(rSource As Range, sName As String, sSubject As String) As String

    Dim vaSource As Variant
    Dim i As Long
    Dim lCnt As Long
    Dim aOutput() As String

    vaSource = rSource.Value

    For i = LBound(vaSource, 1) To UBound(vaSource, 1)
        If vaSource(i, 1) Like sName And vaSource(i, 3) Like sSubject Then
            lCnt = lCnt + 1
            ReDim Preserve aOutput(1 To lCnt)
            aOutput(lCnt) = vaSource(i, 4)
        End If
    Next i

    Commentary = Join(aOutput, "|")

End Function

一样使用
=Commentary(A1:D13,"Anne","Science")

答案 1 :(得分:1)

您可以使用数据透视表并将结果连接到那里,如下所示:

SO19503989 example

修改

我应该解释一下,如果有很多条目,请在I7中使用=I6&", "&F7,复制以适应并选择系列中的最后一个。