vba - 如何在 Visual Basic 中查找单词片段
问题描述
如何在 Microsoft Word 的 Visual Basic 宏中找到部分单词?我想找到所有出现的单词片段,但不是整个单词。换句话说,我想要 (1) 在它们之前没有空格并且 (2) 在它们之后只有空格或标点符号的字符串。
例如,搜索“able”将返回可靠但不能够或有能力。
我想查找并突出显示所有出现:仅突出显示单词片段或突出显示包含单词片段的整个单词。
解决方案
根据您的情况,我创建了一个简单的正则表达式来查找相关单词。请尝试以下代码:
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 并更新您的需要。
谢谢,
由纪
推荐阅读
- xampp - Magento 2 已安装,但缺少管理员登录表单
- reactjs - 我需要哪个导入才能在 KotlinJS React App 中使用 hashrouter
- ionic-framework - Mapbox 导航 Ionic
- html - 了解为什么表格单元格不包装其 100% 的高度内容
- javascript - 如何确保食物没有放在蛇里面?
- java - 为什么嵌套类对象在将外部类实例设置为空后仍然可以访问外部类属性?
- twitter-bootstrap - 在外部单击时关闭 Bootstrap 4.21 弹出框
- java - KafkaConsumer 不消费消息
- mysql - 通过zapier调用存储过程但没有插入行
- python - 尽管大小正确,但无法调整 numpy 图像数组的大小