Text file in VBA: open / find replace / save / close file

Here is the pseudo code for what I hope to do:

Open text File

Find "XXXXX" and Replace with "YYYY"

Save text File As

Close text file

This is what I still have

Private Sub CommandButton1_Click()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\filelocation"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, "DIM A", "1.75")
sTemp = Replace(sTemp, "DIM B", "2.00")
sTemp = Replace(sTemp, "DIM C", "3.00")
sTemp = Replace(sTemp, "DIM D", "4.00")

'Save txt file as (if possible)

iFileNum = FreeFile
Open sFileName For Output As iFileNum

Print #iFileNum, sTemp

Close iFileNum

'Close Userform
Unload UserForm1

End Sub

But instead of overwriting the original text file, I want to “save as” to a new file.

+5
source share
5 answers

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier ( C:\filelocation).

If you want a fantasy and show the real Save As dialog box, you can do this instead:

sFileName = Application.GetSaveAsFilename()
+5
source

Why turn on Notepad?

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\Temp\test.txt"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, "THIS", "THAT")

iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum

End Sub
+8
source

, ...

; , FileSystemObject:

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
+3

, acrosse .

" "

... ... .

( Application.GetSaveAsFilename())

** **

, /

. ( )

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

:

newFilename = replace (sFilename, ".txt", ".csv" )

newFilename = replace (sFilename, ".", "_edit." ) differrent

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

, , txt ,

, :)

0

"ReadedData"

Open "C:\satheesh\myfile\Hello.txt" For Input As #1

do until EOF(1)   

       Input #1, ReadedData
loop**
-1

All Articles