I am trying to write a macro in Microsoft Access to accomplish the following:
For a list of linked tables (ODBC connection):
-SELECT top 10 records
-export results of each query to either Excel or CSV file of title [table_name] + suffix, i.e., "tablename1_10", "tablename2_10", etc. to a designated folder
======================
UPDATE:
======================
I now have a script, which despite my previous error with the ODBC connection, works when I do not try to declare an ODBC Connection String and declare "qdf.Open". Macro below, with small edits for anonymity:
Sub queryAllTables()
Dim tables() As String
tables = Split("<table names>", ",")
For Each element In tables
Dim elm As String
elm = element
Call sExportTop10(elm, "<folder>", False)
Next element
End Sub
Sub sExportTop10(strTable As String, strFolder As String, blnExcel As Boolean)
On Error GoTo E_Handle
Dim strFile As String
Dim strSQL As String
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
strFile = strFolder & strTable
strSQL = "SELECT TOP 10 * FROM [" & strTable & "];"
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
For Each MyQueryDef In CurrentDb.QueryDefs
If MyQueryDef.Name = "qdfExport" Then
CurrentDb.QueryDefs.Delete ("qdfExport")
Exit For
End If
Next
Set dbs = CurrentDb()
Set qdf = dbs.CreateQueryDef("qdfExport")
qdf.ReturnsRecords = False
qdf.SQL = strSQL
qdf.OpenRecordSet
If blnExcel = True Then
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qdfExport", strFile & "_10.xlsx", True
Else
DoCmd.TransferText acExportDelim, , "qdfExport", strFile & "_10.csv", True
End If
sExit:
On Error Resume Next
Exit Sub
E_Handle:
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
Resume sExit
End Sub