这个问题很多人问过我,excel自带的函数组合也能够做到,但实际上效果一般都不理想,而且再次使用也很麻烦,所以自己写了个自定义函数。
这个自定义函数,是将所有符合条件的文本放在同一个单元格里,按给定的分隔符分隔。
1 | Public Function Contxts(delimiter As String, ParamArray args() As Variant) |
函数实际上就是利用if得到数组,并把所有的数组用分隔符重新组合,下图就是使用函数的一个例子。
这样的结果里没有排除重复值,所以我又写了一个函数,以应对这种情况。1
2
3
4
5
6
7
8
9
10
11
12Public Function Duplicates(s As String, delimiter As String)
Dim qt() As String, str As String
Dim n As Long
qt = Split(s, delimiter)
str = qt(0) & ","
For n = 1 To UBound(qt)
If InStr(1, str, qt(n)) = 0 Then
str = str & qt(n) & ","
End If
Next n
Duplicates = Left(str, Len(str) - 1)
End Function
这个函数对任何一个有固定分隔符的字符串,都能进行去重,并重新组合。