Not sure if this is the most efficient method but one idea would be to use the CreateTextFile method of the FileSystemObject
, to create another file you can write to.
I've tested this on a small file and appears to be working as expected.
Modified after answer accepted to avoid .ReadLine
and .WriteLine
loops
Sub FindLines()
'Declare ALL of your variables :)
Const ForReading = 1 '
Const fileToRead As String = "C:\Users\david_zemens\Desktop\test.txt" ' the path of the file to read
Const fileToWrite As String = "C:\Users\david_zemens\Desktop\test_NEW.txt" ' the path of a new file
Dim FSO As Object
Dim readFile As Object 'the file you will READ
Dim writeFile As Object 'the file you will CREATE
Dim repLine As Variant 'the array of lines you will WRITE
Dim ln As Variant
Dim l As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
Set readFile = FSO.OpenTextFile(fileToRead, ForReading, False)
Set writeFile = FSO.CreateTextFile(fileToWrite, True, False)
'# Read entire file into an array & close it
repLine = Split(readFile.ReadAll, vbNewLine)
readFile.Close
'# iterate the array and do the replacement line by line
For Each ln In repLine
ln = IIf(InStr(1, ln, "ant", vbTextCompare) > 0, Replace(ln, "t", "wow"), ln)
repLine(l) = ln
l = l + 1
Next
'# Write to the array items to the file
writeFile.Write Join(repLine, vbNewLine)
writeFile.Close
'# clean up
Set readFile = Nothing
Set writeFile = Nothing
Set FSO = Nothing
End Sub
Then, depending on whether you want to get rid of the "original" file you could do something like:
'# clean up
Set readFile = Nothing
Set writeFile = Nothing
'# Get rid of the "old" file and replace/rename it with only the new one
Kill fileToRead
Name fileToWrite As fileToRead
End Sub