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.
but this is what I have got in using the code above
Assuming you know what columns you want to write in advance, the following can be used (with optional header row:
Dim iFileNo As Integer
iFileNo = FreeFile
Open sFileName For Output As #iFileNo
Write #iFileNo, "ID", "Name", "Age", "Address"
Write #iFileNo, 1, "Person #1", 42, "Place #1"
Write #iFileNo, 2, "Person #2", 57, "Place #2"
Close #iFileNo
You read this as follows:
Dim sHeaders As String
Dim iFileNo As Integer
Dim lID As Long
Dim sName As String
Dim iAge As Integer
Dim sAddress As String
iFileNo = FreeFile
Open sFileName For Input As #iFileNo
Line Input #iFileNo, sHeaders
Do Until Eof(iFileNo)
Input #iFileNo, lID, sName, iAge, sAddress
Loop
Close #iFileNo