Microsoft Access VBA - Edit Text File - vba

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

Related

Find and replace characters in strings in all .xlsx files in folder VBA

I am trying to replace characters such as "/" and "ó", and also a line break (alt + ENTER, manually replaced in excel with find and replace with CTRL + J) in excel files (.xlsx). The characters can be found all over the excel sheets (not one particular range). The reason that I would like to replace these values is that these characters are giving me errors in another application.
I have 20 excel files in one folder, with multiple sheets. I would like to make a script (vba macro) to loop through the excel files and all its sheets and do the replacements.
I am very new with vba/macros.
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim sFileName As String
Dim FileExt(2) As String
ChDir = "C:\mydirectory\"
FileExt(1) = "xlsx"
For i = 1 To 1
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, "ó", "o")
sTemp = Replace(sTemp, "/", "")
Open sFileName For Output As #1
Print #1, sTemp
Close #1
sFileName = Dir()
Loop
Next i
End Sub
I have tried to combine code from scripts mentioned here:
Find and replace string in all excel files in folder and here
Excel macro to find and replace multiple strings in any text file
Loop through files in a folder using VBA?
But I didn't get it to work.
Help would be very appreciated!

logs for user activity in vba userform

I am trying to work on a code that will give me the user activity on the userform that I have created. I want to keep this logs file in shared drive if possible.
below is my code, not getting any records in logs folder
Sub LogInformation(LogMessage As String)
Const LogFileName As String = "D:\FOLDERNAME\TEXTFILE.LOG"
Dim FileNum As Integer
FileNum = FreeFile ' next file number
Open LogFileName For Append As #FileNum ' creates the file if it doesn't exist
Print #FileNum, LogMessage ' write information at the end of the text file
Close #FileNum ' close the file
End Sub
Public Sub DisplayLastLogInformation()
Const LogFileName As String = "D:\FOLDERNAME\TEXTFILE.LOG"
Dim FileNum As Integer, tLine As String
FileNum = FreeFile ' next file number
Open LogFileName For Input Access Read Shared As #f ' open the file for reading
Do While Not EOF(FileNum)
Line Input #FileNum, tLine ' read a line from the text file
Loop ' until the last line is read
Close #FileNum ' close the file
MsgBox tLine, vbInformation, "Last log information:"
End Sub
Sub DeleteLogFile(FullFileName As String)
On Error Resume Next ' ignore possible errors
Kill FullFileName ' delete the file if it exists and it is possible
On Error GoTo 0 ' break on errors
End Sub
Private Sub Workbook_Open()
LogInformation ThisWorkbook.Name & " opened by " & _
Application.UserName & " " & Format(Now, "yyyy-mm-dd hh:mm")
End Sub

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

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

Using textstream object to replace tab with spaces and delete characters

I have over a thousand .s2p files (a delimited text file used by electrical testing equipment) that were edited by a VBA macro, which opened each raw file in Excel as a tab-and-space delimited text file, and replaced a few of the columns with data columns from another file, then saved them in original format (.s2p) and closed them. This is the call I used to open the each file:
Call Application.Workbooks.OpenText(Filename:=(path & filename & ".s2p"), Origin:="437", DataType:=xlDelimited, ConsecutiveDelimiter:=True, Tab:=True, Space:=True, TextQualifier:=xlTextQualifierNone)
Now, when I open the .s2p files in Notepad to view them, the original single space separating the columns is now a full tab, and some double quote (") characters were added to some of the file header lines (despite setting TextQualifier parameter to xlTextQualifierNone...)
Because of this I want to write another macro that can open all of these .s2p files again, loop through the lines, and replace any double quotes with blanks, and any tabs with single spaces. I was planning to use .OpenAsTextStream on each file, but it seems like the TextStream object doesn't support overwriting lines, but can only write new lines...
Is there a better way to achieve what I am trying to do than just reading lines from the original file, and writing them to a newly created file? It is imperative that I save the final file as ".s2p" and not ".txt".
You don't need the text streams, just the basic input output actions available in VBA.
Option Explicit
Sub test()
FixFile "c:\temp\mytestfile.s2p"
End Sub
Sub FixFile(filename As String)
Dim fnum As Integer
Dim fileText As String
Dim finalText As String
fnum = FreeFile
On Error Resume Next
Open filename For Input As #fnum
If Err.Number <> 0 Then
Debug.Print "Critical error attempting to open " & filename & _
". Error #" & Err.Number & ": " & Err.Description
Exit Sub
End If
finalText = ""
Do Until EOF(fnum)
Line Input #fnum, fileText
fileText = Replace(fileText, """", " ", , , vbTextCompare)
fileText = Replace(fileText, vbTab, " ", , , vbTextCompare)
finalText = finalText & fileText & vbCrLf
Loop
Close fnum
fnum = FreeFile
Open filename For Output As #fnum
Print #fnum, finalText
Close fnum
End Sub
Edited to show line by line read with a final write.

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**