如何通过 ODBC 将表与 VBA 代码链接

tes*_*sto 4 ms-access

实际上,我使用 ODBC 连接将 Ms Acces 连接到 PostgreSQL-DB 的表。我使用外部数据/导入 ODBC-Link 命令连接它们。效果很好。

但是如何使用 VBA 链接我的表呢?

Jer*_*son 5

使用 VBA 将表与 ODBC 链接时,您可以添加APP=参数来指定应用程序名称,该名称通常会显示在数据库服务器上的连接属性中。

例如,以下是链接表的 ODBC 连接字符串示例:

ODBC;Driver={SQL Server};Server=MyServer\SQLExpress;Database=MyDatabase;APP=My App Title;Trusted_Connection=Yes;
Run Code Online (Sandbox Code Playgroud)

My App Title是将作为该连接的应用程序名称的字符串。

更新 1为了回应 OP 的进一步评论:

以下是在 VBA 中通过 ODBC 链接表的示例代码。为了实现这一点,您还应该在每次重新链接之前删除 ODBC 链接表,以确保您的选项得到尊重,并且 Microsoft Access 更新链接表的架构。此示例显示了 SQL Server 数据库的连接字符串,因此您需要更改的只是 PostgreSQL-DB 的连接字符串。其余的 VBA 代码是相同的。

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
Run Code Online (Sandbox Code Playgroud)