vba - Word VBA Find and move on
问题描述
Here is my issue,
I'm looking for ":"
and typing HTML code with VBA. The code below keeps looping at the same ":"
and does not move on to the next, since I'm not actually removing it. Any suggestions?
Dim bFound As Boolean
bFound = True
Set r = ActiveDocument.Content
r.Find.ClearFormatting
Do While bFound
With r.Find
.Text = ":"
.Replacement.Text = ":</b>"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
bFound = .Execute(Replace:=wdReplaceOne, Forward:=True)
End With
If bFound Then
r.Select
Selection.HomeKey Unit:=wdLine
Selection.TypeText Text:="<b>"
Selection.EndKey Unit:=wdLine
Selection.MoveRight
End If
Loop
解决方案
代码有两个问题,否则很好:
它
wdFindContinue
用于Wrap
属性,这意味着 Find 将在文档开头重新启动。根据经验,始终wdFindStop
在代码中使用。如果正在搜索的内容保留在文档中,则有必要将找到的 Range 移动到该点之外。这可以通过使用来完成
Range.Collapse
。可以将其想象为当您进行选择时按键盘上的右箭头键:它将光标置于所选内容之外。
我已经用这两个更改修改了原始代码,另外我还声明了一个Range
变量。没有此声明的原始代码运行表明Option Explicit
可能不在代码模块的顶部。如果有就更好了...
Sub JumpBeyondFound()
Dim r As Word.Range
Dim bFound As Boolean
bFound = True
Set r = ActiveDocument.content
r.Find.ClearFormatting
Do While bFound
With r.Find
.Text = ":"
.Replacement.Text = ":</b>"
.Forward = True
.wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
bFound = .Execute(Replace:=wdReplaceOne, Forward:=True)
End With
If bFound Then
r.Select
Selection.HomeKey Unit:=wdLine
Selection.TypeText Text:="<b>"
Selection.EndKey Unit:=wdLine
Selection.MoveRight
r.Collapse wdCollapseEnd
End If
Loop
End Sub
推荐阅读
- matlab - 警告:此位置的表格数据不可编辑
- css - 以条纹虚线为背景
- export-to-csv - 在使用 azure 数据工厂提取为 .csv 文件时,是否有任何选项可以将包含逗号的单元格值括在双引号中?
- java - 我们如何有效地编写空检查 Java 8
- reactjs - Next js getServerSideProps 有时不会被调用
- linux - 用 iptables 发送 smtp
- javascript - 发送带有随机字符串的请求不起作用
- mysql - MySQL 关键字别名
- sencha-architect - 如何通过试用 Sencha Ext JS 获得 Sencha Architect?
- python - 包装一个计算库以实现另一个