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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With