2016-10-04 73 views
-1

我需要做一個vba代碼來比較兩列中的文本,並突出顯示第二列中的匹配文本。我開始編寫代碼,下面是我到目前爲止的內容。它在第一行工作正常,如何修改代碼以將其應用於整個表格,而不僅僅是第一行。我是VBA新手,任何幫助都會很棒。Excel VBA代碼來比較兩列中的文本字符串,並突出顯示某些文本字符串不是整個單元格?

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 
+0

_I努力擴大它在表中的所有行,我得到錯誤messages_真的嗎?讓我猜猜他們是什麼......不,實際上,你爲什麼不告訴我們? –

+0

@chrisneilsen _它寫在我的屏幕上,你看不懂嗎?_ –

回答

0

如果您代碼正常的第一行(我沒有測試過,所以纔會只相信你是正確的),那麼下面,我認爲,要改變什麼:

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 

即移動的strString計算的循環內,並且基於它正在處理的行的列G中的值。

0

我只是給別人這個答案非常similar question ...

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 
相關問題