【发布时间】:2020-07-24 15:34:29
【问题描述】:
我正在尝试对类似字符串使用查找和替换来运行 Word VBA 宏。它可以完美地与跟踪关闭,但在跟踪时,我会得到像 CompanyCompany 这样的重复。似乎仅在打开跟踪时才同时执行查找/替换。我有数百份文件要查看,因此必须进行跟踪。有关如何避免这种情况的任何建议?
Private Sub document_open()
With ActiveDocument
.TrackRevisions = True
.ShowRevisions = True
End With
Dim rngStory As Word.Range
Dim lngValidate As Long
lngValidate = ActiveDocument.Sections(1).Headers(1).Range.StoryType
'Iterate through all story types in the current document.
For Each rngStory In ActiveDocument.StoryRanges
'Iterate through all linked stories.
Do While .Found = True
With rngStory.Find
.ClearFormatting
.IgnoreSpace = True
.MatchCase = False
.Text = "Corporation"
.Replacement.ClearFormatting
.Replacement.Text = "Company"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
.ClearFormatting
.IgnoreSpace = True
.MatchCase = False
.Text = "Corp."
.Replacement.ClearFormatting
.Replacement.Text = "Company"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
.ClearFormatting
.IgnoreSpace = True
.MatchCase = False
.Text = "Corp"
.Replacement.ClearFormatting
.Replacement.Text = "Company"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
'Get next linked story (if any).
Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
End Sub
【问题讨论】:
-
Do While .Found = True- 目前尚不清楚With块变量是什么限定了这个.Found成员调用。或者With rngStory.Find指令应该在Do While...Loop循环体内?请注意,Do While...Loop Until是非法的,看起来您这里有两个不同的重叠版本的代码。如前所述,此代码无法编译,更不用说产生不正确的结果。我不熟悉 Word 对象模型,但是否有可能需要在 3 个不同的通道中完成 3 个替换? “Corp”会在“Corp.”中找到。和“公司”……