Search code examples
ms-access

How to link tables with VBA code over ODBC


Actually I use a ODBC-Connection to connect Ms Acces to tables of a PostgreSQL-DB. I connect them by using the External Data/Import ODBC-Link command. It works fine.

But how can I use VBA to link my tables?


Solution

  • When using VBA to link a table with ODBC, you can add and APP= argument to specify an application name that will generally show in the properties of the connection on your database server.

    For example, here is a sample ODBC Connection string for a linked table:

    ODBC;Driver={SQL Server};Server=MyServer\SQLExpress;Database=MyDatabase;APP=My App Title;Trusted_Connection=Yes;
    

    My App Title is the string that will be your Application Name for that connection.

    Update 1 In response to further comment by the OP:

    Here is sample code to link a table via ODBC in VBA. To facilitate this, you also should always delete the ODBC linked table each time before re-linking it to make sure that your options are respected, and that Microsoft Access updates the schema for the linked table. This example shows a connection string for a SQL Server database, so all you would need to change is the connection string for your PostgreSQL-DB. The remaining VBA code would be the same.

    Dim db As DAO.Database
    Dim tdf As DAO.TableDef
    Dim strConn As String
    Dim ODBCTableName as String
    Dim AccessTableName as String
    
    Set db = CurrentDb()
    ODBCTableName = "dbo.YourTable"
    AccessTableName = "YourTable"
    strConn = "ODBC;Driver={SQL Server};Server=YOURSERVER\SQLINSTANCE;Database=MYDATABASE;Trusted_Connection=No;UID=MyUserName;PWD=MyPassword"
    db.TableDefs.Refresh
    For Each tdf In db.TableDefs
        If tdf.Name = AccessTableName Then
            db.TableDefs.Delete tdf.Name
            Exit For
        End If
    Next tdf
    Set tdf = db.CreateTableDef(AccessTableName)
    
    '===============================
    'If your connection string includes a password
    'and you want the password to be saved, include the following 3 lines of code
    'to specify the dbAttachSavePWD attribute of the TableDef being created
    'If you don't want to save the password, you would omit these 3 lines of code
    '===============================
    If InStr(strConn, "PWD=") Then
        tdf.Attributes = dbAttachSavePWD
    End If
    
    tdf.SourceTableName = ODBCTableName 
    tdf.Connect = strConn
    db.TableDefs.Append tdf