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

问题描述 投票:0回答:1

实际上我使用ODBC-Connection将Ms Access连接到PostgreSQL-DB的表。我使用外部数据/导入ODBC-Link命令连接它们。它工作正常。

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

ms-access
1个回答
1
投票

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

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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.