我不认为你可以在不使用多个单元格或 VBA 的情况下在单个单元格函数中执行此操作。定义一个像下面这样的 UDF,并在一个单元格中使用新函数,语法如下
=StringIntersect("a b c","d e b f")
这将返回“b”
这个函数确实有嵌套循环,但在字符串数组上我想它会足够快
Function StringIntersect(s1 As String, s2 As String) As String
Dim arys1() As String
Dim arys2() As String
Dim arysub() As String
Dim i as integer
Dim j as integer
arys1 = Split(s1, " ")
arys2 = Split(s2, " ")
For i = LBound(arys1) To UBound(arys1)
For j = LBound(arys2) To UBound(arys2)
If arys1(i) = arys2(j) Then StringIntersect = StringIntersect & arys1(i) & " "
Next
Next
StringIntersect = Trim(StringIntersect) 'remove trailing space
End Function
如果你不想做这两个循环,你应该可以用 inStr 做一些非常快的事情。我没有进行任何速度测试,但我怀疑下面的函数更快,但是你会得到意想不到的结果,即字符串在第一个输入中重复,或者第一个输入中的字符串是第二个输入中的子字符串。这可以通过更多检查来避免,但您可能会失去速度优势。
Function StringIntersect(s1 As String, s2 As String) As String
Dim arys1() As String
arys1 = Split(s1, " ")
For i = LBound(arys1) To UBound(arys1)
If InStr(1, s2, arys1(i), vbBinaryCompare) > 0 Then StringIntersect = StringIntersect & arys1(i) & " "
Next
StringIntersect = Trim(StringIntersect) 'remove trailing space
End Function