PDA

View Full Version : Search and Replace Macro for .txt files modification



afzalw
06-19-2013, 03:54 PM
I have this Macro which basicall reads the path from column A and search a string from Column B and Replace it with a String in Column C. It works and nothing wrong with it.

Now I want it to perform a bit differently. I want to know if its possible.

e.g It should search some string in Column A but don't replace it yet instead it should search for "1" from this position in the text file and replace "1" with string in column C.

Why: The reason I want to do that is that there are so many "1" in my text document and if I search "1" from the start it wont be a unique variable or I wont be able to replace the "1" I actually want to replae. But if it search for "1" after searching that string in Column A it would be the correct "1" I want to replace.

Thankyou

Here is my code:

LastRow = Sheets("Part B").Cells(Rows.Count, 1).End(xlUp).Row

ThisWorkbook.Sheets("Part B").Activate

With CreateObject("scripting.filesystemobject")
For i = 2 To LastRow 'assuming row 1 houses col heads
.createtextfile(Cells(i, 1)).write Replace(.opentextfile(Cells(i, 1)).ReadAll, Cells(i, 2), Cells(i, 7))
Next
End With

patel
06-20-2013, 12:15 AM
attach please a sample file and also desired result

afzalw
06-20-2013, 10:17 AM
attach please a sample file and also desired result

I have attached a zip file containing Excel Macro and a text file with some data.
Thanks

patel
06-21-2013, 03:06 AM
I did not understand, where is desired result ?

afzalw
06-21-2013, 10:28 AM
I did not understand, where is desired result ?

Here is the file with desired results.

patel
06-21-2013, 11:02 AM
Sub textchange()
Fname = Range("A2")
sn = Split(CreateObject("scripting.filesystemobject").opentextfile(Fname).readall, vbCrLf)
For j = 0 To UBound(sn)
If InStr(sn(j), "CRuttingBr") > 0 And InStr(sn(j), "ACRuttingBr") = 0 Then
sn(j + 1) = Replace(sn(j + 1), "1", "1000")
End If
s = s & sn(j) & vbCrLf
Next
Kill Fname
Open Fname For Append As #1
Print #1, s
Close #1
End Sub

afzalw
06-22-2013, 09:15 AM
Sub textchange()
Fname = Range("A2")
sn = Split(CreateObject("scripting.filesystemobject").opentextfile(Fname).readall, vbCrLf)
For j = 0 To UBound(sn)
If InStr(sn(j), "CRuttingBr") > 0 And InStr(sn(j), "ACRuttingBr") = 0 Then
sn(j + 1) = Replace(sn(j + 1), "1", "1000")
End If
s = s & sn(j) & vbCrLf
Next
Kill Fname
Open Fname For Append As #1
Print #1, s
Close #1
End Sub

Thanks it is working for that text file. Actually that .txt file was the specific portion of a larger 7 MB text file and when I try to run this code on that larger file it does not work and Excel stops responding.
I have upload the big text file in an exterior link here:
http://speedy.sh/e5YPa/Text.txt

The number "1" after CRuttingBr line has to be replaced with "1000".