Eduardo Aviles
asked on
Replace multiple strings in word document
Hello Experts, I am hoping you can help with my dilemma. I have a directory with about 10k + Word files and I have to go through them all and find two strings and replace them. I tried writing a VbScript , but I am stuck with it. I am wondering if anyone can help me. here is the code I have so far, but when I for loop into the directory I get an error. I can get the first string to work, but not the second one
Option Explicit
Dim fso, objWord, objDoc, objShape, strFindText, strReplaceText, strFindText2, strReplaceText2, sPfolder, sFolder, x, colFiles,myStoryRange
Const wdReplaceAll = 2
Const msoTextBox = 17
Set fso = CreateObject("Scripting.FileSystemObject")
sPfolder = "C:\Scripts"
Set sFolder = fso.GetFolder(sPfolder)
Set colFiles = sFolder.Files
strFindText = "None"
strReplaceText = "Internal Use"
strFindText2 = "COPYRIGHT (c) 2017 "
strReplaceText2 = "COPYRIGHT (c) 2018 "
For each x in colFiles
Set objWord = CreateObject("Word.Application")
objWord.Visible = false
Set objDoc = objWord.Documents.Open("C:\Scripts\test.docx")
For Each objShape In objDoc.Shapes
If objShape.Type = msoTextBox Then
objShape.TextFrame.TextRange.Find.Execute _
strFindText, , , , , , , , , _
strReplaceText, wdReplaceAll
End If
If objShape.Type = msoTextBox Then
objShape.TextFrame.TextRange.Find.Execute _
strFindText2 , , , , , , , , , _
strReplaceText2, wdReplaceAll
End If
Next
Next
Any help would be most appreciated.
You can simplify your code like this:
For Each objShape In objDoc.Shapes
If objShape.Type = msoTextBox Then
objShape.TextFrame.TextRange.Find.Execute _
strFindText, , , , , , , , , _
strReplaceText, wdReplaceAll
objShape.TextFrame.TextRange.Find.Execute _
strFindText2 , , , , , , , , , _
strReplaceText2, wdReplaceAll
End If
Next
Perhaps more readable, would be: For Each objShape In objDoc.Shapes
If objShape.Type = msoTextBox Then
objShape.TextFrame.TextRange.Find.Execute _
FindText:=strFindText, ReplaceWith:=strReplaceText, Replace:=wdReplaceAll
objShape.TextFrame.TextRange.Find.Execute _
FindText:=strFindText2, ReplaceWith:=strReplaceText2, Replace:=wdReplaceAll
End If
Next
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you Bill Prew and aikimark, the code you both provided were awesome. Thank you both for your inputs.
ASKER
Thank you, Bill Prew the code was clean and very efficient works like a charm.
»bp