Solved How do I Create a Proper CSV file

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:03
Joined
May 21, 2018
Messages
9,486
I am trying to help someone create a manual CSV file. The file appears properly formatted, but it opens up as a single cell in Excel. What am I missing. See thread
Thanks.
 
This is for vba in Excel. But I think you can use it with a recordset in Access too.

 
Thanks, but no real information in there. Here is the DB that makes the CSV.
 

Attachments

I could not get the comma to work but replaced with a tab and it worked. Still curious.
 
Maybe a matter of the text encoding of the file? I can get it to work if I don't set Unicode = True...
Code:
Function CreateTextFile(FileName as String, Optional Overwrite As Boolean = True. Optional Unicode As Boolean = False) As TextStream
Call it like this, it fails...
Code:
Set Stream = FS.CreateTextFile(ExportFile, False, True)
Call it like this, it works.
Code:
Set Stream = FS.CreateTextFile(ExportFile)
This routine works for me in your database...
Code:
Public Sub Export3()
    Dim ts As Scripting.TextStream
   
    With New Scripting.FileSystemObject
        Set ts = .CreateTextFile(CurrentProject.Path & "\test.csv")
    End With
   
    ts.WriteLine "Team,Color,Sport"
   
    With CurrentDb.OpenRecordset("tblTest")
        Do While Not .EOF
            With .Fields
                ts.WriteLine Join(Array(!Team, !Color, !Sport), ",")
            End With
            .MoveNext
        Loop
        .Close
    End With
   
    ts.Close
   
    VBA.Shell "Excel.exe """ & CurrentProject.Path & "\test.csv"""
End Sub
 
Last edited:
I am trying to help someone create a manual CSV file. The file appears properly formatted, but it opens up as a single cell in Excel. What am I missing. See thread
Thanks.
Is the O/P actually using comma in their regional settings?
 
@MarkK,
That is the answer. If I change my code it works going from.
Set Stream = FS.CreateTextFile(ExportFile, False, True)
to
Set Stream = FS.CreateTextFile(ExportFile, False, False)

So changing from unicode to ASCII works. Not sure I fully understand that, but it works.
 
fsoFile.WriteLine strRec
is what I use to write each line. If you want to use the other methods, you probably need CRLF at the end of each record. Looks like WriteLine automaticly adds the CRLF but the other methods don't

Also, properly formatted .csv files enclose strings in quotes but not other columns.

The reason I had to write the .csv file manually rather than just using TransferText was because the receiving system wanted ALL fields enclosed in quotes regardless of field type.
 
Last edited:

Users who are viewing this thread

Back
Top Bottom