vbams-accessms-access-2010

Exporting a query result into a text file using vba-MS Access


I have a Table in MS Access 2010 and I want to export the result of a query into a text file( the user specified a path and this Textfile should be saved in this Path)

Here is my Query:

SELECT Name FROM MyTable

and I want to have each name in a seprate row in a text file. How can I do that in VBA?


Solution

  • In this particular case the most straightforward approach would be something like this:

    Sub ExportToText()
    Dim rst As DAO.Recordset
    Open "C:\__tmp\names.txt" For Output As #1
    Set rst = CurrentDb.OpenRecordset("SELECT [Name] FROM MyTable", dbOpenSnapshot)
    Do While Not rst.EOF
        Print #1, rst!Name
        rst.MoveNext
    Loop
    rst.Close
    Set rst = Nothing
    Close #1
    End Sub