2

I am trying to replace 3 text from a text file.I tried this-

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Aron_", "Lori_")
strNewText1 = Replace(strText, "Aron", "Jason")   'Not working
strNewText2 = Replace(strText, "Sketa", "Skicia") 'Not working


Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForWriting)
objFile.WriteLine strNewText 
objFile.WriteLine strNewText1 'Not working
objFile.WriteLine strNewText2 'Not working


objFile.Close

i am not able to figure out how to do multiple replacement.The code working perfect for single replace function but not more than one...plz help

1 Answer 1

10

You need to call Replace on the results of the previous Replace:

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Aron_", "Lori_")
strNewText1 = Replace(strNewText, "Aron", "Jason")
strNewText2 = Replace(strNewText1, "Sketa", "Skicia")

Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForWriting)
objFile.WriteLine strNewText2 

objFile.Close


You could actually reuse a single variable, instead of having strNewText, strNewText1, strNewText2.

strText = Replace(strText, "Aron_", "Lori_")
strText = Replace(strText, "Aron", "Jason")
strText = Replace(strText, "Sketa", "Skicia")

and later:

objFile.WriteLine strText


Also, you might want to consider using regular expressions for matching multiple values at a time. (Search on SO for VBScript regular expressions or VBA regular expressions.)

Sign up to request clarification or add additional context in comments.

4 Comments

i tried - strNewText = Replace(strText, "Aron_", "Lori_") strNewText1 = Replace(strNewText, "Aron", "Jason") . but its not working..
What's not working? Are you getting an error, or is the file not being written, or is the text of the file not being changed?
only for the first Replace the file is being written and text is getting changed,but for the second replace the text is not getting changed..
Just saw your edited section, it is working fine now by using single variable...Thanks for your awsome responese and timely help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.