# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  VB6 - Save Recordset to CSV format

## CVMichael

This is a function I made that is quite usefull when you want to save the data in a Recordset directly to a CSV file.


```
Public Function RecordsetToCSV(rsData As ADODB.Recordset, Optional ShowColumnNames As Boolean = True, Optional NULLStr As String = "") As String
    Dim K As Long, RetStr As String
    
    If ShowColumnNames Then
        For K = 0 To rsData.Fields.Count - 1
            RetStr = RetStr & ",""" & rsData.Fields(K).Name & """"
        Next K
        
        RetStr = Mid(RetStr, 2) & vbNewLine
    End If
    
    RetStr = RetStr & """" & rsData.GetString(adClipString, -1, """,""", """" & vbNewLine & """", NULLStr)
    RetStr = Left(RetStr, Len(RetStr) - 3)
    
    RecordsetToCSV = RetStr
End Function
```

This function returns a string in CSV format, to save to a file, you should do something like:


```
    Dim CSVData As String
    CSVData = RecordsetToCSV(rsData, True)

    Open "C:\test.csv" For Binary Access Write As #1
        Put #1, , CSVData
    Close #1
```

----------


## MildSeven

Thanks... very helpful!!!!

----------


## dilettante

Of course it destroys any type information of the fields, saving everything as text.  It also fails to handle quoting quotes that occur in fields, producing a broken CSV file in such a case.

It is short and sweet though!

----------


## chawdrysrk

This code snippet is very usefull. 
As @dilettante said, this fails to handle whenever a double quotes is present in the data, any idea to fix this will be really helpful.
thanks in advance.

----------

