Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

How to find and replace a text in multiple Word documents using VBA

I am seeking help to find and replace texts in multiple Word documents. I have a code to do that in only one document but don't know how to loop through all documents in the same folder. Here is the code:

Sub storyrangesearch()
    
For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = " Of "
        .Replacement.Text = " of "
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = True
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With
Next myStoryRange
End Sub
question from:https://stackoverflow.com/questions/65852638/how-to-find-and-replace-a-text-in-multiple-word-documents-using-vba

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For example:

Sub Demo()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, wdDoc
strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "*.doc", vbNormal)
While strFile <> ""
  Set wdDoc = Documents.Open(FileName:=strFolder & "" & strFile, AddToRecentFiles:=False, Visible:=False)
  With wdDoc
    With .Range.Find
      .Text = " Of "
      .Replacement.Text = " of "
      .Format = False
      .Forward = True
      .MatchCase = True
      .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
    End With
    .Close SaveChanges:=True
  End With
  strFile = Dir()
Wend
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub
 
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function

To extend the processing to sub-folders, see: https://www.msofficeforums.com/117894-post9.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...