首页 > 解决方案 > 如何在 Visual Basic 中查找单词片段

问题描述

如何在 Microsoft Word 的 Visual Basic 宏中找到部分单词?我想找到所有出现的单词片段,但不是整个单词。换句话说,我想要 (1) 在它们之前没有空格并且 (2) 在它们之后只有空格或标点符号的字符串。

例如,搜索“able”将返回可靠但不能够或有能力。

我想查找并突出显示所有出现:仅突出显示单词片段或突出显示包含单词片段的整个单词。

标签: vbafragmentwhitespace

解决方案


根据您的情况,我创建了一个简单的正则表达式来查找相关单词。请尝试以下代码:

Sub RegSearchHL()
Dim myMatches, myMatch
Dim regExp As Object
Set regExp = CreateObject("vbscript.regexp")
With regExp
   .Pattern = "[A-Za-z]+able+[\ \.\,\:\?\!\;]"   'please replace your text
   .Global = True
End With
Set myMatches = regExp.Execute(ActiveDocument.Content.Text)
For Each match In myMatches
    Options.DefaultHighlightColorIndex = wdYellow
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Highlight = True
With Selection.Find
    .Text = match.Value
    .Replacement.Text = match.Value
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll    
Next match
End Sub

此外,您可以将参数传递给 RegExp Pattern 并更新您的需要。

谢谢,

由纪


推荐阅读