Search code examples
csvvb6filesystemobject

How to write in CSV file using VB6


How can I write per column in .csv file using VB6? I use File System Object .writeline to read and write in .csv file but my problem is it only write in one column only. Can someone please help me.

Dim fso As New FileSystemObject
Dim fsoStream As TextStream

Set fsoStream = fso.CreateTextFile("C:\Users\Users\Desktop\File\Sample.csv", True)

fsoStream.WriteLine "Like This is what I have tried" 'this must be written in the first column
fsoStream.WriteLine "But this is a sample only" 'this must be written in the first column
fsoStream.WriteLine "Sample 1" 'this must be written in the second column
fsoStream.WriteLine "Sample 1" 'this must be written in the second column
fsoStream.WriteLine "Sample 2" 'this must be written in the third column
fsoStream.WriteLine "Sample 2" 'this must be written in the third column

fsoStream.Close
Set fsoStream = Nothing
Set fso = Nothing

This picture must be the output.

enter image description here

but this is what I have got in using the code above enter image description here


Solution

  • You can build a string for each row, and when the row-string is complete then write it to file

    for example using the code from your post :

    Dim strLine As String
    Dim fso As New FileSystemObject
    Dim fsoStream As TextStream
    
    Set fsoStream = fso.CreateTextFile("C:\Users\Users\Desktop\File\Sample.csv", True)
    
    'prepare the first row
    strLine = "Like This is what I have tried" 'this must be written in the first column
    'write the first row
    fsoStream.WriteLine strLine
    
    'prepare the second row
    strLine = "But this is a sample only"      'this must be written in the first column
    strLine = strLine & "," & "Sample 1"       'this must be written in the second column
    'write the seconde row
    fsoStream.WriteLine strLine
    
    'prepare the third row
    strLine = ""                               'an empty first column
    strLine = strLine & "," & "Sample 1"       'this must be written in the second column
    strLine = strLine & "," & "Sample 2"       'this must be written in the third column
    'write the third row
    fsoStream.WriteLine strLine
    
    'prepare the fourth row
    strLine = ""                               'an empty first column
    strLine = strLine & ","                    'an empty second column
    strLine = strLine & "," & "Sample 2"       'this must be written in the third column
    'write the fourth row
    fsoStream.WriteLine strLine
    
    fsoStream.Close
    Set fsoStream = Nothing
    Set fso = Nothing
    

    This will not give the result which you posted in your desired output picture, but that is because of the extra write actions you had in your original code as well

    Just delete those extra lines in your code, and the result will be as you posted in the picture. I am sure you can find which extra lines i am talking about :)