與你原來的代碼保持一致,你可以添加其他For each cell in Range
(和其他一些東西):
Sub test4String2color()
Dim wb As Workbook
Dim ws As Worksheet
Dim strLen As Integer
Dim i As Long
Dim tst As Range
Set wb = ActiveWorkbook
Set ws = wb.ActiveSheet
Dim keyWordRng As Range
Dim dataRng As Range
Set keyWordRng = ws.Range("F1:F2")
Set dataRng = ws.Range("A1:A5")
For Each tst In keyWordRng
Debug.Print "Searching for: " & tst
For Each cell In dataRng
If tst.Value = cell.Value Then
cell.Characters(InStr(cell, tst), strLen).Font.Color = vbRed
ElseIf InStr(1, cell.Value, ",") > 0 Then
getWordsInCell cell, tst.Value
End If
Next cell
Next tst
End Sub
Sub getWordsInCell(ByVal cel As Range, keyword As String)
Dim words() As String
Dim keywordS As Integer, keywordE As Integer
words = Split(cel.Value, ",")
Dim i As Long
For i = LBound(words) To UBound(words)
Debug.Print "Found multiple words - one of them is: " & words(i)
If Trim(words(i)) = keyword Then
keywordS = ActiveWorkbook.WorksheetFunction.Search(keyword, cel, 1)
keywordE = ActiveWorkbook.WorksheetFunction.Search(",", cel, keywordS)
cel.Characters(keywordS, (keywordE - keywordS)).Font.Color = vbRed
End If
Next i
End Sub
請注意,我加入到範圍(keyWordRng
和dataRng
),你將需要調整您的工作表。這應該(手指交叉)工作!
「......但我需要搜索整個數組」,你是什麼意思?如果我把'Gotham'放在'F1'中,它正確地突出顯示了在'A1:D100'範圍內的所有'Gotham'的發現(它突出顯示「Gotham」以及單元格之後的所有文本)。你是說'F1'可以說'Gotham,City,Wayne Enterprises',並且你想要搜索每一個單詞(用逗號或其他分隔符分隔)? – BruceWayne
你在正確的軌道上。你可以使'strTest'成爲一個Collection並循環遍歷它,以便與第二個For循環匹配。由於您沒有使用任何UDT,集合將很容易設置並循環。 – Tyeler
@BruceWayne我在說我想要尋找Gotham,City,Wayne Enterprises。但是它們全部位於不同的單元格中,而不是以逗號分隔的單個單元格中。我有一個約200個單詞的列表,每個單詞都在我想用作搜索條件的不同單元格中。 – user6883405