Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

find and replace text in multiple word documents using automator

hi,

i am looking to replace a certain word in multiple files on Word 365. When i use the find and replace tool, only one file is changed and all the others remain the same. My current workflow is; Get Specified Finder Items -> Open Finder Items -> Find and replace Text in Word Documents -> Save Word Docs -> Close word Doc.

In the above workflow, only 1 file is being changed and saved. the rest remain open and nothing happens

MacBook Pro (Retina, 15-inch, Mid 2015), macOS Sierra (10.12.5)

Posted on Jul 7, 2018 12:59 AM

Reply

Similar questions

13 replies

Jul 9, 2018 7:12 PM in response to Dheer201

Macro was a windows only macro. Microsoft didn't implement the same file selection on macOS as Windows. Ported the windows only macro found here:

How to Find and Replace Contents in Multiple Word Documents - Data Recovery Blog


Restrictions:

1) all word documents must be in the same folder

2) All documents in the folder must be word documents.

3) I did minimal testing.

4) Please create a backup of your system. If you want to live dangerously, just back up all your word documents. Please test this code for functionality.


I tested this in macOS Yosemite with Office 2011.


The folder format is like thus.

Macintosh HD:Users:mac:Documents:wordMultiwordCHange:


' Find and Replace a string in all documents in a folder
Sub FindAndReplaceInFolder()
  Dim objDoc As Document
  Dim strFile As String
  Dim strFolder As String
  Dim strFindText As String
  Dim strReplaceText As String
  Dim fileString As String
  Dim MyDir As String


Debug.Print "beginning of program...." & Format(Now(), "dd/mm/yyyy hh:mm:ss.ms")

  ' pop up input boxes for user to enter folder path, the finding and replacing texts.
  ' Path needs to be like this. Notice not colon in front, but required in back.
  ' Macintosh HD:Users:mac:Documents:wordMultiwordCHange:
  strFolder = InputBox("Enter folder path here:")

  Debug.Print "strFloder is " & strFolder

  strFile = Dir(strFolder)
  Debug.Print "strFile is " & strFile

  strFindText = InputBox("Enter finding text here:")
  Debug.Print "strFindText is " & strFindText
  strReplaceText = InputBox("Enter replacing text here:")
  Debug.Print "strReplaceText is " & strReplaceText

  '  Open each file in the folder to search and replace texts. Save and close the file after the action.
  While strFile <> ""
    Debug.Print "strFile is " & strFile

    'Skip hidden folder format file.
    If strFile = ".DS_Store" Then GoTo NextIteration

    'Real work
    fileString = strFolder & strFile
    Debug.Print "fileString is " & fileString
    Set objDoc = Documents.Open(fileName:=fileString)

    With objDoc
      With Selection
        .HomeKey Unit:=wdStory
        With Selection.Find
          .Text = strFindText
          .Replacement.Text = strReplaceText
          .Forward = True
          .Wrap = wdFindContinue
          .Format = False
          .MatchCase = False
          .MatchWholeWord = False
          .MatchWildcards = False
          .MatchSoundsLike = False
          .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
      End With
      objDoc.Save
      objDoc.Close
    End With

NextIteration:
     strFile = Dir()
  Wend

End Sub  ' FindAndReplaceInFolder()



User uploaded file

Aug 25, 2018 12:21 AM in response to rccharles

Better error processing & Word documents only.

When running, turn on the immediate window.

control + command + g

Should you need to report an error:

-1- Post the complete error message

-2- you should turn on the immediate window and post back the results.



    Sub FindAndReplaceInFolderVersion2()

    ' Find and Replace a string in all documents in a folder
    '
    '  VBA forums
    '     https://www.mrexcel.com/forum/index.php
    '     http://www.vbaexpress.com/forum/forum.php
    '
    '
    '  Descriptions of error processing
    '   https://msdn.microsoft.com/en-us/library/6xx36z07(v=vs.100)?cs-save-lang=1&cs-lang=vb#code-snippet-1
    '   https://www.fmsinc.com/free/newtips/VBA/ErrorHandling/LineNumber.html
    '
    ' Permission is hereby granted, free of charge, to any person obtaining a copy
    ' of this software and associated documentation files (the "Software"), to deal
    ' in the Software without restriction, including without limitation the rights
    ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    ' copies of the Software, and to permit persons to whom the Software is
    ' furnished to do so, subject to the following conditions:
    '
    ' The above copyright notice and this permission notice shall be included in all
    ' copies or substantial portions of the Software.
    '
    ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    ' SOFTWARE.
    '


      Dim objDoc As Document
      Dim strFile As String
      Dim fileString As String
      Dim MyDir As String
      Dim strError As String
      Dim message, title, defaultValue As String
      Dim strFolder, strReplaceText   As String
      Dim docStringFind As String
      Dim fileExtension As String
      Dim boxTheMsg As String
      Dim Msg As String

10   Debug.Print "...===...beginning of program....===..." & Format(Now(), "dd/mm/yyyy hh:mm:ss.ms")

      ' pop up input boxes for user to enter folder path, the existing text and replacement text.
      ' Path needs to be like this. Notice no colon in front, but required in back.
      ' Macintosh HD:Users:mac:Documents:word global change:wordMultiwordChange:

20  message = "Enter folder path here. " & vbNewLine & "Example:" & vbNewLine & "Macintosh HD:Users:mac:Documents:"  ' Set prompt.
30  title = "Change All Documents"  ' Set title.
40  defaultValue = "Macintosh HD:Users:mac:"   ' Set default value.
    ' Display message, title, and default value.
50  strFolder = InputBox(message, title, defaultValue)
60  If Len(strFolder) = 0 Then
70    MsgBox ("Cancelled inputing file path.")
80    Exit Sub
90  End If
100 Debug.Print Len(strFolder)

110    Debug.Print "strFolder is " & strFolder

120    strFile = Dir(strFolder)
130    Debug.Print "strFile is " & strFile

140    docStringFind = InputBox("Enter finding text here:")
150       If Len(docStringFind) = 0 Then
160           MsgBox ("Cancelled Find string input.")
170           Exit Sub
180       End If
190    Debug.Print "docStringFind  is " & docStringFind

200    strReplaceText = InputBox("Enter replacing text here:")
210       If Len(strReplaceText) = 0 Then
220           MsgBox ("Cancelled Replace string input.")
230           Exit Sub
240       End If
250   Debug.Print "strReplaceText is " & strReplaceText

        '  Open each file in the folder to search and replace texts. Save and close the file after the action.
260    While strFile <> ""
              On Error GoTo ErrHandler
270           Debug.Print "--> strFile is " & strFile

        'Skip hidden folder format file.
280     If strFile = ".DS_Store" Then GoTo NextIteration

        'Retrieve File Extension
290    fileExtension = Right(strFile, Len(strFile) - InStrRev(strFile, "."))
300    Debug.Print "fileExtension is " & fileExtension
310    If (LCase(fileExtension) <> "doc" And LCase(fileExtension) <> "docx") Then
320      Debug.Print "skipping " & strFile & " because it doesn't have .doc or .docx entension. "
330      GoTo NextIteration
340    End If

        'Real work
350     fileString = strFolder & strFile
360     Debug.Print "fileString is " & fileString
370     Set objDoc = Documents.Open(fileName:=fileString)

380     With objDoc
390       With Selection
400         .HomeKey Unit:=wdStory
410         With Selection.Find
420           .Text = docStringFind
430           .Replacement.Text = strReplaceText
440           .Forward = True
450           .Wrap = wdFindContinue
460           .Format = False
470           .MatchCase = False
480           .MatchWholeWord = False
490           .MatchWildcards = False
500           .MatchSoundsLike = False
510           .MatchAllWordForms = False
520         End With
530         Debug.Print "  Text is " & Selection.Find.Text & "  Replacement.Text Is " & Selection.Find.Replacement.Text
540         Selection.Find.Execute Replace:=wdReplaceAll
550       End With
560       Debug.Print "save & close"
570       objDoc.Save
580       objDoc.Close
590     End With

600     GoTo NextIteration: ' skip error code

ErrHandler:
    
630     Debug.Print "  --- error --- "
640     boxTheMsg = "An error occured , while processing document:" & vbCrLf & "  " & strFile & vbCrLf
650     boxTheMsg = boxTheMsg & "Error Line: " & Erl & vbCrLf
670     boxTheMsg = boxTheMsg & "Error: (" & Str(Err.Number) & " ) " & vbCrLf & Err.Description
680     Debug.Print "boxTheMsg is " & boxTheMsg
690     MsgBox boxTheMsg, vbCritical

695     On Error GoTo -1  '  clear error .  clears err structure
        'try going to the next file.

NextIteration:
700      strFile = Dir()

710   Wend


    End Sub  ' FindAndReplaceInFolder(Version2)

Jul 16, 2018 4:09 AM in response to rccharles

hi,

Thanks again for your reply. I have been trying since the past couple of days to make this work. but it hasn't been happening.

I am getting a Run Time error '5174' when i ran your code purely.



The location of the files is Macintosh HD/Users/dheer/DOCS/RM1.


The files within the folder are all word with extensions of .doc and .docx

Also, all the file names are different. i even tried adding the previous string of code from the link you shared with me.

i replaced

strFile = Dir(strFolder) from your code with

strFile = Dir(strFolder & "\" & "*.docx" & "*.doc", vbNormal) . {Also, added &".doc" as it was not there in the original string of code.}


It yet did not work when i ran the code.

The file names in the folder have spaces, dots, - , and numbers. (Word document names)


Is there some mistake i am making?


Regards,

Dheer

Jul 16, 2018 11:09 AM in response to Dheer201

I'm running 10.10.5 with word 2011. Don't know if this would make a difference.

strFile = Dir(strFolder & "\" & "*.docx" & "*.doc", vbNormal) . {Also, added &".doc" as it was not there in the original string of code.}

mac version of word doesn't support file selection [ "*.docx" ], hence the requirement to have only word documents in the folder. I could manually code this if necessary, but that's a later enhancement.


as for as the issue, you should turn on the immediate window and post back the results. Word isn't does seem to give the statement in error, so I add more debug.print statement to track down the error.


' Find and Replace a string in all documents in a folder
Sub FindAndReplaceInFolder()
  Dim objDoc As Document
  Dim strFile As String
  Dim strFolder As String
  Dim strFindText As String
  Dim strReplaceText As String
  Dim fileString As String
  Dim MyDir As String
  
  
Debug.Print "beginning of program...." & Format(Now(), "dd/mm/yyyy hh:mm:ss.ms")

  ' pop up input boxes for user to enter folder path, the finding and replacing texts.
  ' Path needs to be like this. Notice no colon in front, but required in back.
  ' Macintosh HD:Users:mac:Documents:wordMultiwordCHange:
  strFolder = InputBox("Enter folder path here:")

  Debug.Print "strFolder is " & strFolder

  strFile = Dir(strFolder)
  Debug.Print "strFile is " & strFile

  strFindText = InputBox("Enter finding text here:")
  Debug.Print "strFindText is " & strFindText
  strReplaceText = InputBox("Enter replacing text here:")
  Debug.Print "strReplaceText is " & strReplaceText

  '  Open each file in the folder to search and replace texts. Save and close the file after the action.
  While strFile <> ""
    Debug.Print "strFile is " & strFile
  
    'Skip hidden folder format file.
    If strFile = ".DS_Store" Then GoTo NextIteration
  
    'Real work
    fileString = strFolder & strFile
    Debug.Print "fileString is " & fileString
    Set objDoc = Documents.Open(fileName:=fileString)
  
    With objDoc
      With Selection
        .HomeKey Unit:=wdStory
        With Selection.Find
          .Text = strFindText
          .Replacement.Text = strReplaceText
          .Forward = True
          .Wrap = wdFindContinue
          .Format = False
          .MatchCase = False
          .MatchWholeWord = False
          .MatchWildcards = False
          .MatchSoundsLike = False
          .MatchAllWordForms = False
        End With
        Debug.Print "  Text is " & Selection.Find.Text & "  Replacement.Text Is " & Selection.Find.Replacement.Text
        Selection.Find.Execute Replace:=wdReplaceAll
      End With
      Debug.Print "save & close"
      objDoc.Save
      objDoc.Close
    End With
  
NextIteration:
     strFile = Dir()
  Wend

End Sub  ' FindAndReplaceInFolder()

Jul 17, 2018 9:25 PM in response to rccharles

I add some error recovery the script. Should skip over non .doc and .docx files.


supposedly adding line number will result in getting line numbers in error messages, but that don't work for me. add wimpie "I'm not responsible for anything."


Sub FindAndReplaceInFolderVersion2()
'  Find and Replace a string in all documents in a folder
'
'  VBA forums
'     https://www.mrexcel.com/forum/index.php
'
'     http://www.vbaexpress.com/forum/forum.php
' Copyright (c) 2018 rccharles
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
    '
    
    
      Dim objDoc As Document
      Dim strFile As String
      Dim fileString As String
      Dim MyDir As String
      Dim strError As String
      Dim message, title, defaultValue As String
      Dim strFolder, strReplaceText   As String
      Dim docStringFind As String
      Dim fileExtension As String
      Dim boxTheMsg As String
    
    
    
10   Debug.Print "...===...beginning of program....===..." & Format(Now(), "dd/mm/yyyy hh:mm:ss.ms")
    
      ' pop up input boxes for user to enter folder path, the existing text and replacement text.
      ' Path needs to be like this. Notice no colon in front, but required in back.
      ' Macintosh HD:Users:mac:Documents:wordMultiwordChange:
    
20  message = "Enter folder path here. " & vbNewLine & "Example:" & vbNewLine & "Macintosh HD:Users:mac:Documents:"  ' Set prompt.
30  title = "Change All Documents"  ' Set title.
40  defaultValue = "Macintosh HD:Users:mac:"   ' Set default value.
    ' Display message, title, and default value.
50  strFolder = InputBox(message, title, defaultValue)
60  If Len(strFolder) = 0 Then
70    MsgBox ("Cancelled inputing file path.")
80    Exit Sub
90  End If
100 Debug.Print Len(strFolder)
    
110    Debug.Print "strFolder is " & strFolder
    
120    strFile = Dir(strFolder)
130    Debug.Print "strFile is " & strFile
    
140    docStringFind = InputBox("Enter finding text here:")
150       If Len(docStringFind) = 0 Then
160           MsgBox ("Cancelled Find string input.")
170           Exit Sub
180       End If
190    Debug.Print "docStringFind  is " & docStringFind
    
200    strReplaceText = InputBox("Enter replacing text here:")
210       If Len(strReplaceText) = 0 Then
220           MsgBox ("Cancelled Replace string input.")
230           Exit Sub
240       End If
250   Debug.Print "strReplaceText is " & strReplaceText
    
        '  Open each file in the folder to search and replace texts. Save and close the file after the action.
260    While strFile <> ""
              On Error GoTo ErrHandler
270           Debug.Print "strFile is " & strFile
    
        'Skip hidden folder format file.
280     If strFile = ".DS_Store" Then GoTo NextIteration
    
        'Retrieve File Extension
290    fileExtension = Right(strFile, Len(strFile) - InStrRev(strFile, "."))
300    Debug.Print "fileExtension is " & fileExtension
310    If (fileExtension <> "doc" And fileExtension <> "docx") Then
320      Debug.Print "skipping " & strFile & " because it doesn't have .doc or .docx entension. "
330      GoTo NextIteration
340    End If
    
        'Real work
350     fileString = strFolder & strFile
360     Debug.Print "fileString is " & fileString
370     Set objDoc = Documents.Open(fileName:=fileString)
    
380     With objDoc
390       With Selection
400         .HomeKey Unit:=wdStory
410         With Selection.Find
420           .Text = docStringFind
430           .Replacement.Text = strReplaceText
440           .Forward = True
450           .Wrap = wdFindContinue
460           .Format = False
470           .MatchCase = False
480           .MatchWholeWord = False
490           .MatchWildcards = False
500           .MatchSoundsLike = False
510           .MatchAllWordForms = False
520         End With
530         Debug.Print "  Text is " & Selection.Find.Text & "  Replacement.Text Is " & Selection.Find.Replacement.Text
540         Selection.Find.Execute Replace:=wdReplaceAll
550       End With
560       Debug.Print "save & close"
570       objDoc.Save
580       objDoc.Close
590     End With
    
600     GoTo NextIteration: ' skip error code
    
ErrHandler:
        On Error GoTo -1  '  clear error 
610     strError = "While processing " & strFile & "   An error occured "
620     MsgBox strError
        '  https://www.fmsinc.com/free/newtips/VBA/ErrorHandling/LineNumber.html
630     Debug.Print "--- error --- " & strError
640     boxTheMsg = "While processing document " & strFile & "   An error occured ." & vbCrLf4
650     boxTheMsg = boxTheMsg & "Error Line: " & Erl & vbCrLf
670     boxTheMsg = boxTheMsg & "Error: (" & Err.Number & ") " & Err.Description
680     Debug.Print "boxTheMsg is " & boxTheMsg
690     'MsgBox boxTheMsg, vbCritical
        'try going to the next file.
    
NextIteration:
700      strFile = Dir()
    
710   Wend
    
    
    End Sub  ' FindAndReplaceInFolder(Version2)

Aug 30, 2018 10:59 PM in response to rccharles

I ran this script on office 2011 under yosemite 10.10.5. In High Sierra 10.13.6, it would not read certain directories when it read a directory it missed files in the directory.


what you need to do is to post back the immediate window, control + command + g, output. Explain what the issue is.


source:

https://pastebin.com/raw/fqqq5wPT


' To see the code and run, click on the Developer tab then click on the Macros icon.

'

' To see debug messages, open Immediate Window

' Word > View > Immediate Window

' control + command + g

'

' To run, click on the Blue triangle in the upper right of the Word window. [ hopefully ]


here is the output in the immediate window.


..===.===..beginning of program....=======...30/08/2018 19:50:12.812
current document name is Document2
length of foder name is 32  strFolder is Macintosh HD:Users:mac:multidocs
  modified strFolder is Macintosh HD:Users:mac:multidocs:
strFile is NEWS ALERT #2.docx
docStringFind  is the
strReplaceText is the

--> strFile is NEWS ALERT #2.docx
fileExtension is docx
fileString is Macintosh HD:Users:mac:multidocs:NEWS ALERT #2.docx
  Text is -->the<-- Replacement.Text Is -->the<--
  document updated
  saved
  closed

--> strFile is NEWS ALERT #3.docx
fileExtension is docx
fileString is Macintosh HD:Users:mac:multidocs:NEWS ALERT #3.docx
  Text is -->the<-- Replacement.Text Is -->the<--
  document updated
  saved
  closed

--> strFile is NEWS ALERT.docx
fileExtension is docx
fileString is Macintosh HD:Users:mac:multidocs:NEWS ALERT.docx
  Text is -->the<-- Replacement.Text Is -->the<--
  document updated
  saved
  closed

--> strFile is skippie
fileExtension is skippie
skipping skippie because it doesn't have .doc or .docx entension.

--> strFile is skippie.txt
fileExtension is txt
skipping skippie.txt because it doesn't have .doc or .docx entension.

find and replace text in multiple word documents using automator

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.