我尝试使用 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
您需要迭代形状(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