本机工作表公式根本无法很好地处理字符串连接。即使是正在引入的新字符串函数,例如 TEXTJOIN function¹ 和更新后的 CONCAT function²,也难以在 TEXTJOIN 的空白/非空白参数之外进行条件连接。
这里有一对将执行任务的用户定义函数(又名 UDF)。
Function udfUniqueList(rng As Range, _
Optional delim As String = ",")
Dim str As String, r As Range
'always truncate ranges as parameters to the usedrange
Set rng = Intersect(rng, rng.Parent.UsedRange)
str = rng(1).Value2
For Each r In rng
If Not CBool(InStr(1, delim & str & delim, delim & r.Value2 & delim, vbTextCompare)) Then
str = str & delim & r.Value2
End If
Next r
udfUniqueList = str
End Function
Function udfRogueHeaders(rng As Range, hdr As Range, _
Optional delim As String = ",", _
Optional bBlnks As Boolean = False)
Dim i As Long, bas As String, str As String
'always truncate ranges as parameters to the usedrange
Set rng = Intersect(rng, rng.Parent.UsedRange)
'reshape hdr to be identical to rng
Set hdr = hdr.Resize(rng.Rows.Count, rng.Columns.Count)
bas = rng(1).Value2
For i = 1 To rng.Cells.Count
If (CBool(Len(UCase(rng.Cells(i).Value2))) And Not bBlnks) Or _
bBlnks Then
If UCase(bas) <> UCase(rng.Cells(i).Value2) Then
str = str & IIf(CBool(Len(str)), delim, vbNullString) & _
hdr.Cells(i).Value2
End If
End If
Next i
udfRogueHeaders = str
End Function
在 P2:Q2 中,
=udfUniqueList(A2:L2)
=udfRogueHeaders(A2:L2, A$1:L$1)
Results:
¹ TEXTJOIN function 与 Excel 2016 ⁄ Office 365 ⁄ Excel Online 一起引入。它在早期版本中不可用。
² 用于 Excel 2016 ⁄ Office 365 ⁄ Excel Online 的新 CONCAT function 旨在用改进的功能替换旧的 CONCATENATE function。