Results 1 to 4 of 4

Thread: VB6 - Save Recordset to CSV format

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,802

    VB6 - Save Recordset to CSV format

    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.
    Code:
    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:
    Code:
        Dim CSVData As String
        CSVData = RecordsetToCSV(rsData, True)
    
        Open "C:\test.csv" For Binary Access Write As #1
            Put #1, , CSVData
        Close #1

  2. #2
    Member
    Join Date
    Sep 2003
    Location
    Montreal, Canada
    Posts
    42

    Re: VB6 - Save Recordset to CSV format

    Thanks... very helpful!!!!
    - lone wolf

  3. #3
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: VB6 - Save Recordset to CSV format

    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!

  4. #4
    New Member
    Join Date
    Feb 2022
    Posts
    1

    Re: VB6 - Save Recordset to CSV format

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width