在Excel中,我怎样才能创build两个string的“交集”(不放入VB)?

在Mac Excel 2011中,我有两个string,每个string由空格分隔的较小的无空格string组成。 例如:

“红绿蓝粉红”“马苹果红猴粉红”

从这些,我想提取交叉string:

“红粉红”

我可以在VB中完成,但我宁愿保持在Excel中。 现在我知道我可以通过对每个较大string中的较小组件string的数量进行假设,来一起破解(在Excel中)。 然后,我可以将一个较大的string切入这些组件,然后对每个string在第二个大string上执行FIND(),并将结果连接起来。

问题是,虽然在这里我只给出两个string,实际上我有两组string,每个包含20个大string。 所以在Excel中,“劈步”的方法就像O(N ^ 2)一样,我正在寻找一个更简单的方法。

有任何想法吗?

我不认为你可以在不使用多个单元格或VBA的单细胞function中完成。 定义一个如下所示的UDF,并在语法中使用一个单元格中的新函数

=StringIntersect("abc","debf") 

这将返回“B”

这个函数确实有嵌套的循环,但是在string数组上,我想它会很快

 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做一些很快的事情。 我没有做任何速度testing,但我怀疑下面的函数更快,但是你会得到意想不到的结果是string重复在第一个input或第一个inputstring是在第二个子string。 这可以避免更多的检查,但你可能会放弃速度的好处。

 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