Samples of VBA code I'm using in my daily tasks.

Wednesday, March 17, 2010

Save Recordset To CSV File

Public Sub SaveRecordsetToCSV()
    Dim rsTemp As ADODB.Recordset
    Set rsTemp = New ADODB.Recordset
    
    rsTemp.Open "MyTableName", CurrentProject.Connection, adOpenStatic, adLockOptimistic
 
    Dim CSVData As String
    CSVData = RecordsetToCSV(rsTemp, True)
 
    Open "C:\MyFileName.csv" For Binary Access Write As #1
        Put #1, , CSVData
    Close #1
    
    rsTemp.Close
    Set rsTemp = Nothing
End Sub


Public Function RecordsetToCSV(rsData As ADODB.Recordset, _
        Optional ShowColumnNames As Boolean = True, _
        Optional NULLStr As String = "") As String
    'Function returns a string to be saved as .CSV file
    'Option: save column titles

    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


4 comments:

  1. I'm struggling with the removal of the Quotes " syntax from the resultant CSV output.
    I just need simple commas between values.
    Like Val1,Val2,Val3,Val4, etc.
    Suggestions?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. any help/leads to remove the quotes will be really helpful, thanks in advance.

    ReplyDelete