how do i convert text files into CSV files?

D

David Biddulph

If your fields are separated by commas, then it already is a CSV. Take a
copy and rename as CSV if you wish.

If your fields are separated in some either way, either by tabs or other
characters, or by the use of fixed width fields, then opening the txt file
from within Excel will give you a wizard to select the fields accordingly,
and to choose a format for the columns as you import them. Having read the
data into Excel, you can save as CSV if you wish, but remember that reading
a CSV into Excel directly doesn't give you the flexibility that the wizard
gives, so if in doubt rename to .TXT instead of .CSV before you read it into
Excel.

[... and next time, please ask your question in the body of the message, not
just in the subject line.]
 
C

Chip Pearson

It depends on the format of the text files. Do they have a delimiter? You
could use the Text Import Wizard by choosing "Text Files" in the Get
External Data dialog from the Data menu and the do a Save As to CSV.

Or you could write code to bypass Excel altogether.

Sub ConvertTextToCSV(InputFileName As String, _
OutputFileName As String, _
Delimiter As String)

Dim InFNum As Integer
Dim OutFNum As Integer
Dim InputLine As String
Dim RecCount As Long

InFNum = FreeFile()
Open InputFileName For Input Access Read As #InFNum
OutFNum = FreeFile()
Open OutputFileName For Output Access Write As #OutFNum
Do
Line Input #InFNum, InputLine
RecCount = RecCount + 1
InputLine = Replace(InputLine, Delimiter, ",", , , vbBinaryCompare)
Print #OutFNum, InputLine
Loop Until EOF(InFNum)

Close #InFNum
Close #OutFNum

Debug.Print "Records: " & CStr(RecCount)

End Sub

Sub Test()
ConvertTextToCSV InputFileName:="C:\Test.txt", _
OutputFileName:="C:\Test.csv", _
Delimiter:=" "

End Sub


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com
(email address is on the web site)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top