样本数据:
Col A Col B
Grand Theft Auto Grand Theft Grand,Theft
Sub Repeatwrd()
Dim lastRow As Long
Dim i As Long
Dim cellValueA As String
Dim cellValueB As String
Dim wordsA As Variant
Dim wordsB As Variant
Dim wordIndex As Long
Dim word As Variant
Dim wordCount As Integer
' Get the last row of data in column A
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
' Loop through each row of data in column A and compare with column B
For i = 1 To lastRow
' Get the values in columns A and B for the current row
cellValueA = Cells(i, 1).Value
cellValueB = Cells(i, 2).Value
' Split the strings into words
wordsA = Split(cellValueA, " ")
wordsB = Split(cellValueB, " ")
' Loop through each word in column A
For wordIndex = 0 To UBound(wordsA)
' If the word is not found in column B, highlight it in column A
If InStr(cellValueB, wordsA(wordIndex)) = 0 Then
word = wordsA(wordIndex)
' Highlight the word in column A
Cells(i, 1).Characters(InStr(cellValueA, word), Len(word)).Font.ColorIndex = 3 ' Highlight in red
'Add highlight word in c column
'Cells(i, 3).Value = Cells(i, 3).Value & " " & word
End If
Next wordIndex
' Loop through each word in the string
For Each word In wordsA
' Count the number of occurrences of the word in the string
wordCount = UBound(Split(cellValueA, word)) - LBound(Split(cellValueA, word))
' If the word occurs more than once, paste it in column C for the current row
If wordCount > 1 Then
'ws.Cells(i, 3).Value = word
Cells(i, 3).Value = word
Exit For ' Exit the loop once a repeated word is found
End If
' If the word occurs more than once, paste it in column C for the current row
If wordCount > 1 Then
'ws.Cells(i, 3).Value = word
Cells(i, 3).Value = word
Exit For ' Exit the loop once a repeated word is found
End If
Next word
Next i
End Sub
i可以得到一个值Grand如何得到col b中的两个重复单词(Grand,Theft)值?
3条答案
按热度按时间1tu0hz3e1#
如何获取目标列中的重复值:技巧是在每个循环中删除原始单元中所有出现的测试字。
将示例代码的第二部分替换为以下内容:
dkqlctbz2#
您应该使用字典、集合或数组来记录您找到并处理的内容,以供后续处置,而不是立即离开循环。
yeotifhr3#
在VBA中创建和UDF来检查这个,考虑一个单词在2个空格之间,或者在字符串的开头有尾随空格,或者在字符串的结尾有前导空格。把所有这些案子加起来。如果总和大于0,则为重复。
此UDF需要2个参数:
rng1
是要检查的字,rng2
是包含rng1
的重复的范围。请注意,输出排序是不同的,这取决于您如何设置rng1
和rng2
,但单词是相同的:C列中的公式为:
=GET_DUP_WORDS(A1;B1)
列D中的公式相反:=GET_DUP_WORDS(B1;A1)
您可以在SUB中合并此UDF以应用全范围。