Link to home
Start Free TrialLog in
Avatar of Eduardo Aviles
Eduardo AvilesFlag for United States of America

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

Open in new window

Any help would be most appreciated.
Avatar of Bill Prew
Bill Prew

What is the error exactly?


»bp
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

Open in new window

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

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Eduardo Aviles

ASKER

Thank you Bill Prew and aikimark, the code you both provided were awesome.  Thank you both for your inputs.
Thank you, Bill Prew  the code was clean and very efficient works like a charm.