How do I compare text in Excel cells to see if same words are found?

时光怂恿深爱的人放手 提交于 2020-02-15 06:00:48

问题


I have several rows of Excel cells which contain a string of words, all separated by commas. I want to compare each cell with another cell to check if any of the words match/are duplicates. For example:

cell A1: dog, cat, rabbit, mouse, lion, bear, tiger
cell A2: sausage, pickle, dog, cat, elephant, bread

result: dog, cat

The result could also be a number (e.g. 2) if that is easier. Many thanks!


回答1:


I think you would be best served using VBA which you could then deploy as a User Defined Function (UDF)

  • hold down altf11 to go to the VBE
  • Insert ... Module
  • copy and paste in the code below
  • hold down altf11 to go back to Excel

Then call the function in Excel such as
=DupeWord(A1,A2) to find any matches between A1 and A2

Usr Defined Function

Function DupeWord(str1 As String, str2 As String) As String
Dim vArr1
Dim vArr2
Dim vTest
Dim lngCnt As Long
vArr1 = Split(Replace(str1, " ", vbNullString), ",")
vArr2 = Split(Replace(str2, " ", vbNullString), ",")
On Error GoTo strExit

For lngCnt = LBound(vArr1) To UBound(vArr1)
vTest = Application.Match(vArr1(lngCnt), vArr2, 0)
If Not IsError(vTest) Then DupeWord = DupeWord & vArr1(lngCnt) & ", "
Next lngCnt
If Len(DupeWord) > 0 Then
DupeWord = Left$(DupeWord, Len(DupeWord) - 2)
Else
strExit:
DupeWord = "No Matches!"
End If

End Function

Use inside VBA

Sub test()
MsgBox DupeWord("dog, cat, rabbit, mouse, lion, bear, tiger", "sausage, pickle, dog, cat, elephant, bread")
End Sub



回答2:


From here

To check if the string is equal to another you can use Exact
=EXACT(text1,text2)

Text1 is the first text string.

Text2 is the second text string.



来源:https://stackoverflow.com/questions/12069890/how-do-i-compare-text-in-excel-cells-to-see-if-same-words-are-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!