我最近在运行 word 宏(在本例中具体指搜索和替换操作)时注意到一个问题,即当激活跟踪更改时,它们没有预期的行为(激活它对我来说很有意义,这样我就可以更轻松地跟踪由于宏而发生在文档中的更改,从而更容易确定其性能)。我有以下代码(这只是一个演示问题的示例):
Sub test()
ActiveDocument.TrackRevisions = Not ActiveDocument.TrackRevisions
With Selection.Find
.Text = "(B)([0-9]{6})"
.Replacement.Text = "\1 \2"
.Wrap = wdFindContinue
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
.Text = "(organised)( )(under)"
.Replacement.Text = "\1 \3"
.Wrap = wdFindContinue
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
第一个 choice.find 的作用是查找如下数字
B666666
并将其替换为
B 666666
第二次搜索和替换的作用是找到文本中存在双空格的特定部分,并将其替换为单空格
organised under
更改为
organised under
这两个代码都有效。但如果我在运行代码之前使用
ActiveDocument.TrackRevisions = Not ActiveDocument.TrackRevisions
那么代码的第一部分结果是
"B666666 " 'thus it does nothing except for putting a space in front of the string
第二段代码执行以下操作
"organisedunder " 'thus it merges the two strings and puts a space in front of them.
有人可以解释这种行为的变化吗?除了不激活跟踪变更之外,是否还有其他方法可以防止这种情况发生?
解决方案? :
Sub EvenMoreTesting()
Selection.HomeKey Unit:=wdStory
With Selection
.Find.Text = "Stocks"
Do
Selection.HomeKey Unit:=wdStory
Found = .Find.Execute
If Found Then Selection.Range.HighlightColorIndex = wdYellow
If Found Then Selection.TypeText Text:="Sto"
Loop While Found
End With
End Sub