【问题标题】:Word VBA duplicating find and replace with trackingWord VBA 重复查找和替换与跟踪
【发布时间】: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.”中找到。和“公司”……

标签: vba ms-word


【解决方案1】:

以下应该可以工作

Private Sub document_open()

With ActiveDocument
    .TrackRevisions = True
    .ShowRevisions = True
End With

Dim story As Range

For Each story In ActiveDocument.storyRanges
    Do While Not story Is Nothing
        With story.Find
            .Replacement.text = "Company"
            .Execute "Corporation", Replace:=wdReplaceAll
            .Execute "Corp.", Replace:=wdReplaceAll
            .Execute "Corp", Replace:=wdReplaceAll
        End With
        
        Set story = story.NextStoryRange
    Loop
Next

End Sub

【讨论】:

  • 我能够切换顺序以使其工作:执行“公司”,替换:=wdReplaceAll .执行“公司”,替换:=wdReplaceAll .执行“公司”,替换:= wdReplaceAll . 执行“公司”,替换:=wdReplaceAll••••ˇˇˇˇ
  • 不幸的是,在更大的规模和更多的字符串中,这不起作用。它仍然失败并重复这个词。
猜你喜欢
  • 2012-03-08
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 2018-01-18
  • 2014-04-06
  • 2018-03-24
  • 1970-01-01
  • 2012-11-13
相关资源
最近更新 更多