这个 TextJoinIfs 用户定义函数(又名 UDF)为 Excel 2003 - 2013 版本提供了基本的 TEXTJOIN功能,并通过添加可选的错误控制、唯一性、排序和条件参数数组来简化标准,从而为所有版本提供扩展功能。
此 TextJoinIfs UDF 代码属于公共模块代码表;例如 Book1 - Module1(代码)。
Option Explicit
Public Function TextJoinIfs(delim As String, iOptions As Long, iIgnoreHeaderRows As Long, _
rng As Range, ParamArray pairs()) As Variant
'TEXTJOINIFS - Basic TEXTJOIN functionality for XL2003-XL2013 versions
' Expanded TEXTJOINIFS functionality for all versions
' =TextJoinIfs(<delimiter>, <options>, <header_rows>, <string_range>, [criteria_range1, criteria1], [criteria_range2, criteria2], …)
' OPTIONS
' +2 Include blanks
' +4 Include worksheet errrors
' +8 Unique list
' +16 Sort ascending (cannot be used with 17)
' +17 Sort descending (cannot be used with 16)
If Not CBool(UBound(pairs) Mod 2) Then
TextJoinIfs = CVErr(xlErrValue)
Exit Function
End If
Dim i As Long, j As Long, a As Long, arr As Variant
Dim bIncludeBlanks As Boolean, bIncludeErrors As Boolean, bUniqueList As Boolean
Dim bSorted As Boolean, bDescending As Boolean
bIncludeBlanks = CBool(2 And iOptions)
bIncludeErrors = CBool(4 And iOptions)
bUniqueList = CBool(8 And iOptions)
bSorted = CBool(16 And iOptions)
bDescending = CBool(1 And iOptions)
Set rng = Intersect(rng, rng.Parent.UsedRange.Offset(iIgnoreHeaderRows - rng.Parent.UsedRange.Rows(1).Row + 1, 0))
With rng
ReDim arr(.Cells.Count)
If Not IsMissing(pairs) Then
For i = LBound(pairs) To UBound(pairs) Step 2
Set pairs(i) = pairs(i).Resize(rng.Rows.Count, rng.Columns.Count).Offset(iIgnoreHeaderRows, 0)
Next i
End If
For j = 1 To .Cells.Count
If CBool(Len(.Cells(j).Text)) Or bIncludeBlanks Then
If Not IsError(.Cells(j)) Or bIncludeErrors Then
If IsError(Application.Match(.Cells(j).Text, arr, 0)) Or Not bUniqueList Then
If IsMissing(pairs) Then
arr(a) = .Cells(j).Text
a = a + 1
Else
For i = LBound(pairs) To UBound(pairs) Step 2
If Not CBool(Application.CountIfs(pairs(i).Cells(j), pairs(i + 1))) Then Exit For
Next i
If i > UBound(pairs) Then
arr(a) = .Cells(j).Text
a = a + 1
End If
End If
End If
End If
End If
Next j
End With
ReDim Preserve arr(a - 1)
If bSorted Then
Dim tmp As String
For i = LBound(arr) To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If CBool(LCase(CStr(arr(i))) < LCase(CStr(arr(j))) And bDescending) Xor _
CBool(LCase(CStr(arr(i))) > LCase(CStr(arr(j))) And Not bDescending) Then
tmp = arr(j): arr(j) = arr(i): arr(i) = tmp
End If
Next j
Next i
End If
TextJoinIfs = Join(arr, delim)
End Function
句法:
=TextJoinIfs(<delimiter>, <options>, <header_rows>, <string_range>, [criteria_range1, criteria1], [criteria_range2, criteria2], …)
文档
示例 1
简单的 TextJoin 操作丢弃空白和错误,只保留唯一的字符串。与换行符 (vbLF) 分隔符连接,但忽略前两个标题行并按升序排序。
=textjoinifs(CHAR(10), 24, 2, A:A)
示例 2
扩展的 TextJoinIfs 操作丢弃空白和错误,只保留唯一的字符串。与分号/空格分隔符连接。一组条件范围和标准。
=textjoinifs("; ", 8, 0, B:B, A:A, A2)
示例 3
扩展的 TextJoinIfs 操作丢弃空白和错误。与逗号/空格分隔符连接。使用数学比较的多个条件对。
=textjoinifs(", ", 0, 0, B:B, A:A, ">="&D2, A:A, "<="&E2)
非常感谢Lorem Ipsum Generator提供的示例字符串内容。