将查找和替换方法应用于 MSWordDoc.Range 不知怎的并没有覆盖整个文档

问题描述 投票:0回答:1

我尝试使用 VBA 使用通配符替换某些字符串。 但是,Shapes 中的文本与 FindText 中指定的格式相同,但不知何故在 Replace 方法中幸存下来。

我也尝试过

RngToFind.WholeStory
,结果相同。如何将查找和替换应用于文档中的所有内容?

顺便说一句,如果我手动替换,结果很好,不会出现上述问题。所以我认为关键是Range对象的声明。

Dim MSWordApp As Object, MSWordDoc As Object, RngToFind As Object

Set MSWordApp = CreateObject("Word.Application")
Set MSWordDoc = MSWordApp.Documents.Open("C:\Users\User\Desktop\123.docx")
Const wdReplaceAll As Long = 2
Const wdSaveChanges As Long = -1

Set RngToFind = MSWordDoc.Range
With RngToFind.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Execute FindText:="Doc*.??", MatchWildcards:=True, ReplaceWith:="", Replace:=wdReplaceAll
End With
Set RngToFind = Nothing
MSWordDoc.Close SaveChanges:=wdSaveChanges
MSWordApp.Quit
Set MSWordDoc = Nothing
Set MSWordApp = Nothing
excel vba ms-word
1个回答
0
投票

您需要迭代形状(Word 宏示例):

Option Explicit

Sub Macro4()
  Dim v As Variant
  For Each v In ActiveDocument.Shapes
    With v.TextFrame.TextRange.Find
      .Text = "Doc*.??"
      .Replacement.Text = ""
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchAllWordForms = False
      .MatchSoundsLike = False
      .MatchWildcards = True
      .Execute Replace:=wdReplaceAll
    End With
  Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.