Parse a txt file and save as csv?
This code is extracting CSV data
Sub GetCSVData()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Const Delimiter = ","
Set fsread = CreateObject("Scripting.FileSystemObject")
'default folder
Folder = "C:\temp\test"
ChDir (Folder)
FName = Application.GetOpenFilename("CSV (*.csv),*.csv")
RowCount = LastRow + 1
If FName < "" Then
'open files
Set fread = fsread.GetFile(FName)
Set tsread = fread.OpenAsTextStream(ForReading, TristateUseDefault)
Do While tsread.atendofstream = False
InputLine = tsread.ReadLine
'extract comma seperated data
ColumnCount = 1
Do While InputLine < ""
DelimiterPosition = InStr(InputLine, Delimiter)
If DelimiterPosition 0 Then
Data = Trim(Left(InputLine, DelimiterPosition - 1))
InputLine = Mid(InputLine, DelimiterPosition + 1)
Else
Data = Trim(InputLine)
InputLine = ""
End If
Cells(RowCount, ColumnCount) = Data
ColumnCount = ColumnCount + 1
Loop
RowCount = RowCount + 1
Loop
tsread.Close
End If
End Sub
--------------------------------------------------------------------------------------
Here is a macro that reads one file and write to another file
Sub adddouble()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const MyPath = "C:\temp\"
Const ReadFileName = "test.txt"
Const WriteFileName = "outtest.txt"
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Set fsread = CreateObject("Scripting.FileSystemObject")
Set fswrite = CreateObject("Scripting.FileSystemObject")
'open files
ReadPathName = MyPath + ReadFileName
Set fread = fsread.GetFile(ReadPathName)
Set tsread = fread.OpenAsTextStream(ForReading, TristateUseDefault)
WritePathName = MyPath + WriteFileName
fswrite.CreateTextFile WritePathName
Set fwrite = fswrite.GetFile(WritePathName)
Set tswrite = fwrite.OpenAsTextStream(ForWriting, TristateUseDefault)
Do While tsread.atendofstream = False
InputLine = tsread.ReadLine
OutputLine = Replace(InputLine, Chr(34), Chr(34) & Chr(34))
tswrite.writeline OutputLine
Loop
tswrite.Close
tsread.Close
End Sub
"Frank Pytel" wrote:
Hello;
I am trying to come up with some vba that will parse a txt file. There are
two files that come with different size delimited strings. I would like to
try to find a generic script that will parse the string lengths according to
their size and then add a comma after the end of the string length. I would
then like to save it into a csv file with line breaks. Can anyone direct me
to an accurate solution.
The string lengths are different, but I don't mind having two separate
scripts to run on the separate files.
Any help or direction would be greatly appreciated.
Thanks
Frank Pytel
|