Link Table via DAO

时光总嘲笑我的痴心妄想 提交于 2019-12-02 00:25:02

Take a closer look at how you're examining the table names in CurrentDb. This line throws error #13, "Type mismatch", on my system:

Msgbox tbl

I think you should ask for the TableDef.Name instead:

Msgbox tbl.Name

However, I'm not sure that's the only problem here. You seem to be trying to link to a table in another db file by copying that TableDef and adding it to CurrentDb.TableDefs. IF you can make that work, it won't give you a link to the source table, it would make a new copy in CurrentDb. But I'm skeptical whether it can work at all.

You could create a new TableDef object, set its Name, Connect, and SourceTableName properties, then append it to CurrentDb.TableDefs. Include the database password in the Connect property.

Here is code tested in Access 2007.

Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Dim strDbFile As String
Dim strLinkName As String
Dim strPassword As String
Dim strSourceTableName As String

strDbFile = "C:\share\Access\MyDb.accdb"
strPassword = "foo"
strSourceTableName = "Contacts"
strLinkName = "link_to_contacts"

strConnect = "MS Access;PWD=" & strPassword & _
    ";DATABASE=" & strDbFile
Debug.Print strConnect
Set db = CurrentDb
Set tdf = db.CreateTableDef
tdf.Connect = strConnect
tdf.SourceTableName = strSourceTableName
tdf.Name = strLinkName
db.TableDefs.Append tdf
Set tdf = Nothing
Set db = Nothing

Tables and queries share the same name space in MS Access. Chances are you have a query with the same name as the table you are trying to link.

Also, Environ("username") is easily spoofed. Consider using the API function GetUserName instead. Of course, if you need real security you'll want to upgrade your back-end to SQL Server (Express) or some other RDBMS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!