如果一个单词后面没有另一个特定的单词,我想用VB突出显示它



所以我在使用VB方面完全是个新手。当一个单词后面两个单词中没有另一个特定的单词时,我会尝试突出显示它。我尝试了以下代码,但它似乎只是第一个单词。非常感谢。

Sub fek()
'
' 
'
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = "n."
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
If Selection.Find.Found = True Then
With Selection.Range

.MoveStart wdWord, 2

End With

With Selection.Find
.Text = "fek"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With

End If

If Selection.Find.Found = False Then
Selection.Range.HighlightColorIndex = wdYellow
End If
End Sub

下面的代码应该可以随心所欲。你需要记住,Word定义的Word可能与人类不同,例如,IP地址被计算为7个单词!

Sub fek()
Dim findRange As Range
Dim nextWords As Range

Set findRange = ActiveDocument.Content
With findRange.Find
.ClearFormatting
.Text = "n."
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

Do While .Execute = True
'findRange is now the range of the match so set nextWords to the 2 next words
Set nextWords = findRange.Next(wdWord)
nextWords.MoveEnd wdWord, 3
'look for the specific text in the next two words
If InStr(nextWords.Text, "fek") = 0 Then findRange.HighlightColorIndex = wdYellow
'collapse and move findRange to the end of the match
findRange.Collapse wdCollapseEnd
findRange.Move wdWord, 4
Loop
End With
End Sub

如果有很多"n",下面的可能会更快文档中的字符串:

Sub Demo()
Application.ScreenUpdating = False
Dim i As Long
i = Options.DefaultHighlightColorIndex
Options.DefaultHighlightColorIndex = wdYellow
With ActiveDocument.Range
With .Find
.Forward = True
.Format = False
.MatchCase = False
.Wrap = wdFindContinue
.MatchWildcards = True
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.Text = "n."
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
.Replacement.Highlight = False
.Text = "n.[^s ]@fek"
.Execute Replace:=wdReplaceAll
.Text = "n.[^s ]@[!^s ]@fek"
.Execute Replace:=wdReplaceAll
.Text = "n.[^s ]<[!^s ]@>[^s ]@fek"
.Execute Replace:=wdReplaceAll
.Text = "n.[^s ]<[!^s ]@>[^s ]@[!^s ]@fek"
.Execute Replace:=wdReplaceAll
End With
End With
Options.DefaultHighlightColorIndex = i
Application.ScreenUpdating = True
End Sub

最新更新