CONCIF (UDF)
В Excel
=CONCIF($B$1:$B$20,$C1,$A$1:$A$20)
В VBA
Option Explicit
Function CONCIF(MatchRange As Range, ByVal MatchValue As Variant, _
ConcatRange As Range, _
Optional ByVal Delimiter As String = " ") As String
Dim vntM As Variant ' Match Array
Dim vntC As Variant ' Concat Array
Dim Nor As Long ' Number of Rows
Dim i As Long ' Row Counter
Dim strC As String ' Concat String
Dim strR As String ' Result String
' Check number of rows in MatchRange is less than or equal to number
' of rows in Concat Range.
If MatchRange.Rows.Count <= ConcatRange.Rows.Count Then
' Write number of rows in MatchRange to Number of Rows.
Nor = MatchRange.Rows.Count
Else
' Write number of rows in ConcatRange to Number of Rows.
Nor = ConcatRange.Rows.Count
End If
' Check if Number of Rows is equal to 1, which would mean there
' can only be one match.
If Nor = 1 Then
' Check if the value in 1-cell MatchRange is equal to MatchValue.
If MatchRange.Cells(1, 1) = MatchValue Then
' Write value of 1-cell ConcatRange, converted to string, to CONCIF.
CONCIF = CStr(ConcatRange.Cells(1, 1))
End If
Exit Function
End If
' Copy the range defined by 1st Nor number of cells in 1st column of
' MatchRange to 2D 1-based 1-column Match Array.
vntM = MatchRange.Cells(1, 1).Resize(Nor)
' Copy the range defined by 1st Nor number of cells in 1st column of
' ConcatRange to 2D 1-based 1-column Concat Array.
vntC = ConcatRange.Cells(1, 1).Resize(Nor)
' Loop through elements (rows) of Match/Concat Arrays.
For i = 1 To Nor
' Check if current value in MatchArray is equal to MatchValue.
If vntM(i, 1) = MatchValue Then
' Write current value in ConcatArray to Concat String.
strC = CStr(vntC(i, 1))
' Check if Concat String is NOT "".
If strC <> "" Then
' Check if Result String is NOT "".
If strR <> "" Then
' Concatenate current value of Result String, Delimiter
' and Concat String, to Result String.
strR = strR & Delimiter & strC
Else
' Write Concat String to Result String (only once).
strR = strC
End If
End If
End If
Next
' Write Result String to CONCIF.
CONCIF = strR
End Function
