在Excel中突出显示单词

时间:2015-10-01 16:02:48

标签: excel vba

所以我认为我找到了问题的答案here...但是当我复制并粘贴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很满意他的结果,看着我看不到我错的地方的代码。

2 个答案:

答案 0 :(得分:1)

在通过查看Word VBA代码并且没有Excel弄乱我的原始帖子之后我找到了答案,然后将其修改为适合我在下面寻找的是我使用的代码并且它适用于我。感谢所有其他答案!

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

答案 1 :(得分:0)

这样的事情应该做你想做的事情:

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