How to easily concatenate text based on criteria in Excel? 如何將Excel中的文本按條件合併

To combine text with the unique ID numbers, you can extract the unique values first and then create a User Defined Function to combine the names based on the unique ID.html

1. Take the following data as example, you need to extract the unique ID numbers first, please apply this array formula: =IFERROR(INDEX($A$2:$A$15, MATCH(0,COUNTIF($D$1:D1, $A$2:$A$15), 0)),""),enter this formula into a blank cell, D2 for example, then press Ctrl + Shift + Enter keys together, see screenshot:app

doc combine text based on criteria 2

Tip: In the above formula, A2:A15 is the list data range you want to extract unique values from, D1 is the first cell of the column you want to put out the extracting result.this

2. And then drag the fill handle down to extract all unique values until blanks displayed, see screenshot:spa

doc combine text based on criteria 3

3. In this step, you should create a User Defined Function to combine the names based on the unique ID numbers, please hold down the ALT + F11 keys, and it opens the Microsoft Visual Basic for Applications window.excel

4. Click Insert > Module, and paste the following code in the Module Window.code

VBA code: concatenate text based on criteriaorm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Function ConcatenateIf(CriteriaRange  As Range, Condition  As Variant , ConcatenateRange  As Range,  Optional Separator  As String "," As Variant
'Update 20150414
Dim xResult  As String
On Error Resume Next
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
         xResult = xResult & Separator & ConcatenateRange.Cells(i).Value
     End If
Next i
If xResult <>  "" Then
     xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
End If
ConcatenateIf = xResult
Exit Function
End Function

5. Then save and close this code, go back to your worksheet, and enter this formula into cell E2, =CONCATENATEIF($A$2:$A$15, D2, $B$2:$B$15, ",") , see screenshot:htm

doc combine text based on criteria 4

6. Then drag the fill handle down to the cells that you want to apply this formula, and all the corresponding names have been combined based on the ID numbers, see screenshot:ip

doc combine text based on criteria 5

Tips:ci

1. In the above formula, A2:A15 is the original data which you want to combine based on, D2 is the unique value you have extracted, and B2:B15 is the name column that you want to combine together.

2. As you can see, I combined the values which are separated by comma, you can use any other characters by changing the comma 「,」 of the formula as you need.

Link: https://www.extendoffice.com/documents/excel/2723-excel-concatenate-based-on-criteria.html

相關文章
相關標籤/搜索