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

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

Related

VBA to open Explorer dialogue, select txt file, and add a header that is the filename without file path

I have 100's of text files named correctly, but I need the name of the text file added into the first row (thus shifting the existing data down to the second row) with " on either side of the name.
The text files are over multiple folders, so I need to be able to open an explorer dialogue first to select multiple text files and add the new header row to every one.
Any help would be hugely appreciated as I cannot find the answer anywhere on google!
Tom
My attempt, but doesnt really work becaue 1. I have to set the directory, and 2. I need to have the filename with " either side, for example "Line1":
Sub ChangeRlnName()
'the final string to print in the text file
Dim strData As String
'each line in the original text file
Dim strLine As String
Dim time_date As String
Set FSO = CreateObject("Scripting.FileSystemObject")
'Get File Name
Filename = FSO.GetFileName("C:\Users\eflsensurv\Desktop\Tom\1.txt")
'Get File Name no Extension
FileNameWOExt = Left(Filename, InStr(Filename, ".") - 1)
strData = ""
time_date = Format(Date, "yyyymmdd")
'open the original text file to read the lines
Open "C:\Users\eflsensurv\Desktop\Tom\1.txt" For Input As #1
'continue until the end of the file
While EOF(1) = False
'read the current line of text
Line Input #1, strLine
'add the current line to strData
strData = strData + strLine & vbCrLf
Wend
'add the new line
strData = FileNameWOExt + vbLf + strData
Close #1
'reopen the file for output
Open "C:\Users\eflsensurv\Desktop\Tom\1.txt" For Output As #1
Print #1, strData
Close #1
End Sub
Try something like this:
Sub Tester()
Dim colFiles As Collection, f
'get all txt files under specified folder
Set colFiles = GetMatches("C:\Temp\SO", "*.txt")
'loop files and add the filename as a header
For Each f In colFiles
AddFilenameHeader CStr(f)
Next f
End Sub
Sub AddFilenameHeader(fpath As String)
Dim base, content
With CreateObject("scripting.filesystemobject")
base = .GetBaseName(fpath) 'no extension
With .OpenTextFile(fpath, 1)
'get any existing content
If Not .AtEndOfStream Then content = .readall()
.Close
End With
DoEvents
'overwrite existing content with header and previous content
.OpenTextFile(fpath, 2, True).write """" & base & """" & vbCrLf & content
End With
End Sub
'Return a collection of file paths given a starting folder and a file pattern
' e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetMatches(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Collection
Dim fso, fldr, f, subFldr, fpath
Dim colFiles As New Collection
Dim colSub As New Collection
Set fso = CreateObject("scripting.filesystemobject")
colSub.Add startFolder
Do While colSub.Count > 0
Set fldr = fso.getfolder(colSub(1))
colSub.Remove 1
If subFolders Then
For Each subFldr In fldr.subFolders
colSub.Add subFldr.Path
Next subFldr
End If
fpath = fldr.Path
If Right(fpath, 1) <> "\" Then fpath = fpath & "\"
f = Dir(fpath & filePattern) 'Dir is faster...
Do While Len(f) > 0
colFiles.Add fpath & f
f = Dir()
Loop
Loop
Set GetMatches = colFiles
End Function

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!

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

Excel VBA: Specify file name and file location to save

I am trying to use Excel VBA to automatically save down a file. I need to save the file with a:
(1) Dynamic name by date: XYZ & today's date (for example "XYZ 20180825")
(2) Static location: let's say that I need to save the file in the directory "C:\Program Files"
I am wondering how I can reflect that in VBA.
Here is a crashcourse, sorry for the language mix ...
Create and write file
Sub SchreibeDatei()
Dim strDateiname As String, strDateipfad As String
strDateiname = Date & Time & "test.txt"
strDateipfad = ThisWorkbook.Path & "\" & strDateiname
' Datei erzeugen und/oder schreiben
Open strDateipfad For Output As #1
Print #1, ""
Print #1, ""
Close #1
End Sub
Append to existing file
Sub ErweitereDatei()
Dim strDateiname As String, strDateipfad As String
strDateiname = "test.txt"
strDateipfad = ThisWorkbook.Path & "\" & strDateiname
Open strDateipfad For Append As #1
Print #1, ""
Close #1
End Sub
Read file
Sub LeseDatei()
Dim strDateiname As String, strDateipfad As String
Dim strZeile As String, strInhalt As String
strDateiname = "test.txt"
strDateipfad = ThisWorkbook.Path & "\" & strDateiname
' Datei zeilenweise lesen
Open strDateipfad For Input As #1
While Not EOF(1) ' EOF = EndOfFile
Line Input #1, strZeile
strInhalt = strInhalt + strZeile & Chr(10)
Wend
Close #1
MsgBox strInhalt
End Sub
Delete file
Sub LoescheDatei()
Dim strDateiname As String, strDateipfad As String
strDateiname = "test.txt"
strDateipfad = ThisWorkbook.Path & "\" & strDateiname
Kill(strDateipfad)
End Sub
Changing names, location and including datetime you will find!

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