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)