troubleshooting Question

Getting error while doing mass find n replace in Sub folder

Avatar of Milan Soni
Milan Soni asked on
Microsoft OfficeMicrosoft Word
4 Comments1 Solution129 ViewsLast Modified:
When I am running the below code for n number of document in a folder then it works fine but when i inclde more sub folder with the docs then it shows the error
"Run-time error '5792':
The files appears to be corrupted.

Can someone help? I am not much familier with coding.

Public Sub MassReplace()
    With ApplicationFileSearch
        .LookIn = "C:\Users\milans\Desktop\Procedure - Test"             ' where to search
        .SearchSubFolders = True    ' search the subfolders
        .FileName = "*.docx"         ' file pattern to match

        ' if more than one match, execute the following code
        If .Execute() > 0 Then
            ' for each file you find, run this loop
            For i = 1 To .FoundFiles.Count
                ' open the file based on its index position
                Documents.Open FileName:=.FoundFiles(i), ReadOnly:=False   'I tracked error it is the line where erorr is coming

                ' search and replace the address
                Selection.Find.ClearFormatting
                Selection.Find.Replacement.ClearFormatting
                With Selection.Find
                    .Text = "ABC"
                    .MatchCase = True
                    .Replacement.Text = "XYZ"
                End With
                Selection.Find.Execute Replace:=wdReplaceAll


                ' save and close the current document
                ActiveDocument.Close wdSaveChanges
            Next i
        Else
            ' if the system cannot find any files
            ' with the .doc extension
            MsgBox "No files found."
        End If
    End With
End Sub
ASKER CERTIFIED SOLUTION
Neil Fleming
Consultant and developer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros