CreateLinkedTable Script - Microsoft Access

The following script will programmatically create a linked table in Microsoft Access. No check is made to see if the table already exists.

Sub CreateLinkedTable(serverName As String, dbName As String, remoteTableName As String, _
trustedConnection As Boolean, userName As String, password As String)

    Dim localTableName As String
    Dim tdf As TableDef
    Dim fld As Field

    localTableName = Replace$(remoteTableName, ".", "_")
    Set tdf = CurrentDb.CreateTableDef(localTableName)
    tdf.Connect = SqlServerConnection(serverName, dbName, remoteTableName, trustedConnection, _
        userName, password)
    tdf.SourceTableName = remoteTableName
    CurrentDb.TableDefs.append tdf

End Sub
Private Function SqlServerConnection(serverName As String, dbName As String, targetTable As _
String, Optional trustedConnection As Boolean = True, Optional userName As String = "", Optional _
password As String = "") As String

    Dim result As String
    result = "ODBC;DRIVER=SQL Server;SERVER={server};DATABASE={db};"
    result = result & "PACKET SIZE=4096;PERSIST SECURITY INFO=False"
    result = result & ";TABLE={table}"
    If trustedConnection Then
        result = result & "Trusted_Connection=Yes;"
        result = result & "UID={username};PWD={password}"
    End If
    result = Replace$(result, "{server}", serverName)
    result = Replace$(result, "{db}", dbName)
    result = Replace$(result, "{table}", targetTable)
    result = Replace$(result, "{username}", userName)
    result = Replace$(result, "{password}", password)

    SqlServerConnection = result

End Function