Search Replace in Text files - Loop to Next Search & Replacement
good sunday,
i am tryign to do search and replacements in text files
i found this
it only replaced the first instance and didnt move on to the next
http://www.vbaexpress.com/forum/show...m-Control-File
Code:
Sub repltxtfiles()
Const ForReading = 1
Const ForWriting = 2
Dim objFSO As Object
Dim objFile As Object
Dim fName As String
Dim i As Long, LR As Long
Dim strText As String, strNewText As String
LR = ThisWorkbook.ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Set objFSO = CreateObject("Scripting.FileSystemObject")
For i = 2 To LR
fName = ThisWorkbook.ActiveSheet.Range("A" & i) & "\" & Range("B" & i)
If Not objFSO.FileExists(fName) Then GoTo Nexti
Set objFile = objFSO.OpenTextFile(fName, ForReading)
strText = objFile.ReadAll
objFile.Close
'Case insensitive
strNewText = Replace(strText, Range("C" & i), Range("D" & i), Compare:=vbTextCompare)
'Case sensitive
'strNewText = Replace(strText, Range("C" & i), Range("D" & i), Compare:=vbBinaryCompare)
Set objFile = objFSO.OpenTextFile(fName, ForWriting)
objFile.WriteLine strNewText
objFile.Close
Set objFile = Nothing
Nexti:
Next i
Set objFSO = Nothing
End Sub
Private Sub CommandButton1_Click()
repltxtfiles
End Sub
Worksheet set up as below
File Path (A) | File Name (B) | Search (C) | Replacement (D)
C:\Users\DJ\Desktop\ a.txt hello hi
apple cherry
I am wondering why only the first replacement and not all the others set up
thank you for your help