答案 0 :(得分:0)
原生工作表公式根本不能很好地处理字符串连接。即使是正在引入的新字符串函数,例如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 强>
¹ Excel 2016 / Office 365 / Excel Online正在引入TEXTJOIN function。它在早期版本中不可用。
² Excel 2016 / Office 365 / Excel Online的新CONCAT function旨在用功能改进的旧CONCATENATE function替换。