Abstract

Dann und wann habe ich mit der Datenbank MS Access zu tun. Wenn es dann um den Export von Daten geht, bin ich jedes Mal von der DoCmd.TransferText Methode enttäuscht. Die unten genannte Subroutine ist m. E. deutlich besser.

Appendix – Table2Csv Programmcode

Bitte den Haftungsausschluss im Impressum beachten.

Sub Table2Csv(Table As String, Filename As String, _
    Optional Delim As String = ",", Optional ShowHeader As Boolean = True)
'Export database table to csv file, optionally with field headers.
'Simpler and safer approach than DoCmd.TransferText plus export specs,
'especially when we face a variable number of fields.
    Dim FileNum As Integer, i As Integer
    Dim MyDelim As String, NextRecord As String
    Dim rs As New ADODB.Recordset	
	
    FileNum = FreeFile	
    Open Filename For Output As #FileNum	
    rs.Open "SELECT * FROM " & Table, CurrentProject.connection	
    If ShowHeader Then
        MyDelim = ""
        NextRecord = ""
        For i = 0 To rs.fields.count - 1
            NextRecord = NextRecord & MyDelim & rs.fields(i).name
            MyDelim = Delim
        Next i
        Print #FileNum, NextRecord
    End If
    Do Until rs.EOF
        MyDelim = ""
        NextRecord = ""
        For i = 0 To rs.fields.count - 1
            NextRecord = NextRecord & MyDelim & rs.fields(i).Value
            MyDelim = Delim
        Next i			
        Print #FileNum, NextRecord			
        rs.MoveNext			
    Loop	
    rs.Close
    Close #FileNum	
End Sub