Question

Right now I have an MS SQL database with about 50 or so tables in it with which I'd like to link to MS Access using a DSN Less connection. Below is the basic code where I have a parameter of stRemoteTableName which is the table name of the SQL table to import. I could call this function each time for each table but that would take forever; is there anyway to loop through all tables in an SQL database and pass them to this function so that all tables are imported? I'm having a very hard time finding any code online for something like this, so help is much appreciated.

 Private Sub ImportAllTables(stRemoteTableName)
        On Error GoTo AttachDSNLessTable_Err
            Dim td As TableDef
            Dim stConnect As String
            stServer = "C:\Location"
            stDatabase = "DB"
            stLocalTableName = stRemoteTableName
            stUsername = ""

            For Each td In CurrentDb.TableDefs
                If td.Name = stLocalTableName Then
                    CurrentDb.TableDefs.Delete stLocalTableName
                End If
            Next

            stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"

            Set td = CurrentDb.CreateTableDef(stLocalTableName, stRemoteTableName, stConnect)
            CurrentDb.TableDefs.Append td
            Exit Sub

        AttachDSNLessTable_Err:

           AttachDSNLessTable = False
            MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description
        End Sub
Was it helpful?

Solution

You can use a pass-through query to list the table names from your SQL Server database. Open a recordset based on that query. Then loop through the recordset rows and link each table.

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strConnect As String
Dim strSelect As String

strSelect = "SELECT t.name FROM sys.tables t;"
'strConnect =  <you already have this as stConnect>
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strSelect)
qdf.Connect = strConnect
Set rs = qdf.OpenRecordset
With rs
    Do While Not .EOF
        ' you want to link; I will just list
        ' the table names
        Debug.Print !name
        .MoveNext
    Loop
    .Close
End With
Set rs = Nothing
Set qdf = Nothing
Set db = Nothing
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top