Excel macro to find and replace multiple strings in any text file - vba

I used below code from your site to replace strings in a text file and it works fine. But, I don't want specify a file name, it should ready any file like (*.txt or *.xml).
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
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, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub

Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim sFileName As String
Dim FileExt(2) As String
ruta = Application.ActiveWorkbook.Path
ChDrive ruta
ChDir ruta
FileExt(1) = "txt"
FileExt(2) = "xml"
For i = 1 To 2
sFileName = Dir("*." & FileExt(i))
Do
If sFileName = "" Then Exit Do
sTemp = ""
Open sFileName For Input As #1
Do Until EOF(1)
Line Input #1, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close #1
sTemp = Replace(sTemp, "THIS", "THAT")
Open sFileName For Output As #1
Print #1, sTemp
Close #1
sFileName = Dir()
Loop
Next i
End Sub

You can iterate through items in an array!!
Sub FindAndReplaceText()
Dim FileName As String
Dim FolderPath As String
Dim FSO As Object
Dim I As Integer
Dim SearchForWords As Variant
Dim SubstituteWords As Variant
Dim Text As String
Dim TextFile As Object
'Change these arrays to word you want to find and replace
SearchForWords = Array("string1", "string2", "string3")
SubstituteWords = Array("string100", "string200", "string300")
'Change the folder path to where your text files are.
FolderPath = "C:\your_path_here\"
Set FSO = CreateObject("Scripting.FileSystemObject")
FolderPath = IIf(Right(FolderPath, 1) <> "\", FolderPath & "\", FolderPath)
FileName = Dir(FolderPath & "\*.txt")
Do While FileName <> ""
FileSpec = FolderPath & FileName
'Read all the file's text into a string variable.
Set TextFile = FSO.OpenTextFile(FileSpec, 1, False)
Text = TextFile.ReadAll
TextFile.Close
'Scan the string for words to replace and write the string back to the file.
Set TextFile = FSO.OpenTextFile(FileSpec, 2, False)
For I = 0 To UBound(SearchForWords)
Debug.Print Text
Replace Text, SearchForWords(I), SubstituteWords(I)
Debug.Print Text
Next I
TextFile.Write Text
TextFile.Close
FileName = Dir()
Loop
End Sub

Related

Parse and format text file

I have a text file that is not in a format that I can use for printing labels. The current format is like this:
DY234-02 0.5 0.5 Qty 6
U21 U12 U14 U28
TR459-09 0.5 0.5 Qty 9
U11 U78 U7 U8 U30 U24
I need the file to end up like this:
DY234-02 0.5 0.5 Qty 6 U21 U12 U14 U28
TR459-09 0.5 0.5 Qty 9 U11 U78 U7 U8 U30 U24
The files contain about 100 lines of this format I have used vbscript to try to get what I need but the format is not much different. If someone could get me pointed in the right direction that would be great. I am open to all other methods for accomplishing this. Thanks
This is my code in vbscript, but is not doing the job correctly:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\parse.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine1 = objFile.ReadLine
strLine2 = ""
If Not objFile.AtEndOfStream Then
strLine2 = objFile.ReadLine
End If
strNewLine = strLine1 & strLine2
strNewContents = strNewContents & strNewLine & vbCrLf
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Scripts\B3.txt", ForWriting, True)
objFile.Write strNewContents
objFile.Close
If the format is repeated like this, you can read in the text file line by line, and check if there is data on each line. If so join the data to an output string, otherwise add a carriage return to the output string, before finally outputting it to a new text file. Something like this perhaps:
Dim strInFile As String
Dim strOutFile As String
Dim intInFile As Integer
Dim intOutFile As Integer
Dim strInput As String
Dim strOutput As String
strInFile = "J:\downloads\data-in.txt"
strOutFile = "J:\downloads\data-out.txt"
intInFile = FreeFile
Open strInFile For Input As intInFile
intOutFile = FreeFile
Open strOutFile For Output As intOutFile
Do
Line Input #intInFile, strInput
If Len(Trim(strInput)) > 0 Then
strOutput = strOutput & " " & strInput
Else
strOutput = strOutput & vbCrLf
End If
Loop Until EOF(intInFile)
Print #intOutFile, strOutput
Reset
Regards,
Try next code, please. It is fast due to the fact it reads all the text value at once and drop the result, also at once. Everything is happening in memory.
Sub testSplitTextFile()
Dim objFSO As Object, objTF As Object, strIn As String, fullFilename As String, retFile As String
Dim arrIn As Variant, strRet As String, i As Long
'use here your path
fullFilename = "C:\Teste VBA Excel\Teste StackOverflow\TestSplit.txt"
retFile = "C:\Teste VBA Excel\Teste StackOverflow\RetFile.txt"'your path
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(fullFilename, 1)
strIn = objTF.ReadAll 'it reads all the txt file string
objTF.Close
arrIn = Split(strIn, vbCrLf) 'it splits the above string on lines
'Then, it builds a string based on your conditions:
For i = 0 To UBound(arrIn) - 1
If arrIn(i) <> "" And arrIn(i + 1) <> "" Then
strRet = strRet & arrIn(i) & " " & arrIn(i + 1) & vbCrLf
End If
Next i
strRet = left(strRet, Len(strRet) - 1)' it eliminates the last vbCrLf character
FreeFile 1
Open retFile For Output As #1
Print #1, strRet 'it drops, at once the created string
Close #1
End Sub

Microsoft Access VBA - Edit Text File

I am trying to edit a text file using Microsoft access vba.
What I want to do is the remove all the comma from the text file.
I tried the some of the codes online and it works perfectly fine for my test file.
What the code is to replace the “,” in the file with “”
However, when I try to run it on my actual text file, the access will become not responding , I waited 2 hours , but still didn’t responded.
I not sure is it because of my data is too huge, the size of my text file is 417MB.
Is there anyone is able to advise me on this?
Thank you!
The code i am using
Private Sub Click()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
sFileName = "C:123\123\data.txt"
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, ",", "")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
This line:
sTemp = sTemp & sBuf & vbCrLf
is probably what's killing your performance.
See discussion here: Using Pre-Made Stringbuilder Class
You will find it's faster to process the file line-by-line and write out to a different file. Also keeps your original file intact in case you make a mistake...
Private Sub Click()
Dim sBuf As String
Dim iFileNum As Integer, iFileNum2 As Integer
Dim sFileName As String, sFileNameOut As String
sFileName = "C:123\123\data.txt"
sFileNameOut = "C:123\123\data_out.txt"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
iFileNum2 = FreeFile
Open sFileNameOut For Output As iFileNum2
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
Write #iFileNum2, Replace(sBuf, ",", "")
Loop
Close iFileNum
Close iFileNum2
End Sub

Read only one record from Multiple text files into Excel using VBA

I have multiple txt files in a folder, which are tab delimited. Each of these files have a column called EngagementId, which is the same value, irrespective of number of records. However, it changes for every txt file, which is what I want to capture.
I am trying to get the file name in the first row. The GetFileNames() works for that (as pointed out in the comments)
Sub GetFileNames()
Dim sPath As String
Dim sFile As String
Dim iRow As Integer
Dim iCol As Integer
Dim splitFile As Variant
'specify directory to use - must end in "\"
sPath = ActiveWorkbook.Path
iRow = 0
sFile = Dir(sPath & "\Individual Reports\")
Do While sFile <> ""
iRow = iRow + 1
splitFile = Split(sFile, ".txt")
For iCol = 0 To UBound(splitFile)
Sheet1.Cells(iRow, iCol + 1) = splitFile(iCol)
Next iCol
sFile = Dir ' Get next filename
Loop
End Sub
Each of these txt files have one column (which is in the 13th position in each of the text files), called "EngagementId". I want to pull only the first "Engagement Id", which is from the 2nd row(since the first row contains headers).
Sub Extractrec()
Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String
MyFolder = ActiveWorkbook.Path
MyFile = Dir(MyFolder & "\Individual Reports\*.txt")
Do While MyFile <> ""
Open (MyFolder & MyFile) For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, "\t") 'second loop text is already stored
'-> see reset text
Sheet1.Cells(iRow, iCol + 2).Value = LineItems(13, 2)
Loop
Close #1
Loop
Using an ADODB.Recordset to query would be more versatile.
Sub Example()
On Error Resume Next
Dim rs As Object, f As Object, conn As Object
Dim FolderPath As String, FileName As String, FilterString As String
FolderPath = "C:\Users\best buy\Downloads\stackoverfow\Sample Data File\"
FileName = "example.csv"
FilterString = "WHERE EngagementId = 20"
Set rs = getDataset(FolderPath, FileName, FilterString)
Do While Not rs.BOF And Not rs.EOF
Debug.Print rs.Fields("EngagementId")
Debug.Print rs.Fields("Company")
Debug.Print rs.Fields("City")
Debug.Print rs.Fields("State")
rs.MoveNext
Loop
Set conn = rs.ActiveConnection
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
End Sub
Function getDataset(FolderPath As String, FileName As String, FilterString As String) As Object
Dim conn As Object, rs As Object
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conn.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FolderPath & ";" & _
"Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;""")
rs.ActiveConnection = conn
rs.Source = "SELECT * FROM " & FileName & " " & FilterString
rs.Open
Set getDataset = rs
End Function
Since you only need the second line of each file, you don't need to loop, just read and discard the fist line, then read and split the second one:
Open (MyFolder & MyFile) For Input As #1 'MyFolder & MyFile won't be the correct name (probably should be MyFolder & "\Individual Reports\" & MyFile)
Line Input #1, LineFromFile 'line to discard
Line Input #1, LineFromFile 'line to use
LineItems = Split(LineFromFile, vbTab)
Sheet1.Cells(someplace).Value = LineItems(13) ' replace some place with the correct value that we don't know
Close #1

excel vba move each text file to a new directory using the file name?

i am using the following vba code to import all my text files onto a new row in excel. This bit works fine, the next thing I want to do is once this has imported the text files, I want each text file to be moved from one directory 'Z:\NS\Unactioned\' to another directory called Actioned 'Z:\NS\Actioned\&Filename\'.
And within that folder create a folder for each of the text files from the filename (minus the file extension) where i can then place each text file in the corresponding folder.
So if I had 3 .txt files in my folder Unactioned:
1.txt
2.txt
3.txt
then each txt file would be moved like so:
Actioned/1/1.txt
Actioned/2/2.txt
Actioned/3/3.txt
Can someone please show me how I would do this? Thanks
Code:
Sub Import_All_Text_Files_2007()
Dim nxt_row As Long
'Change Path
Const strPath As String = "Z:\NS\Unactioned\"
Dim strExtension As String
'Stop Screen Flickering
Application.ScreenUpdating = False
ChDir strPath
'Change extension
strExtension = Dir(strPath & "*.txt")
Do While strExtension <> ""
'Sets Row Number for Data to Begin
If Range("C1").Value = "" Then
nxt_row = 1
Else
If Range("C2").Value = "" Then
nxt_row = 2
Else
nxt_row = Range("C1").End(xlDown).Offset(1).Row
End If
End If
'Below is from a recorded macro importing a text file
FileNum = FreeFile()
curCol = 3
Open strPath & strExtension For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
ActiveSheet.Cells(nxt_row, curCol) = DataLine
curCol = curCol + 1
Wend
Close #FileNum
strExtension = Dir
Loop
Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
srcPath = "Z:\NS\Unactioned\"
destPath = "Z:\NS\Actioned\" & srcFile & "\"
ext = Array("*.txt", "*.xls")
For Each x In ext
d = Dir(srcPath & x)
Do While d <> ""
srcFile = srcPath & d
FileCopy srcFile, destPath & d
Kill srcFile
d = Dir
Loop
Next
Application.ScreenUpdating = True
End Sub
You misplaced destPath so it wasn't filled with the document name.
Forgot to create destination directory (with MKDir) and the arguments of the last d=Dir statement
Try this (works for me) :
Sub Import_All_Text_Files_2007()
Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
Dim strExtension As String
Dim nxt_row As Long
'Change Path
Const strPath As String = "Z:\NS\Unactioned\"
'Stop Screen Flickering
Application.ScreenUpdating = False
ChDir strPath
'Change extension
strExtension = Dir(strPath & "*.txt")
Do While strExtension <> ""
'Sets Row Number for Data to Begin
If Range("C" & Rows.Count).End(xlUp).Offset(1).Row >= 5 Then
nxt_row = Range("C" & Rows.Count).End(xlUp).Offset(1).Row
Else
nxt_row = 5
End If
'Below is from a recorded macro importing a text file
FileNum = FreeFile()
curCol = 3
Open strPath & strExtension For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
ActiveSheet.Cells(nxt_row, curCol) = DataLine
curCol = curCol + 1
Wend
Close #FileNum
strExtension = Dir
Loop
srcPath = "Z:\NS\Unactioned\"
ext = Array("*.txt", "*.xls")
For Each x In ext
d = Dir(srcPath & x)
Do While d <> ""
srcFile = srcPath & d
destPath = "Z:\NS\Actioned\" & Left(d, Len(d) - 4) & "\"
If Dir(destPath, 16) = "" Then MkDir (destPath)
FileCopy srcFile, destPath & d
Kill srcFile
d = Dir(srcPath & x)
Loop
Next x
Application.ScreenUpdating = True
End Sub

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

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.
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
Why involve Notepad?
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
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, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
Just add this line
sFileName = "C:\someotherfilelocation"
right before this line
Open sFileName For Output As iFileNum
The idea is to open and write to a different file than the one you read earlier (C:\filelocation).
If you want to get fancy and show a real "Save As" dialog box, you could do this instead:
sFileName = Application.GetSaveAsFilename()
I have had the same problem and came acrosse this site.
the solution to just set another "filename" in the
... for output as ... command was very simple and useful.
in addition (beyond the Application.GetSaveAsFilename() Dialog)
it is very simple to set a** new filename**
just using
the replace command,
so you may change the filename/extension
eg. (as from the first post)
sFileName = "C:\filelocation"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
content = (...edit the content)
Close iFileNum
now just set:
newFilename = replace(sFilename, ".txt", ".csv") to change the extension
or
newFilename = replace(sFilename, ".", "_edit.") for a differrent filename
and then just as before
iFileNum = FreeFile
Open newFileName For Output As iFileNum
Print #iFileNum, content
Close iFileNum
I surfed over an hour to find out how to rename a txt-file,
with many different solutions, but it could be sooo easy :)
This code will open and read lines of complete text file
That variable "ReadedData" Holds the text line in memory
Open "C:\satheesh\myfile\Hello.txt" For Input As #1
do until EOF(1)
Input #1, ReadedData
loop**