word multiple document substitutions

Keywords: Programming

Replace the contents of all documents in the folder. Documents that need to be replaced cannot be opened. Use macro to replace them in batches. The test is word2016
Adapted from the author of the short book https://www.jianshu.com/p/9d348b8015b6? UTM ﹣ campaign = maleskin & UTM ﹣ content = note & UTM ﹣ medium = SEO ﹣ notes & UTM ﹣ source = recommendation
Step 1: create a new Word and open it, click toolbar view - macro (inverted triangle at the bottom) - view macro

Step 2: fill in a file name and click Create

Step 3: copy the following code, replace the newly created macro code (don't delete the previous macro by mistake), pay attention to the code format, and save

Sub CommandButton1_Click()
Application.ScreenUpdating = False  'Turn off screen flash
Dim myFile$, myPath$, i%, myDoc As Object, myAPP As Object, txt$, Re_txt$
Set myAPP = New Word.Application
With Application.FileDialog(msoFileDialogFolderPicker) 'Allow users to select a folder
    .Title = "Select destination folder"
    If .Show = -1 Then
        myPath = .SelectedItems(1) 'Read the selected file path
    Else
        Exit Sub
    End If
End With
myPath = myPath & ""
myFile = Dir(myPath & "\*.docx")
txt = InputBox("Text to replace:")
Re_txt = InputBox("Replace it with:")
myAPP.Visible = True 'Show open documents or not
Do While myFile <> "" 'File is not empty
Set myDoc = myAPP.Documents.Open(myPath & "\" & myFile)
If myDoc.ProtectionType = wdNoProtection Then 'Protected or not
    With myDoc.Content.Find
        .Text = txt
        .Replacement.Text = Re_txt
        .Forward = True
        .Wrap = 2
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=2
    End With
End If
myDoc.Save
myDoc.Close
myFile = Dir
Loop
myAPP.Quit 'Turn off the temporary process
Application.ScreenUpdating = True
MsgBox ("All replaced!")
End Sub

Step 4: go back to the Word document, click View - macro, and run the macro

Step 5: pop up window, select the folder to replace the document (the file name will not be displayed under the folder)

Step 6: text to replace

Step 7: replace with

Step 8: it needs to wait for a while, and the display shows that the replacement is complete

Posted by escabiz on Thu, 09 Jan 2020 06:08:34 -0800