PDA

View Full Version : Solved: USE OF REPLACE COMMAND ON CONTENTS OF TEXT FILE.



andysuth
07-18-2007, 01:07 AM
Hi,

Continuing on from previous thread, I'm trying to take a text file (.txt) and change one string from it (several times) to another and then save it as a new .txt file.

I'd thought I could use:


Dim vFF1 As Long, vNIStep As String, vPBody As String, vOIStep As String

versionint = 1002
vNIStep = "C:\Path\" & versionint & "_inteps.txt"
vOIStep = "C:\Path\inteps.txt"
vPBody = Replace(vOIStep, "1001", versionint)
vFF1 = FreeFile
Open vNIStep For Output As #vFF1
Print #vFF1, vPBody
Close #vFF1


But this only writes the path name in the text file (duh!),

I know the replace command works (because I wrote the text to be replaced at the end of the file path and it correctly replaced it twice), but not sure if I have to read the whole file in, and then run it as a string through the replace command.

It's only a short file (40 lines long/ about 50 Chr/lne), but I'm not even sure how to read the file in.

Any ideas?

Cheers,

-AS

Ebrow
07-18-2007, 05:21 AM
This little function will allow you to replace any text within the file, you can call the code as many times as you need to replace text. The input and output path can be the same or different (if you wish to keep the orginial as backup)


Function myReplaceFileText(myFilePathInput As String, myFilePathOutput As String, myReplaceString As String, myString As String)

Dim myFileString As String

Open myFilePathInput For Input As #1
myFileString = Input(LOF(1), 1)
Close #1

myFileString = Replace(myFileString, myReplaceString, myString, Compare:=vbTextCompare)

Open myFilePathOutput For Output As #2
Print #2, myFileString
Close
End Function



Sub Test()

Dim myFilePathInput As String
Dim myFilePathOutput As String
Dim myReplaceString As String
Dim myString As String

myFilePathInput = "C:\Test\test.txt"
myFilePathOutput = "C:\Test\test.txt"
myReplaceString = "TEST"
myString = "ITWORKS"

Call myReplaceFileText(myFilePathInput, myFilePathOutput, myReplaceString, myString)

End Sub

andysuth
07-19-2007, 09:05 AM
Thanks for the help, I was halfway through a solution when you wrote, so I finished and checked it, this works well:


Dim vFF As Long, vNIStep As String, vBody As String, vIStep As String, vOIStep As String

vNIStep = "C:\path\" & versionint & "_istps.txt"
vOIStep = "C:\path\istps.txt"

vFF = FreeFile
Open vOIStep For Binary As #vFF
vBody = Space$(LOF(vFF))
Get #vFF, , vBody
Close #vFF
vIStep = Replace(vBody, "1001", versionint)
Open vNIStep For Output As #vFF
Print #vFF, vIStep
Close #vFF


Thanks for your help. I think this thread can be closed, but don't know how to do that.

-AS