VBA User Defined Function for “Concatenate If” by rows

前端 未结 1 1151
野的像风
野的像风 2021-01-15 09:00

I have some data of whether or not a particular \"service\" (e.g. Bird Survey) has been performed for a particular site, with a \"yes\" or \"no\" for each service.

E

1条回答
  •  粉色の甜心
    2021-01-15 09:45

    Based upon what you're looking for, I found this function a long time ago and it's worked a charm:

    Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, _
            ConcatenateRange As Range, Optional Separator As String = ",") As Variant
        Dim i As Long
        Dim strResult As String
        On Error GoTo ErrHandler
        If CriteriaRange.Count <> ConcatenateRange.Count Then
            ConcatenateIf = CVErr(xlErrRef)
            Exit Function
        End If
        For i = 1 To CriteriaRange.Count
            If CriteriaRange.Cells(i).Value = Condition Then
                strResult = strResult & Separator & ConcatenateRange.Cells(i).Value
            End If
        Next i
        If strResult <> "" Then
            strResult = Mid(strResult, Len(Separator) + 1)
        End If
        ConcatenateIf = strResult
        Exit Function
    ErrHandler:
        ConcatenateIf = CVErr(xlErrValue)
    End Function
    

    Given your question, it would be used as follows:

    =ConcatenateIf(B2:E2,"yes",$B$1:$E$1,", ")
    

    Initial credit goes to this link.

    Hope this does the trick!!

    0 讨论(0)
提交回复
热议问题