0

I am trying to create a macro in order to do a mass find and replace across multiple word documents. I have found this one on the net and altered it to also apply for graphics however I keep getting a run time error (5174) saying that the file could not be found (even though it is definitely in the folder).

I believe the issue is this: support.microsoft.com/en-us/kb/212664 but am having a bit of trouble implementing it into my Macro as simply adding ".docx" after every single Fname doesn't seem to work.

I have limited experience with Macros so apologies if this is a novice question.

Any help would be greatly appreciated.

Thanks.

Sub ReplaceText()
Dim Directory As String
Dim FType As String
Dim FName As String

Directory = "C:\Users\pieria\Desktop\TempPics"
FType = "*.docx"

ChDir Directory
FName = Dir(FType)
' for each file you find, run this loop
Do While FName <> ""
' open the file
Documents.Open FileName:=FName  '<--Error is supposedly here 

' search and replace the company name
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "CompanyA"
    .MatchCase = True
    .Replacement.Text = "CompanyB"
End With
Selection.Find.Execute Replace:=wdReplaceAll

' save and close the current document
ActiveDocument.Close wdSaveChanges

' look for next matching file
FName = Dir
Loop 
End Sub
0

I expect the current instance not being aware of the ChDir you did. You better specify the full path when opening the file:

 ' open the file
 Documents.Open FileName:= Directory & "\" & FName 

I concatenate the string in Directory and FName with the & operator.

So if Directory contains C:\Users\pieria\Desktop\TempPics and FName contains First.docx with & you create a new string C:\Users\pieria\Desktop\TempPics\First.docx

Notice the \ I added between the directory name and the filename...

3
  • I have another issue that you may be able to help with... Im also trying to do a "find and replace for images in footers. The code I have only seems to work for images not in footers! – Antonio Oct 1 '15 at 11:55
  • I cant seem to add it in the comment section so will open another thread and post the link – Antonio Oct 1 '15 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.