Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text file in VBA: Open/Find Replace/SaveAs/Close File

Tags:

text-files

vba

Here is pseudocode for what I am hoping to do:

Open text File

Find "XXXXX" and Replace with "YYYY"

Save text File As

Close text file

This is what I have so far

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.

like image 776
Russell Saari Avatar asked May 03 '12 15:05

Russell Saari


People also ask

How do I use find and replace in VBA?

Example #1 – VBA Find and Replace the WordStep 1: First, mention the Range of cells we are replacing. In this example, the range is from A1 to B15 so the code will be Range (“A1: B15”). Step 2: Now, put a dot to see the IntelliSense list. Step 3: Select the Replace method from the IntelliSense list.

How do I read a text file into a macro in Excel?

Step 1: Open Excel. Step 2: Add a shape (Read Text File) to your worksheet . Step 3: Right-click on “Read Text file” and “Assign Macro..” Step 7: Adjust column width in your excel file.


1 Answers

Guess I'm too late...

Came across the same problem today; here is my solution using 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
like image 131
Bojie Shuai Avatar answered Sep 27 '22 15:09

Bojie Shuai