Blockweiser CSV Export von komplexen MS Access Abfragen

Bei komplexen Abfragen kommt Access leicht an seine Grenzen. Hier eine VBA Funktion die eine Abfrage Blockweise (a 5000 Datensätze) in eine CSV Daten exportiert.

Public Function ExportQueryToCSV(ByVal queryName As String, ByVal fileName As String)
    Dim rs As DAO.Recordset
    Dim outFile As Long
    Dim i As Long
    Dim blockCount As Long
    
    ' Open the recordset for the query
    Set rs = CurrentDb.OpenRecordset(queryName)
    
    ' Open the output file
    outFile = FreeFile()
    Open fileName For Output As #outFile
    
    ' Write the field names as the first row of the file
    For i = 0 To rs.Fields.Count - 1
        If i > 0 Then
            Print #outFile, ",";
        End If
        Print #outFile, rs.Fields(i).Name
    Next i
    
    ' Loop through the recordset and write blocks of 5000 records to the file
    blockCount = 0
    Do While Not rs.EOF
        If blockCount Mod 5000 = 0 Then
            ' Start a new block
            If blockCount > 0 Then
                ' Close the previous block
                Print #outFile, ""
            End If
        End If
        
        ' Write the current record to the current block
        For i = 0 To rs.Fields.Count - 1
            If i > 0 Then
                Print #outFile, ",";
            End If
            Print #outFile, rs.Fields(i)
        Next i
        
        ' Move to the next record
        rs.MoveNext
        blockCount = blockCount + 1
    Loop
    
    ' Close the last block and the output file
    Print #outFile, ""
    Close #outFile
    
    ' Clean up
    rs.Close
    Set rs = Nothing
End Function

In dieser Funktion wird zuerst eine Schleife verwendet, um die Spaltennamen aus der Abfrage zu lesen und als erste Zeile in die CSV-Datei zu schreiben. Anschließend wird die Datensatzschleife wie zuvor verwendet, um die Datensätze blockweise in die CSV-Datei zu schreiben.

Bitte beachten Sie, dass diese Funktion nur funktioniert, wenn die Abfrage eindeutige Spaltennamen hat. Wenn die Abfrage Spalten enthält, die aus mehreren Tabellen stammen oder umbenannt wurden, müssen die Spaltennamen möglicherweise manuell angepasst werden.