在Excel中突出显示单词

所以我想我在这里find了我的问题的答案…但是当我复制并粘贴VBA代码时,在“With range.Find”行中出现“Compile error:Argument not optional”错误。

Sub HighlightWords2() Dim range As range Dim i As Long Dim TargetList TargetList = Array("words") 'put list of terms to find here For i = 0 To UBound(TargetList) Set range = ActiveDocument.range With range.Find .Text = TargetList(i) .Format = True .MatchCase = True .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False Do While .Execute(Forward:=True) = True range.HighlightColorIndex = wdYellow Loop End With Next End Sub 

OP对他的结果很满意,看着代码我不明白我要去哪里错了。

当我通过查看Word VBA代码和没有Excel我混乱了我原来的职位,我find了一个答案,然后修改它,以适应我在找的下面是我使用的代码,它适用于我。 感谢所有其他的答案!

 Sub HIGHLIGHTER() Dim sPos As Long, sLen As Long Dim rng As Range Dim findMe As String Dim i As Integer Dim t As Integer Dim SearchArray SearchArray = Array("DEMENTIA", "SENILE", "ALZHEIMERS", "ALZHIEMERS", "WANDERING", "WANDER", "DEMENT") For t = 0 To UBound(SearchArray) Set rng = Range("N2:N10000") findMe = SearchArray(t) For Each rng In rng With rng If rng.Value Like "*" & findMe & "*" Then If Not rng Is Nothing Then For i = 1 To Len(rng.Value) sPos = InStr(i, rng.Value, findMe) sLen = Len(findMe) If (sPos <> 0) Then rng.Characters(Start:=sPos, Length:=sLen).Font.Color = RGB(255, 0, 0) rng.Characters(Start:=sPos, Length:=sLen).Font.Bold = True i = sPos + Len(findMe) - 1 End If Next i End If End If End With Next rng Next t End Sub 

像这样的东西应该做你想做的事情:

 Sub HighlightWords2() Dim range As range Dim i As Long Dim TargetList(3) TargetList(0) = "SearchTerm1" TargetList(1) = "SearchTerm2" TargetList(2) = "SearchTerm3" TargetList(3) = "SearchTerm4" For i = 0 To UBound(TargetList) Set range = ActiveSheet.Cells With range Set c = .Find(TargetList(i), lookat:=xlPart, MatchCase:=True) If Not c Is Nothing Then c.Cells.Interior.ColorIndex = 6 End If End With Next i End Sub