我知道问题标题不清楚,所以希望我能澄清:
考虑以下VBA脚本(由M.Paige编写):
Sub rem_space()
Set myRange = ActiveDocument.Content
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
这将用":"替换":"的每个实例。
问题是,我有任意数量的空间,必须多次运行才能消除":"的所有实例。
那么,修改此VBA脚本以使其只运行一次,从而在删除冒号之前产生任意数量的任意空格的最佳方法是什么呢。
VBA脚本应该是递归的吗?
我应该搜索文档以确定冒号前的最大空格,然后运行VBA脚本该次数吗?
在for循环中运行VBA脚本(比如说100次)会抓住一切吗?
什么是最容易实现的解决方案?
这个重复了对.Execute
的调用,但不依赖于无限循环。
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
Do While .Found
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
Loop
End With
或者可能是Do...Loop While
循环。
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
Do
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
Loop While .Found
End With
试试这个:
Sub rem_space()
Dim myRange As Range
Set myRange = ActiveDocument.Content
Do While True
With myRange.Find
.Text = " :"
.Replacement.Text = ":"
If (Not .Execute(Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue)) Then Exit Do
End With
Loop
End Sub
它使用Do While True
无限循环,然后只有当对.Execute
的调用返回false时才退出。