Excel VBA代码比较两列中的文本字符串并突出显示某些文本字符串而不是整个单元格?
我需要做一个vba代码来比较两列中的文本,并突出显示第二列中匹配的文本。我从代码开始,下面是我到目前为止得到的。它在第一行上运行良好,如何修改代码以将其应用于整个表,而不仅仅是第一行。我是VBA新手,任何帮助都会很好Excel VBA代码比较两列中的文本字符串并突出显示某些文本字符串而不是整个单元格?,excel,vba,Excel,Vba,我需要做一个vba代码来比较两列中的文本,并突出显示第二列中匹配的文本。我从代码开始,下面是我到目前为止得到的。它在第一行上运行良好,如何修改代码以将其应用于整个表,而不仅仅是第一行。我是VBA新手,任何帮助都会很好 Sub Test1() Dim strString$, x& Dim rngCell As Range strString = Range("G2").Value Application.ScreenUpdating = False For Each
Sub Test1()
Dim strString$, x&
Dim rngCell As Range
strString = Range("G2").Value
Application.ScreenUpdating = False
For Each rngCell In Range("S2", Range("S" & Rows.Count).End(xlUp))
With rngCell
.Font.ColorIndex = 1
For x = 1 To Len(.Text) - Len(strString) Step 1
If Mid(.Text, x, Len(strString)) = strString Then .Characters(x, Len(strString)).Font.ColorIndex = 5
Next x
End With
Next rngCell
Application.ScreenUpdating = True
End Sub
如果您的代码在第一行正确运行(我还没有测试它,所以只需相信您是正确的),那么我认为您需要更改以下内容:
Sub Test1()
Dim strString$, x&
Dim rngCell As Range
Application.ScreenUpdating = False
For Each rngCell In Range("S2", Range("S" & Rows.Count).End(xlUp))
With rngCell
.Font.ColorIndex = 1
strString = Cells(rngCell.Row, "G").Value
For x = 1 To Len(.Text) - Len(strString) Step 1
If Mid(.Text, x, Len(strString)) = strString Then .Characters(x, Len(strString)).Font.ColorIndex = 5
Next x
End With
Next rngCell
Application.ScreenUpdating = True
End Sub
i、 e.将strString的计算移到循环内,并基于正在处理的行的G列中的值。我刚刚给了某人一个非常 我试着在表中的所有行上展开它,我得到了错误消息,真的吗?让我猜猜他们是什么。。。不,事实上,你为什么不告诉我们?@chrisneilsen它写在我的屏幕上,你看不出来吗?
Sub ColorMatchingString()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim strTest As Collection: Set strTest = New Collection
Dim udRange As Range: Set udRange = ws.Range("AC2:AC311") 'Define Search Ranges
Dim myCell, myMatch, myString, i
Dim temp() As String, tempLength As Integer, stringLength As Integer
Dim startLength as Integer
For Each myMatch In udRange 'Build the collection with Search Range Values
strTest.Add myMatch.Value
Next myMatch
For Each myCell In ws.Range("A2:AB1125") 'Loop through each cell in range
temp() = Split(myCell.Text, ", ") 'define our temp array as "," delimited
startLength = 0
stringLength = 0
For i = 0 To UBound(temp) 'Loop through each item in temp array
tempLength = Len(temp(i))
stringLength = stringLength + tempLength + 2
For Each myString In strTest
'Below compares the temp array value to the collection value. If matched, color red.
If StrComp(temp(i), myString, vbTextCompare) = 0 Then
startLength = stringLength - tempLength - 1
myCell.Characters(startLength, tempLength).Font.Color = vbRed
End If
Next myString
Next i
Erase temp 'Always clear your array when it's defined in a loop
Next myCell
End Sub